JQuery- Fast Development Reference.

Syed Khizaruddin
Frontend Weekly
Published in
11 min readOct 9, 2019

--

This is just for quick reference to JQuery for developers.

Hope this helps you.

JQUERY is a Javascript Library, small and easy to learn and use,

There are many library which are dependent on JQuery like for example bootstrap.

lets begin development
Photo by Danielle MacInnes on Unsplash

SOME Common JQuery functions:

$('.red-box').fadeIn(3000);
$('.red-box').fadeOut(3000);
$('.red-box').fadeTo(3000, 0.5);

fadeTo makes element transparent to an amount of opacity given in the second parameter.

fadeIn and fadeOut makes an element’s style to display none.

fadeIn and fadeOut in combination with fadeTo are of no use, as fadeIn or fadeOut will make element display to none and applying fadeTo will make the opacity to the intensity of what we have given in fadeTo function, and hence it will not be seen, as it is already hidden, due to display none by fadeIn or fadeOut function.

$('.red-box').fadeToggle(3000);

fadeToggle will make visible content invisible and vice versa.

It makes display none to display block or vice versa.

$('.red-box').hide();

Hide will make selected element not to appear in DOM, it makes elements style as display none;

$('.red-box').hide(3000);

Hide with 3000 will animate and hide a selected element on the duration of 3000 i.e. 3sec.

$('.red-box').show();

Show element will show the hidden element, it makes the element’s style as a display block.

$('.red-box').show(3000);

Similar to hiding rather it will show element with animation of duration 3000 milliseconds.

$('.red-box').slideUp(3000);

the slide will make the selected element to fade Upwards and eventually hide it making the CSS to display none In a duration of 3000 milliseconds.

slideDown will make the selected element to fade downwards and eventually hide it making the CSS to display none on the duration of 3000 milliseconds

$('.red-box').slideToggle(3000);

It does same as fadeToggle just the animation is seen sliding.

$('.red-box').animate({
'margin-left': '+=200px'
}, 3000, 'linear');

Custom animation uses the animate function of jQuery

It takes an object having key-value pair which is used for changing the value or applying animation on certain CSS the third argument it takes is animation style by default it is set to swing but we can change it as per our need.

The second argument is the time in milliseconds.

We can also give JavaScript kind of styling in an object like

$('.red-box').animate({
marginLeft: '+=200px',
},3000, 'linear');

We cannot use the color in animate function.

$('.red-box').delay(3000).fadeTo(3000, 0.5);

We can use multiple functions by chaining it one after another and the execution will be from left to right,

delay function takes time as an argument in milliseconds, so that it can wait for that much seconds and then fadeTo will be called.

Callback function on completion of animation:

Every function till now takes the third argument is a callback function which is called when the animation has been finished.

fadeIn, fadeout, fadeToggle, slideDown, slideToggle, slideUp etc. takes callback function.

Selectors:

$('p').css('background-color','red');

change background color of all p tags to red.

$('.red-box').css('background-color', 'green');

change background color of all red-box classes to green.

$('#list').css('background-color', 'green');

change background color to green of the element of id list.

$('input[type="text"]').css('background-color', 'green');

changing background color to green of input type text.

