Articles

JQuery, what it is and what we can do with the JavaScript library

jQuery is a fast, lightweight and feature-rich JavaScript library based on the principle “write less, do more” . JQuery APIs simplify the management and maintenance of HTML documents, event management, adding animation effects to a web page. It is compatible with all major browsers such as Chrome, Firefox, Safari, Edge.

Creating an Ajax-based application becomes very simple and fast with jQuery.

jQuery was originally created by John Resig in early 2006. The jQuery project is currently maintained and maintained by a distributed group of developers as an open source project.

You can save a lot of time and effort with jQuery. So add this site to your favorites and continue reading

What you can do with jQuery

There are many more things you can do with jQuery.

  • You can easily select HTML page elements, to read or modify attributes;
  • You can easily create effects like show or hide elements, transitions, scrolls and so on;
  • You can easily create complex CSS animations with fewer lines of code;
  • You can easily manipulate DOM elements and their attributes;
  • You can easily implement Ajax to enable asynchronous data exchange between client and server;
  • You can easily traverse all the DOM tree to locate any element;
  • You can easily perform multiple actions on an element with a single line of code;
  • You can easily get or set the size of HTML elements.

The list doesn't end there, there are many other cool things you can do with jQuery.

Benefits of using jQuery

There are several advantages why one should opt for using jQuery:

  • Save a lot of time: You can save a lot of time and effort by using jQuery's built-in effects and selectors and focus on other aspects of development;
  • Simplify common JavaScript tasks - jQuery greatly simplifies common JavaScript tasks. Now you can easily create feature-rich and interactive web pages, with fewer lines of code. The typical example is the implementation of Ajax to refresh the content of a page, without refreshing it;
  • Simplicity: jQuery is very easy to use. Anyone with a basic working knowledge of HTML, CSS, and JavaScript can start developing with jQuery;
  • Compatible with all browsers: jQuery was created with modern browsers in mind and is compatible with all major modern browsers such as Chrome, Firefox, Safari, Edge;
  • Absolutely Free – And the best part is that it's completely free to download and use.

jQuery download

To get started, let's first download a copy of jQuery and then include it in our project. Two versions of jQuery are available for download: tablet e not compressed .

The uncompressed file is better suited for development or debugging; while, the minified and compressed file is recommended for production because it saves bandwidth and improves performance due to the smaller file size.

We can download jQuery from here: https://jquery.com/download/

Once you download the jQuery file you can see that it has a js extension, i.e. it is a JavaScript file. In fact JQuery is nothing but a JavaScript library, so you can include the jQuery file in the HTML document with the element just like you include regular JavaScript files.

<head>
    <title>Simple HTML Document</title>
    <link rel="stylesheet" href="css/style.css">
    <script src="js/jquery-3.6.3.min.js"></script>
</head>
<body>
    <h1>Hello, World!</h1>
</body>
</html>

Remember to always include the jQuery file before custom scripts; otherwise, the jQuery APIs won't be available when your jQuery code tries to access them.

As you may have noticed, we skipped the attribute in the previous example type="text/javascript" inside the tag . Infatti questo non è richiesto in HTML5. JavaScript è il linguaggio di scripting predefifinished in HTML5 and in all modern browsers.

jQuery from CDN

As an alternative, you can embed jQuery into your document via freely available CDN (Content Delivery Network) links, if you'd rather avoid downloading the file.

CDNs can offer a performance advantage by reducing load time, because they host jQuery on multiple servers around the world, and when a user requests the file, it will be served from the closest server.

This also has the advantage that if your web page visitor has already downloaded a copy of jQuery from the same CDN while visiting other sites, they won't have to download it again since it's already in their browser's cache.

In this case you will have to write:

<script src =" https://code.jquery.com/jquery-3.6.3.min.js "> </script>

In addition to the CDN provided by the jquery project, you can include jQuery via Google e Microsoft CDN.

First web page based on jQuery

Having seen the goals of the jQuery library and how to include it in your document, now is the time to put jQuery into practice.

Now let's do a simple jQuery operation by changing the header text color from the pre colordefinished black to green color.

<head>
    <title>My First jQuery Web Page</title>
    <link rel="stylesheet" href="css/style.css">
    <script src="js/jquery-3.6.3.min.js"></script>
    <script>
        $(document).ready(function(){
            $("h1").css("color", "#00ff00");
        });
    </script>
</head>
<body>
    <h1>Hello, World!</h1>
</body>
</html>

In the code we performed a simple jQuery operation by changing the color of the header i.e. the element using the jQuery element's selector and css() method when the document is ready, known as the document ready event. 

