Sunday, June 20, 2021

jQuery Notes

jQuery features

The jQuery library contains the following features:
  • HTML/DOM manipulation
  • CSS manipulation
  • HTML event methods
  • Effects and animations
  • AJAX
  • Utilities

The element Selector

The jQuery element selector selects elements based on the element name.
You can select all <p> elements on a page like this:
$("p")

Event Handler

The next step is to define what should happen when an event fires on an element. You must pass a function to handle the event. The event handler method is an anonymous function which is passed as parameter into the action method such as click etc.

$("p").click(function(){
  // action goes here!!
});


Event handler Example: When a user clicks on a button, all paragraph elements of the document will be hidden when the following code is executed.


$(document).ready(function(){
  $("button").click(function(){
    $("p").hide();
  });
});

jQuery Methods

Following methods are covered in this tutorial.
  • hide
  • show
  • stop
  • text
  • html
  • val
  • append
  • prepend
  • after
  • before
  • remove
  • addClass
  • removeClass
  • toggleClasselements
  • css

jQuery hide() and show() methods: With jQuery, we can hide and show HTML elements with hide() and show() methodsSyntax of the methods are as follows.

$(selector).hide(speed, callback);
$(selector).show(speed, callback);

Both speed and callback are optional parameters. The speed parameter specifies the speed of the hiding or showing, and can take the values- "slow", "fast", or milliseconds. The callback parameter is a function to be executed after the hide() or show() method completes (you will learn more about callback functions ahead).

Simple hide and show examples


$("#hide").click(function(){
  $("p").hide();
});

$("#show").click(function(){
  $("p").show();
});

The following example demonstrates the speed parameter with hide() method.

Example to hide paragraph elements with 1000 milliseconds speed:

$("button").click(function(){
  $("p").hide(1000);
});

Stop animation using stop() method: The jQuery stop() method is used to stop an animation or effect before it is finished. The stop method works for all jQuery effect functions, including sliding, fading and custom animations. The syntax is as follows.
$(selector).stop(stopAll, goToEnd);

Both stopAll and goToEnd are optional Boolean parameters. The stopAll parameter specifies whether the animation queue should be cleared or not. The default is false, which means that only the active animation will be stopped, allowing any queued animations to be performed afterwards. The goToEnd parameter specifies whether or not to complete the current animation immediately. The default value is false. So, by default, the stop() method kills the current animation being performed on the selected element.

Example of stop() method: The following example demonstrates the stop() method, with no parameters:

$("#stop").click(function(){
  $("#panel").stop();
});

Callback Functions:JavaScript statements are executed line by line. However, with effects, the next line of code can be run even though the effect is not finished. This can create errors. To prevent this, you can create a callback function. A callback function is executed after the current effect is finished.

Typical syntax: $(selector).hide(speed, callback);

The example below has a callback parameter that is a function that will be executed after the hide effect is completed:

Example with callback parameter

$("button").click(function(){
  $("p").hide("slow", function(){
    alert("The paragraph is now hidden");
  });
});

Example without callback parameter

$("button").click(function(){
  $("p").hide(1000);
  alert("The paragraph is now hidden");
});

Methods Chaining

With jQuery, you can chain together actions/methods. Chaining allows us to run multiple jQuery methods (on the same element) within a single statement. Until now we have been writing jQuery statements one at a time (one after the other). However, there is a technique called chaining, that allows us to run multiple jQuery commands, one after the other, on the same element(s). Tip: In this way, browsers do not have to find the same element(s) more than once.

To chain an action, you simply append the action to the previous action.

The following example chains together the css(), slideUp(), and slideDown() methods. The "p1" element first changes to red, then it slides up, and then it slides down:

Example

$("#p1").css("color", "red").slideUp(2000).slideDown(2000);
We could also have added more method calls if needed.

Tip: When chaining, the line of code could become quite long. However, jQuery is not very strict on the syntax; you can format it like you want, including line breaks and indentations. The following works fine.

$("#p1").css("color", "red")
  .slideUp(2000)
  .slideDown(2000);

DOM Manipulation

jQuery contains powerful methods for changing and manipulating HTML elements and attributes. One very important part of jQuery is the possibility to manipulate the DOM. jQuery comes with a bunch of DOM related methods that make it easy to access and manipulate elements and attributes.

Set or get content using text(), html(), and val() methods
Three simple, but useful, jQuery methods for DOM manipulation are:
  • text() - Sets or returns the text content of selected elements
  • html() - Sets or returns the content of selected elements (including HTML markup)
  • val() - Sets or returns the value of form fields
Example of text method: The following example demonstrates how to get content with the jQuery text() and html() methods.