$(h2, p, input').css('background-color', 'green');

changing background color to green of h2 p and all input tags.

$('p:first').css('background-color', 'green');

changing first paragraph tag’s background color to green.

$('p:last').css('background-color', 'green');

changing last paragraph tag’s background color to green.

$('li:last').css('background-color', 'green');

changing last li tag’s background color to green.

$('li:even').css('background-color', 'green');

changing even li tag’s background color to green.

$('li:odd').css('background-color', 'green');

changing odd li tag’s background color to green.

$('input:text').css('background-color', 'green');

changing input type text’s background color to green.

$('input:selected').css('background-color', 'green');

changing background color to green of input which is selected.

$('input:checked').css('background-color', 'green');

changing input which is checked background color to green.

DOM TRAVERSING:

$('#list').find('li').css('background-color', 'red');

find function will find an element given in the find function respective to the selected element.

i.e. the “#list” is selected element and find will find all li elements inside “#list ” element, it will select all elements irrespective of hierarchy.

i.e.

<p id=”list”>
<ul>
<li>first li</li> <! — this is selected-->
<li>
<li></li> <!-- this is selected -->
</li> <! — this is selected — >
</ul>
</p>

and all grand children as well, till it cannot find any li tags.

$('#list').children('li').css('background-color', 'red');

Children will select direct children of a selected element(“#list”) only one level hierarchy i.e. direct children of “#list” i.e. li, only that li will be selected and rest all children and grand children will be rejected.

$('#list').parents('div').css('background-color', 'red');

Parents will select all parent element of the selected element and passing div will select only div elements from all parents.

$('#list').parent().css(‘background-color', ‘red’);

Parent will select the direct parent element of the selected element and not grand parent or great grand parents.

$('#list').siblings('p').css('background-color', 'red');

Siblings will select all the sibling elements i.e. elements next to selected element that share same or common parent element

$('#list').siblings(":header").css('background-color', 'red');

This will select only those element which comes under header.

$('#list').next().css('background-color', 'red');
$('#list').prev().css('background-color', 'red');

Next and prev will select elements which are next to the selected element or previous to the selected element.

$('#list').find('li').filter(':even').css('background-color', 'red');

This filter element will filter out all even items from the selected elements

We can use,

$('li').filter(function(index){
return index;
)}.css('background-color': '#fcfcfc');

This function will return the index of all elements selected and we can use it wherever we want.

Like we have used it for adding CSS to every element.

$('li').first().css('background-color','red');

This will select only the first li element,

Same as,

$('li:first').css('background-color', 'red');
$('li').last().css('background-color','red');

This will select only the first li element.

Same as,

$('li:last').css('background-color' , 'red');
$('li').eq(0).css('background-color','red');

This will select first element

eq() function is equivalent function

It takes 012345 as an argument as per our choice of selection

0 will select the first element

1 will select the second element and so on.

Negative numbers will count from back

So, -1 is the last element -2 is the second last element and so on.

$("li").not("first").css('background-color','red');

This will select everything from selected element but not the first element.

$("ul ul:first").append("<li> this is appended</li>");

DOM MANIPULATION:

append function adds HTML after the element which is selected if multiple elements are selected then HTML will be inserted into each and every selected element.

$("<li> this is appended </li>").appendTo($("ul ul:first"));

This will do the same with a different approach.

$("ul ul:first").prepend("li> this is prepended</li>");

Prepend will add HTML before the selected element.

$("<li> this is prepended </li>").prependTo("ul ul:first");

This will add HTML before the selected element different approach.

$(".red_box").after("<div class='red_box'> this is another red box</div>");

This will add a next sibling element to the selected element and if multiple elements are selected it will add next sibling to every selected element.

Similarly, we can add the previous sibling to the selected element using before function.

$(".red_box").before("<div class='red_box'> this is another red box</div>");

All these dom-manipulation functions take anonymous function

Like below,

$(".red_box").before(function(){
return "<div> this is returned</div>";
});
$("<li> this is added by JQuery</li>").before("ul ul:first");

This will do the same thing but with a different approach.

$("li").replaceWith("<li>this is replaced </li>");

replaceWith function allows to replace selected element with HTML passed to it.

It can take an anonymous function.

$("li").replaceWith(function(){
return "<li>this is replaced </li>";
});
var firstItem = $("li:first");
$("p").replaceWith(firstItem);
$(".red_box, .blue-box").replaceWith("<div class='green-box'>more green</div>");

Different approach same result:

$("<div class='green-box'>more green</div>").replaceAll(".red_box, .green-box");

Remove element from the DOM:

$("li").remove();

Removing elements from the form which is not input Textarea and br tag and are direct children of form

$("#form").children().not("input, textarea, br").remove();

Detaching an element and reinserting in a fresh position.

var detachedListItem = $("li").detach();
$("#content").append(detachedListItem);

This removes the element with event listeners and safely attach using the append function with event listeners.

This thing can be done with remove function.

But using remove all event listeners associated with that element will be lost.

Using detach saves event listeners associated with that element.

$("p").empty();

It clears text content, HTML stylings etc. inside the selected element.

attr(), prop(), val()

HTML:

<a href="https://www.google.com">google</a>

JQuery:

var link = $("a").attr("href");

The attr function takes the attribute value of a selected element and can change it if we give value in second element.

Hence the value of link will be: https://www.google.com

<input type="checkbox" checked>
var prop = $("input:checkbox").prop();

The prop function takes the property value of the selected element

Hence the value of prop will be: checked.

<input type="text" value="this is the value" />
var value = $("input:text").val();

The val function takes (value property)’s value of the selected element.

We can set the attribute property and value property of an element using the same function by giving the second argument as the desired value you want to set.

For example:

$("a").attr("href", "https://www.facebook.com");
$("input:checkbox").prop("checked");
$("input:text").val("this is updated value");

These functions will not update all elements if there are multiple selections rather it will select only the first element and it will be updated.

$("p").css("width");

This will return the width defined by CSS applied to the element

$("p").css("color", "red");

CSS function can be used to either retrieve the CSS applied or to apply CSS to the selected element.

var pTagProperties = $("p").css(["font-size", "color", "background-color"]);
console.log(pTagProperties["font-size"]);

We can give multiple properties to know their values in the form of an array i.e. inside square brackets.

If we want to apply multiple CSS styles through jQuery we pass key-value pairs in curly brackets called as objects or JSON format.

Like below:

$("p").css({
"font-size": "1rem",
"color": "red",
"text-align": "center"
});

We can use an anonymous function inside the CSS function.

Like below

$("p").css("text-align", function(){
return "center";
});

ADDING REMOVING TOGGLING CLASSES:

$("p").addClass("fancy-link");

This will add a CSS in the selected element.

We can add multiple classes in the same element as below

$("p").addClass("large-text emphasis");

We can use an anonymous function with addClass.

$("p").addClass(function(index){
return "item-"+ index;
});

This will add item-0 to first element item-1 to the second element as a class name and so on.

This anonymous takes 2nd argument as the current class name

So we can use it as,

$("div").addClass(function(index, currentClass){
if( currentClass === "anycurrentclass") {
return "red_box";
}
});
$("p").removeClass("red-box");

This will remove the red-box class from the selected element.

We can chain it to add another class as below.

$("p").removeClass("red-box").addClass("blue-box");

If we want to toggle class i.e. add when not present and remove when present we can use toggleClass function

$("p").toggleClass("display-none");

This function will add display-none in class if not present and remove display-none from class if present in the selected element.

Data attribute:

<p data-name="this is data">hello text</p>
console.log($("p").data("name"));

This will output ~> this is data in console.

The data attribute is used to get the data attribute specified in the selected tag.

We can set the data value of the selected element using the second parameter of the function.

As shown below,

$("p").data("name", "this is data");
$("p").html("<strong> this is added as HTML code</strong>");

Output:

this is added as HTML code.

$("p").text("<p>this is added as simple text</p>");

Output:

<p>this is added as simple text</p>

The HTML function is used to add some HTML working tags inside the selected element.

Whereas text function is used to add only the text content inside the selected element.

In-text function, if we give HTML tags it will be seen as a plain text but if we give HTML tags in HTML function it will be parsed by the browser and it will work as HTML code works in a browser.

$("button-click").click(function(){
alert("the button was clicked");
});

a click function is an event handler to the mouse click on the selected element and it takes anonymous function inside which we can give tasks to perform while executing the click.

Here, an alert will be opened as a popup showing the button was clicked.

$(".btn.btn-primary").hover(function(event){
alert("button was hovered");
});

The hover function is triggered when we take the cursor pointer to the selected element.

the alert function will be called twice because the function will be triggered 2 times first on mouse pointer entering the selected element and when mouse pointer leaving the selected element.

Hence we can use the second parameter for handlerOut and first parameter for handlerIn

So,

$(".btn.btn-primary").hover(function(){
alert("I was triggered while entering");
}, function(){
alert("I was triggered while leaving");
});

Or we can use mouseenter function and mouseleave functions

$(".btn.btn-primary").mouseenter(function(){
$(this).fadeTo(500, 0.5);
});
$(".btn.btn-primary").mouseleave(function(){
$(this).fadeTo(500, 1);
});

The “this” keyword is used to specify the currently selected element.

Here if we hover fast i.e. in and out of element for a couple of times, even when the hovering is stopped the animation still continues.

In order to fix it, we use stop() function to stop current animations

$(".btn.btn-primary").mouseenter(function(){
$(this).stop().fadeTo(500, 0.5);
});
$(".btn.btn-primary").mouseleave(function(){
$(this).stop().fadeTo(500, 1);
});
$("html").on("click keydown", function(){
alert("clicked or key pressed");
});

In order to apply multiple events on the selected element, we use on function with multiple events and an anonymous function for handling the events.

Modularizing code when the anonymous function is too long.

We can code like this if code is becoming complex.

$(".btn").on("click", triggerAlert);
function triggerAlert(){
alert(“hello”);
}

Event delegation:

When we add HTML dynamically through HTML function or append function we are unable to perform any events on it.

So, to solve this problem we have an event delegation.

In this, we select the parent element of the element we are going to append dynamically.

As below,

$('#content').html("<p> this is paragraph</p>");

added element dynamically

$("#content").on("click", "p", function(){
$(this).slideUp();
});

Here “this” is referred to all p elements of parent “#content” element.

So if we add p element dynamically we can have the click event on it as well.

Passing data to events:

$(".btn").on("click", {
user: "Peter",
domain: "www.google.com"
}, function(){
greetUser(event.data);
});

function greetUser(userdata){
let name = userdata.user;
let domain = userdata.domain;
alert("welcome " + name + " from "+ domain);
}

On function takes a first optional argument is an object which can be used as data we want to show or use on the specified event using event.data

Keyboard events:

Keypress function is evil as it has no documentation must not use.

The keydown function is called when the key is pressed.

There is keyup function as well which is triggered when the key is released after pressing.

Every key has its keycode, to know we have event.which to get the keycode

$("html").keydown(function(event){
console.log(event.which);
});
var inputFields = $("input:text, input:password, textarea");

inputFields.focus(function(){
$(this).css("box-shadow", "0 0 4px #666");
});
inputFields.blur(function(){
$(this).css("box-shadow", "none");
});

the focus event is fired when we select the input element.

the blur event is fired when we unselect the selected input element.

$("#checkbox").change(function(){
$(this).css("box-shadow", "0 0 4px #181");
});

Change function event is triggered when there is a change in the selected element.

Change can be the change in value attribute or state of the selected element.

To get whether the checkbox is selected or not we use.

$("#checkbox"). change(function(){
if($(this).is(":checked"){
console.log("checked");
}
});

Form submit event function:

$("#form").submit(function(){
var textInput = $("#form input:text").val().trim();
if(textInput !== "") {
textInput.css("box-shadow", "0 0 4px #181");
event.preventDefault();
}
});

Submit event function is fired when we try to submit a form by clicking the submit button.

Mainly it is used to validate form inputs.

event.preventDefault() function is used to block the default behaviour of that particular event.

Here we are blocking submit event when the input text is empty string.

TLDR;

Please to clap if you find it helpful,

Comment if you have any issues,

Follow my Twitter account from here.

Buy me a coffee here

--

--