jQuery syntax

A jQuery statement usually starts with a dollar sign ( $) and ends with a semicolon ( ;).

In jQuery, the dollar sign ( $) is just an alias for jQuery. Consider the following sample code demonstrating the simplest jQuery statement.

<script>
    $(document).ready(function(){

        alert("Hello I'm a JQuery sign");
    });
</script>

The example simply displays a warning message “Hello I'm a JQuery sign” to the user. Let's see some features:

  • The element <script>: jQuery is just a JavaScript library, jQuery code can be placed inside the element <script>, or you can put it in an external JavaScript file;
  • The line $(document).ready(handler); is known as a ready event. Where is it handler it is a function that is passed to the method to be executed, as soon as the document is ready, i.e. when the DOM hierarchy has been completely built.

The jQuery method ready() it is usually used with an anonymous function. So, the example above can also be written in shorthand notation like this:

<script>
    $(function(){
        alert("Hello I'm a JQuery sign");
    });
</script>

Selectors

Inside a function you can write jQuery statements to perform any action following basic syntax, like:

$(selector).action();

Where is it, $(selector) it basically selects the HTML elements from the DOM tree so it can be manipulated and action() apply some actions on the selected elements, such as changing the value of the CSS property, or setting the content of the element, etc.

Now let's look at another example that sets paragraph text:

<head>
    <title>jQuery Demo</title>
    <link rel="stylesheet" href="css/style.css">
    <script src="js/jquery-3.6.3.min.js"></script>
    <script>
        $(document).ready(function(){
            $("p").text("Hello World!");
        });
    </script>
</head>
<body>
    <p>Not loaded yet.</p>
</body>
</html>

The jQuery example refers to the selector p, and this selects all the paragraphs, then the method text() set the text content of the paragraph with “Hello World!".

The paragraph text in the previous example is automatically replaced when the document is ready. But let's see how to do it in case you want to perform an action before running the jQuery code, to replace the text of the paragraph. 

Let's consider one last example:


<head>

    <title>jQuery Demo</title>
    <link rel="stylesheet" href="css/style.css">
    <script src="js/jquery-3.6.3.min.js"></script>
    <script>
        $(document).ready(function(){
            $("button").click(function(){
                $("p").text("Hello World!");
            });            
        });
    </script>
</head>
<body>
    <p>Not loaded yet.</p>
    <button type="button">Replace Text</button>
</body>
</html>

In this example the paragraph text is replaced only when a click event occurs on the button "Replace Text“, which simply means when a user clicks this button.

Selecting items by ID

You can use the ID selector to select a single item with the unique ID on the page.

For example, the following jQuery code will select and highlight an element with the ID attribute id="markid", when the document is ready.

<script>
$(document).ready(function(){
    // Highlight element with id markid
    $("#markid").css("background", "grey");
});
</script>
Selecting elements with class name

The class selector can be used to select elements with a specific class.

For example, the following jQuery code will select and highlight elements with the class attribute class="markclass", when the document is ready.

<script>
$(document).ready(function(){
    // Highlight elements with class markclass
    $(".markclass").css("background", "grey");
});
</script>
Selecting items by name

The item selector can be used to select items by item name.

For example, the following jQuery code will select and highlight all the paragraph, i.e. the elements "<p>" of the document when it is ready.

Innovation newsletter
Don't miss the most important news on innovation. Sign up to receive them by email.
<script>
$(document).ready(function(){
    // Highlight paragraph elements
    $("p").css("background", "grey");
});
</script>
Selection of elements by attribute

You can use the attribute selector to select an element based on one of its HTML attributes, such as a link attribute targetor the attribute of an input type, etc.

For example, the following jQuery code will select and highlight all text inputs, such as elements "<input>" with type="text", when the document is ready.

<script>
$(document).ready(function(){
    // Highlight paragraph elements
    $('input[type="text"]').css("background", "grey");
});
</script>
Element selection via compound CSS selector

You can also combine CSS selectors to make your selection even more precise.

For example, you can combine the class selector with an element selector to find elements in a document that have a certain type and class.

<script>
$(document).ready(function(){
    // Highlight only paragraph elements with class mark
    $("p.mark").css("background", "yellow");
  
    // Highlight only span elements inside the element with ID mark
    $("#mark span").css("background", "yellow");
  
    // Highlight li elements inside the ul elements
    $("ul li").css("background", "red");
  
    // Highlight li elements only inside the ul element with id mark
    $("ul#mark li").css("background", "yellow");
  
    // Highlight li elements inside all the ul element with class mark
    $("ul.mark li").css("background", "green");
  
    // Highlight all anchor elements with target blank
    $('a[target="_blank"]').css("background", "yellow");
});
</script>
jQuery Custom Selector