$("#btn1").click(function(){
  alert("Text: " + $("#test").text());
});
$("#btn2").click(function(){
  alert("HTML: " + $("#test").html());
});

Example of val method: The following example demonstrates how to get the value of an input field with the jQuery val() method.

$("#btn1").click(function(){
  alert("Value: " + $("#test").val());
});

Set content using text(), html(), and val() methods
We will use the same three methods from the previous page to set content. The following example demonstrates how to set content with the jQuery text(), html(), and val() methods.

Example

$("#btn1").click(function(){
  $("#test1").text("Hello world!");
});
$("#btn2").click(function(){
  $("#test2").html("Hello world!");
});
$("#btn3").click(function(){
  $("#test3").val("Dolly Duck");
});

A Callback Function for text(), html(), and val()
All of these three jQuery methods text(), html(), and val(), also come with a callback function. The callback function has two parameters: the index of the current element in the list of elements selected and the original (old) value. You then return the string you wish to use as the new value from the function. The following example demonstrates text() and html() with a callback function:

Example of Callback Function

$("#btn1").click(function(){
  $("#test1").text(function(i, origText){
    return "Old text: " + origText + " New text: Hello world!
    (index: " + i + ")";
  });
});

$("#btn2").click(function(){
  $("#test2").html(function(i, origText){
    return "Old html: " + origText + " New html: Hello world!
    (index: " + i + ")";
  });
});

With jQuery, it is easy to add new elements/content.

Add new HTML content
We will look at four jQuery methods that are used to add new content:
  • append() - Inserts content at the end of the selected elements
  • prepend() - Inserts content at the beginning of the selected elements
  • after() - Inserts content after the selected elements
  • before() - Inserts content before the selected elements
append() Method: The jQuery append() method inserts content AT THE END of the selected HTML elements.

Example

$("p").append("Some appended text.");

With jQuery, it is easy to remove existing HTML elements.

Remove Elements/Content
To remove elements and content, there are mainly two jQuery methods.
  • remove() - Removes the selected element (and its child elements)
  • empty() - Removes the child elements from the selected element
remove() Method: The jQuery remove() method removes the selected element(s) and its child elements.

Example1

$("#div1").remove();
The jQuery empty() method removes the child elements of the selected element(s).

Example2

$("#div1").empty();
The jQuery remove() method also accepts one parameter, which allows you to filter the elements to be removed. The parameter can be any of the jQuery selector syntaxes. The following example removes all <p> elements with class="test".

Example3

$("p").remove(".test");
This example removes all <p> elements with class="test" and class="demo":  

Example4

$("p").remove(".test, .demo");

With jQuery, it is easy to manipulate the style of elements.

Manipulating CSS

jQuery has several methods for CSS manipulation. We will look at the following methods:
  • addClass() - Adds one or more classes to the selected elements
  • removeClass() - Removes one or more classes from the selected elements
  • toggleClass() - Toggles between adding/removing classes from the selected elements
  • css() - Sets or returns the style attribute
The following stylesheet will be used for all the examples on this page:


.important {
  font-weight: bold;
  font-size: xx-large;
}

.blue {
  color: blue;
}

addClass() Method: The following example shows how to add class attributes to different elements. Of course you can select multiple elements, when adding classes:

Example1

$("button").click(function(){
  $("h1, h2, p").addClass("blue");
  $("div").addClass("important");
});
You can also specify multiple classes within the addClass() method:

Example2

$("button").click(function(){
  $("#div1").addClass("important blue");
});

removeClass() Method
The following example shows how to remove a specific class attribute from different elements:

Example

$("button").click(function(){
  $("h1, h2, p").removeClass("blue");
});

toggleClass() Method
The following example will show how to use the jQuery toggleClass() method. This method toggles between adding/removing classes from the selected elements:

Example

$("button").click(function(){
  $("h1, h2, p").toggleClass("blue");
});

css() Method
The css() method sets or returns one or more style properties for the selected elements.

Get CSS Property: To return the value of a specified CSS property, use the following syntax:

css("propertyname");
The following example will return the background-color value of the first matched element:

Example

$("p").css("background-color");

Set CSS Property
To set a specified CSS property, use the following syntax:

css("propertyname","value");
The following example will set the background-color value for ALL matched elements:

Example

$("p").css("background-color", "yellow");

Set Multiple CSS Properties
To set multiple CSS properties, use the following syntax:

css({"propertyname":"value","propertyname":"value",...});

The following example will set a background-color and a font-size for ALL matched elements:

Example

$("p").css({"background-color": "yellow", "font-size": "200%"});

No comments:

Post a Comment

Hot Topics