DEV Community

Cover image for An Introduction to jQuery: Functionality, Animations, and Server Interaction
Peter Klingelhofer
Peter Klingelhofer

Posted on • Updated on

An Introduction to jQuery: Functionality, Animations, and Server Interaction

Introduction

jQuery is an intuitive way to realize common JavaScript tasks consistently across major browsers. It makes it really easy to select elements with CSS-style selectors, animate, use event listeners, and update the DOM.

// this function lets you find elements on the page
jQuery()

// a typical shorthand used for the jQuery object is
$()

/*
this function creates a jQuery object, selecting 
all list items with a class of 'cool'
*/
$('li.cool');

// we can toggle additional classes on and off like so
$('li.cool').toggleClass('done');
Enter fullscreen mode Exit fullscreen mode

jQuery's cross-browser capabilities allow users to avoid the need for writing fallback code to support older browsers.

Element Functionality

jQuery Method: .blur()

Blur events occur when an element loses focus. This event can work for all element types. An element may lose its focus by a mouse click on a different element on the page, or if the user is traversing the page with keyboard commands (such as pressing the Tab key to move to the next element).

/*
.blur( [eventData ], handler )
- eventData: data object that will be passed to the event handler
- handler: function to be executed every time the event is triggered


here we turn the color of the input field the user just left 
black, and send a message to the console
*/

$(document).ready(() => {  
  $("input").blur(function(){
    $(this).css("background-color", "#000000");   
    console.log(`Until next time, friend!`);
  });  
});  

Enter fullscreen mode Exit fullscreen mode

Element Animation

jQuery Method: .fadeOut()

fadeOut() fades out all matching elements from opaque to invisible

/*
.fadeOut( [duration ] [, complete ] )
- duration: (default: 400) optional number or string designating 
how long the animation takes to complete
- complete: optional callback function to call after 
animation completes


fades out all list items with a class of cool
*/
$("button").click(() => {
  $("li.cool").fadeOut();
});
Enter fullscreen mode Exit fullscreen mode

.fadeOut also includes additional easing options to control the speed of the animation

/*
.fadeOut( options )
- options: object to pass additional options to the method
+ easing: (default: swing) string indicating which easing function 
to use for the transition. swing goes slow in the beginning, speeds 
up, then slows down again at the end, whereas linear has a 
constant speed throughout.
*/

$("button").click(() => {
  $("div").fadeOut(200);
});
Enter fullscreen mode Exit fullscreen mode

Alt Text

Server Communication

jQuery Method: AJAX $.get()

The REST acronym stands for REpresentational State Transfer. REST APIs allows you to interact with servers Get requests and attempts to retrieve data from a specified server.

/*
$.get(url [, callback]);
- url: specifies the URL of the server you intend to request
- callback: optionally name a function to call if successful


here we take input from the user and request the server for a JSON 
file containing information pertaining to that user's account, and 
display it on the page
*/

$(document).ready(function(){
    $("button").click(function(){
        let username = $("#input").val();
        $.get("profile.json", {user: username} , function(data){
            $("#profile").html(data);
        });
    });
});
Enter fullscreen mode Exit fullscreen mode

jQuery Method: AJAX $.post()

Submits data to a specified server.

/*
$.( url [, data ] [, success ] [, dataType ] );
- url: specifies the URL of the server you intend to send data to
- data: optionally specify data to send with the request
- callback: optionally name a function to call if successful
- dataType: the type of data expected from the server

here we ask the server the price of an item on the page
*/

$(document).ready(function(){
    $("button").click(function(){
        $.post('http://example.com/form.php, 
        {category:'client', type:'premium'},(data) => { 
        console.log(`data retrieved`);
        $("#pricetag").html(data.amount);
    });
    });
});

Enter fullscreen mode Exit fullscreen mode

Using REST API, we can submit authentication keys with our AJAX requests so that the server will talk to us. Here is a more complex example using REST API headers in our postSettings object being submitted in our $.ajax call to authenticate the connection with the server


const postSettings = {
  "url": "http://server.location.com/inbox",
  "method": "POST",
  "timeout": 0,
  "headers": {
    "X-Parse-Application-id": "writeKeyid",
    "X-Parse-REST-API-Key": "writeAPIkey"
    "Content-Type": "application/json",
  },
};

$.ajax(postSettings).done(data => console.log(data));

Enter fullscreen mode Exit fullscreen mode

Conclusion

jQuery is an invaluable and powerful tool for achieving otherwise cumbersome JavaScript tasks swiftly and efficiently. We can perform functionality such as blur, animations such as fadeOut, and interact with servers using jQuery AJAX methods. With browser-compatibility operating under the hood so you can focus more on creating and less on worrying about users who haven't updated their browsers in years, we can use jQuery to increase accessibility of our websites.

In closing, I highly recommend this impressively useful cheatsheet Oscarotero has put out for jQuery.

Top comments (1)

Collapse
 
adrianmarkperea profile image
Adrian Perea

I'm curious -- and I hope you understand that I'm not condescending -- but is jquery still widely used in industry nowadays?