In addition to the selectors definiti, jQuery provides its own custom selector to further enhance the capabilities of selecting elements on a page.

<script>
$(document).ready(function(){
    // Highlight table rows appearing at odd places
    $("tr:odd").css("background", "yellow");
  
    // Highlight table rows appearing at even places
    $("tr:even").css("background", "orange");
  
    // Highlight first paragraph element
    $("p:first").css("background", "red");
  
    // Highlight last paragraph element
    $("p:last").css("background", "green");
  
    // Highlight all input elements with type text inside a form
    $("form :text").css("background", "purple");
  
    // Highlight all input elements with type password inside a form
    $("form :password").css("background", "blue");
  
    // Highlight all input elements with type submit inside a form
    $("form :submit").css("background", "violet");
});
</script>

Events

Events are often triggered by user interaction with the web page, such as when clicking a link or button, entering text into an input box or text area, make a selection in a selection box, press a key on the keyboard, move the mouse pointer, etc. In some cases, the browser itself can trigger events, such as page load and download events.

jQuery improves on the basic event handling mechanisms by offering event methods for most native browser events, some of these methods are ready(), click(), keypress(), focus(), blur(), change(), etc.

<script>
$(document).ready(function(){
    // Code to be executed
    alert("Hello World!");
});
</script>

In general, events can be classified into four main groups: 

  • mouse events,
  • keyboard events,
  • events module ed
  • document/window events . 

Mouse events

A mouse event is triggered when the user clicks on an item, moves the mouse pointer, etc.

Here are some commonly used jQuery methods to handle mouse events.

The method click()

The method click() attach an event handler function to the selected elements for the event “click“. The linked function executes when the user clicks on that item. The following example will hide the elements <p> on a page when clicked.

<script>
$(document).ready(function(){
    $("p").click(function(){
        $(this).slideUp();
    });
});
</script>
The method dblclick()

The method dblclick() attach an event handler function to the selected elements for the event “dblclick“. The linked function executes when the user double-clicks that item. The following example will hide the elements <p> when double-clicking them.

<script>
$(document).ready(function(){
    $("p").dblclick(function(){
        $(this).slideUp();
    });
});
</script>
The method hover()

The method hover() attach one or two event handler functions to selected elements that execute when the mouse pointer moves in and out of elements. The first function runs when the user places the mouse pointer over an item, while the second function runs when the user removes the mouse pointer from that item.

The following example will highlight items <p> when you place the cursor on it, the highlight will be removed when you remove the cursor.

<script>
$(document).ready(function(){
    $("p").hover(function(){
        $(this).addClass("highlight");
    }, function(){
        $(this).removeClass("highlight");
    });
});
</script>
The method mouseenter()

The method mouseenter() attach an event handler function to the selected elements which is executed when the mouse enters an element. The following example will add class highlighting to the element <p> when you place the cursor over it.

<script>
$(document).ready(function(){
    $("p").mouseenter(function(){
        $(this).addClass("highlight");
    });
});
</script>
The method mouseleave()

The method mouseleave() attach an event handler function to selected items that runs when the mouse leaves an item. The following example will remove the class highlight from the element <p> when you remove the cursor from it.

<script>
$(document).ready(function(){
    $("p").mouseleave(function(){
        $(this).removeClass("highlight");
    });
});
</script>

Keyboard events

A keyboard event is raised when the user presses or releases a key on the keyboard. Let's look at some commonly used jQuery methods to handle keyboard events.

The method keypress()

The method keypress() attaches an event-handling function to selected elements (typically form controls) that runs when the browser receives keyboard input from the user. The following example will display a message when the event is triggered keypress and how many times it is triggered when you press the key on your keyboard.

<script>
$(document).ready(function(){
    var i = 0;
    $('input[type="text"]').keypress(function(){
        $("span").text(i += 1);
        $("p").show().fadeOut();
    });
});
</script>

The keypress event is similar to the keydown event, except that modifier and nonprinting keys such as Shift, Esc, Backspace or Delete, arrow keys, etc. they fire keydown events but not keypress events.

The method keydown()

The method keydown() attaches an event-handling function to selected items (typically form controls) that is executed when the user first presses a key on the keyboard. The following example will display a message when the event is triggered keydown and how many times it is triggered when you press the key on your keyboard.

