The jQuery library makes it easy to manage the HTML page after it is displayed by the browser. It also provides tools to help you create animations on your page, and tools that allow you to communicate with the server without reloading the page.
Working with jQuery Functions
JavaScript is a fairly low-level programming language. It does not provide advanced controls and animations. Moreover, using direct JavaScript can cause browser incompatibility issues.
JQuery, the popular open source JavaScript library, provides many advanced cross-browser jQuery features that can enhance your web applications. This article starts with the basics and then shows how to extend jQuery using your system.
JQuery is a JavaScript library, so installation is just a matter of importing a script inside a web page. However, there are several recommendations to consider:
- The jQuery library is available via CDN. Using CDN instead of installing jQuery on your servers should provide significant performance and increase throughput.
- Like any static content, jQuery files must be compressed. That's why two versions of jQuery are available: a minimal (or minimized) version, small and efficient, and a development version that is easier to read and debug. For the rest of this article, we will use the minimum version, which is enough for our needs.
- JQuery library files must be cached on the client side, so you must use the jQuery version number in the file name.
JQuery elements
The easiest way to get started with jQuery is to select some elements from our web page.
$ ( ' # author ' )
$ is not a keyword for JavaScript. This is a one-letter function defined by jQuery. The text passed to this function is parsed by jQuery, which then generates the correct series of JavaScript functions to select Document Object Model (DOM) elements. This method of selecting DOM elements is concise and browser independent, which addresses the two most important issues that arise when programming JavaScript. As a result, jQuery provides a quick, easy, and efficient cross-browser selection of DOM nodes on a web page.
Of course, an identifier is not the only way to select items. You can use the element class or some properties of these elements. For example, you can select all elements with a class:
$( ' .vote ' ); <script type="text/javascript"> $(document).ready(function() { var id = $("#author").text(); }); </script>
This task illustrates common good practice with jQuery: the $ (document) .ready () function starts when the web page is ready and loads at the end of the page. From the user's point of view, this means that the whole page loads normally, and then jQuery is used to improve the page.
Using the previous code, the identifier will be read at startup. You can verify this using the JavaScript alert () function.
Manage Webpage Elements
After the HTML elements have been selected, you will certainly need to manage them by changing their CSS class, adding text, or even completely replacing them. JQuery provides functions for all these tasks.
A use case that can be implemented is to replace the identifier that was previously selected. With this information: author name, surname of the author and URL. At the moment, this information will be stored statically inside JavaScript code. Here is information that can be temporarily encoded in JavaScript code:
function Author(id, firstName, lastName, url) { this.id = id; this.firstName = firstName; this.lastName = lastName; this.url = url; } var author = new Author("1", "Julien", "Dubois");
Since the identifier is known, you can select the <div> element, and replace the text from this element:
$("#author").replaceWith("Author: <b>" + author.firstName + " " + author.lastName + "</b><br/>" + "website: <a href=\"" + author.url + "\"> + author.url + "</a>");
JQuery provides many other functions for modifying an HTML element. For example, you can make an element appear or disappear using the show () and hide () functions . An alternative way would be to change the CSS class used by the element; for this, jQuery provides functions for adding a class, deleting a class, or checking for a class.
Now that the identifier has been replaced by information, try to display this information.
Animation with jQuery
Add some animations. JQuery provides a rich set of animations that provides a smooth user interface. You can test all animations on the official website.
Of course, if you abuse the animation, then the resource will become difficult to use. Therefore, you need to find the right balance in order to have a beautiful website.
Let's go back to the example. For example, let's choose a simple slide animation:
$ ("# author-wrapper"). slideDown ("slow");
Using animation with AJAX is very important from a user perspective:
- The animation hides the fact that some requests take time to process on the server side.
- Animations draw the user's attention to what is changing on the web page. Without animation, the user may not notice that part of the page has changed.
Features of jQuery Functions
Functions are a way of executing a set of behavior scenarios, and depending on the function they may even take different arguments.
The jQuery function call is defined using the function keyword. Then it must be followed by the name of the function, a comma-separated list of arguments enclosed in parentheses, and, if necessary, a JavaScript operator. JQuery function parameters, enclosed in braces {}.
function sayHello(name) { return('Hello ' + name); }
In many cases, you can replace many lines of your own JavaScript programming (and the clock needed to test them) with a single function from the JavaScript library.
If necessary, write a simple function multiply (x, y), which simply takes two parameters x and y, performs simple x times y is equal to something, and returns a value. Here is one way to do this:
function multiply(x,y) { return (x * y); } console.log(multiply(2,2));
If you need a utility to get / set / delete values, you can declare the function as a variable like this. This can be useful for assigning a variable in the declaration computed by the function.
var multiply = function(x,y) { return (x * y); } console.log(multiply(2,2));
Below are a few more jQuery functions.
Adding content to a page
jQuery provides functions for managing elements and content on the page, simply replacing HTML to accurately position the new HTML in relation to the selected element, completely remove tags and content from the page.
The js jQuery .html () function can read the current HTML inside an element and replace the current content with other HTML code. Use the .html () function in conjunction with jQuery selection. To get the HTML inside the selection, just add:
.html ()
After choosing jQuery. For example, you can run the following command using the HTML snippet at the beginning of this section:
alert($('#errors').html());
This code creates a warning window with the text "<h2> Errors: </ h2>" in it. Using the html () function will allow you to make a copy of the HTML inside a specific element and paste it into another element on the page.
.text () works like .html (), but it does not accept HTML tags. This is necessary when replacing text in a tag.
$('#errors h2').text('No errors found');
The <h2> tag remains in place; only the text inside is changed.
.append () adds HTML as the last child of the selected item. For example, let's say you select the <div> tag, but instead of replacing the contents of the <div>, you just want to add some HTML before the closing </ div> tag. The .append () function is a great way to add an item to the end of a bulleted (<ul>) or numbered (<ol>) list.
$('#errors').append('<p>There are four errors in this form</p>');
.prepend () is exactly the same function as. append () , but adds HTML immediately after opening the tag for selection. For example, let's say you run the following code in the same HTML that you specified earlier:
$('#errors').prepend('<p>There are four errors in this form</p>');
Replacing and deselecting
Sometimes you can completely replace or remove a selected item. For example, suppose you create a popup dialog using JavaScript. When a visitor clicks the Close button in a dialog box, you naturally want to remove the dialog box from the page.
You can use the jQuery remove () function for this . Say the popup dialog had a popup ID . You can use the following code to remove it:
$('#popup').remove();
The .remove () function is not limited to just one element. Suppose you want to remove all the <span> tags to which the error class applies. You can do it:
$('span.error').remove();
Anonymous Functions
To use the each () function , you pass it a special argument - an anonymous function. An anonymous function is simply a function that contains the steps you want to perform for each selected item.
It does not contain names. Here is the basic structure of an anonymous function:
function() {
Since there is no name, you have no way to call a function. For example, using a regular jQuery named function, you use its name with a set of parentheses, for example: calculateSalesTax (). Instead, you use an anonymous function as an argument, which you pass to another function (strange and confusing, but true). In jQuery, the execution of each () function looks like this:
$ (' selector') .each ( );function() {}
And in conclusion
This article will help jQuery newbies. jQuery is just a JavaScript library that uses shorthand objects, anonymous functions, and method chains.
Using jQuery, the JavaScript programmer has access to many powerful tools common to desktop and mobile developers, such as creating event handlers and using effects for the responsive user interface, the ability to control your user interface without having to refresh the entire page and creating asynchronous calls to quickly respond to your web applications. With jQuery, you can take your web pages to the next level.