<script>
$(document).ready(function(){
    var i = 0;
    $('input[type="text"]').keydown(function(){
        $("span").text(i += 1);
        $("p").show().fadeOut();
    });
});
</script>
The method keyup()

The method keyup() attach an event-handling function to selected elements (typically form controls) that is executed when the user releases a key on the keyboard. The following example will display a message when the event is triggered keyup and how many times it is triggered when you press and release a key on your keyboard.

<script>
$(document).ready(function(){
    var i = 0;
    $('input[type="text"]').keyup(function(){
        $("span").text(i += 1);
        $("p").show().fadeOut();
    });
});
</script>

Form events

A form event is triggered when a form control receives or loses focus, or when the user changes a form control value, such as typing text into a text input, selecting an option in a select box, etc. . Here are some commonly used jQuery methods to handle form events.

The method change()

The method change() attach an event handler function to elements <input> and is executed when its value changes. The following example will display a warning message when selecting an option in the drop down selection box.

<script>
$(document).ready(function(){
    $("select").change(function(){
        var selectedOption = $(this).find(":selected").val();
        alert("You have selected - " + selectedOption);
    });
});
</script>

For click boxes, check boxes, and radio buttons, the event fires immediately when the user makes a mouse selection, but for text input and text area the event fires after the element loses focus.

The method focus()

The method focus() attaches an event handler function to selected elements (typically controls and form bindings) that executes when it gets focus. The following example will display a message when text input receives focus.

<script>
$(document).ready(function(){
    $("input").focus(function(){
        $(this).next("span").show().fadeOut("slow");
    });
});
</script>
The method blur()

The method blur() attach an event handler function to form elements such as <input><textarea><select> which is executed when it loses focus. The following example will display a message when the text input loses focus.

<script>
$(document).ready(function(){
    $("input").blur(function(){
        $(this).next("span").show().fadeOut("slow");
    });
});
</script>
The method submit()

The method submit() attach an event handler function to elements <form> which runs when the user tries to submit a form. The following example will display a message based on the value entered when attempting to submit the form.

<script>
$(document).ready(function(){
    $("form").submit(function(event){
        var regex = /^[a-zA-Z]+$/;
        var currentValue = $("#firstName").val();
        if(regex.test(currentValue) == false){
            $("#result").html('<p class="error">Not valid!</p>').show().fadeOut(1000);
            // Preventing form submission
            event.preventDefault();
        }
    });
});
</script>

Document/Window Events

The events are also fired in a situation where the DOM (Document Object Model) page is ready or when the user resizes or scrolls the browser window, etc. Here are some commonly used jQuery methods to handle this type of event.

The method ready()

The method ready() specifies a function to execute when the DOM is fully loaded.

The following example will replace paragraph text as soon as the DOM hierarchy is fully built and ready to be manipulated.

<script>
$(document).ready(function(){
    $("p").text("The DOM is now loaded and can be manipulated.");
});
</script>
The method resize()

The method resize() attach an event handler function to the window element that runs when the size of the browser window changes.

The following example will show the current width and height of the browser window when you try to resize it by dragging its corners.

<script>
$(document).ready(function(){
    $(window).resize(function() {
        $(window).bind("resize", function(){ 
            $("p").text("Window width: " + $(window).width() + ", " + "Window height: " + $(window).height());
        });
    });
});
</script>
The method scroll()

The method scroll() attach an event handler function to the window or to the iframe and scrollable items that runs whenever the scroll position of the item changes.

The following example will display a message when scrolling the browser window.

<script>
$(document).ready(function(){
    $(window).scroll(function() {
        $("p").show().fadeOut("slow");
    });
});
</script>

Ercole Palmeri

.

Innovation newsletter
Don't miss the most important news on innovation. Sign up to receive them by email.

Latest Articles

The Benefits of Coloring Pages for Children - a world of magic for all ages

Developing fine motor skills through coloring prepares children for more complex skills like writing. To color…

May 2, 2024

The Future is Here: How the Shipping Industry is Revolutionizing the Global Economy

The naval sector is a true global economic power, which has navigated towards a 150 billion market...

May 1, 2024

Publishers and OpenAI sign agreements to regulate the flow of information processed by Artificial Intelligence

Last Monday, the Financial Times announced a deal with OpenAI. FT licenses its world-class journalism…

April 30 2024

Online Payments: Here's How Streaming Services Make You Pay Forever

Millions of people pay for streaming services, paying monthly subscription fees. It is common opinion that you…

April 29 2024