Simplify your code with jQueryAugust 23, 2020

CodeCell - Naman

We are all familiar with JavaScript, the scripting language that enables you to create dynamically updating content, control multimedia, animate images, and pretty much everything else. Well but, some parts of JavaScript code, required to manipulate DOM get really lengthy and repetitive. That is exactly the reason why jQuery was developed!

Introduction


What is jQuery?

jQuery provides almost the same functionality as JavaScript does but with relatively smaller chunks of code. To understand jQuery better, lets dive into some technical details.

jQuery is an open-source light-weight JavaScript library made by John Resig.

To put it simply, it is a collection of JavaScript code packaged together that can be accessed by a much simpler line of code, thus making it easier for developers to implement JavaScript.

This library simplifies JavaScript event handling, traversing HTML documents, AJAX-based interactions, and animations.

Why jQuery?

  • Popularity: One of the greatest strengths of jQuery is the size of its community. It is easier to find support, active developers and it is more likely to be improved with time.
  • Simplicity: jQuery takes a lot of common tasks that require a lot of JavaScript code to accomplish and wraps them into methods that you can call with a single line of code. This makes a few lines of jQuery equivalent to many lines of conventional JavaScript code. This means smaller files and faster loading web pages. It's based on a simple principle, "Write less, do more"
  • Cross browser support: jQuery deals with many cross-browser issues and bugs that you would experience while developing using JavaScript only. This enables you to develop a website that works properly on all types of browsers and different versions too.
  • Flexible: jQuery provides a plugin framework, making it easy to extend jQuery. This includes both official jQuery plugins and thousands of third-party plugins.

What is it used for?

  • HTML event methods
  • DOM manipulation
  • CSS manipulation
  • AJAX
  • Utilities
  • Effects and animations


Getting Started


How to include it in our webpages?

jQuery is included using the script tag in the head of the HTML document. It can be included in 2 ways:

  • jQuery Installation: you can download the jQuery library and add it to your HTML code
  • jQuery CDN: you can include jQuery in your website straight from CDN (Content Delivery Network)
<script src="jquery-3.5.1.min.js"></script>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>


Standard jQuery syntax:

A jQuery statement typically starts with the dollar sign ($) and ends with a semicolon (;)

script element : since jQuery is a javaScript library, code can be placed inside the script element. However, replacing it with an external javaScript file is prefered

<script>
    $document.ready(function(){
        // some code to execute...
        alert("Hello World!")
    });
</script>

The code in the script tag can be read as, $(selector).ready(handler);

  • $(selector) : selects the HTML elements from the DOM tree to be manipulated
  • ready() : method to be executed safely as soon as the DOM hierarchy/selector has been fully constructed
  • handler : a function containing a set of instructions to be executed, when the method '.ready()' is triggered. It can be a pre-defined or an anonymous function

DOM Manipulation

What is DOM? A brief overview…

DOM or Document Object Model is a representation of the web page or document, which can be modified with a scripting language such as JavaScript according to MDN.

It characterizes the DOM HTML document as a hierarchical tree structure and each element in the document tree is called a Node.

DOM Tree

DOM nodes represent all tags that make up the HMTL, it is through this hierarchy that the elements can be accessed through JavaScript/jQuery. With the DOM, programmers can build documents, navigate their structure, and add, modify, or delete elements and content.

Manipulating DOM

  • Get or Set Contents and Values

Some jQuery methods can be used to either assign or read some value on a selection. A few of these methods are text() html(), attr(), and val().

Methods are called with no argument, are referred to as a getters, because they get (or read) the value of the element.

Methods are called with a value as an argument, are referred to as a setter because it sets (or assigns) that value.

<script>
    // get html content
    $(".show-text").html();
    // set new value
    $(".show-text").html("<p>Hello World!</p>");
</script>

  • CSS Method

The jQuery css() method is used to get the computed value of a CSS property or set one or more CSS properties for the selected elements.

<script>
    // get css values
    $("h1").css("color");
    $("h1").css("background");
    // set new css values
    $("h1").css({
        color: "red",
        background: "pink"
    });
</script>

  • CSS Classes Manipulation

addClass(), removeClass(), toggleClass(), etc. are some methods to manipulate the CSS classes assigned to HTML elements. For example, disable and change the color of a button once clicked through a css class.

<script>
    // toggle styling in click
    $("button").on("click", function(){
        $(this).toggleClass("highlight");
    });
</script>

  • Insert New Content

Methods, like append(), prepend(), html(), text(), before(), after(), wrap() etc. allows us to insert new content inside an existing element.

  • Remove Elements or Contents

Methods, such as empty(), remove(), unwrap() etc. to remove existing HTML elements or contents from the document.

jQuery effects

jQuery enables us to add effects to our web page. The most used effects are fade, slide, hide/show methods.


  • Hide/Show:

The hide() method simply sets the inline style display: none for the selected elements. Conversely, the show() method restores the display properties of the matched set of elements to whatever they initially were—typically block, inline, or inline-block.

  • Fade

jQuery fadeIn() and fadeOut() methods are used to display or hide the HTML elements by gradually increasing or decreasing their opacity.

  • Slide

jQuery slideUp() and slideDown() methods to display or hide the HTML elements by gradually increasing or decreasing their opacity.

Note: toggle(), fadeToggle(), slideToggle() are used to switch between hide/show, fade, and slide respectively based on it's current state.

<script>
    $(".hide-btn").click(function(){
        $("p").hide();
    });
    $(".hide-btn").click(function(){
        $("p").show();
    });
</script>

<script>
    //equivalent code
    $(".toggle-btn").click(function(){
        $("p").toggle();
    })
</script>

Note: You can optionally specify the duration or speed parameter for the all of the above methods to control how long the animation will run. Durations can be specified either using one of the predefined string 'slow' or 'fast', or in a number of milliseconds; higher values indicate slower animations.

Other effects methods include animation, stop, chaining, callback and many more...

Ending Note

jQuery is the most outstanding cross-browser JavaScript library compiled for ease of client-side scripting of HTML. As jQuery is built on top of JavaScript, it provides all the functionalities of JavaScript.

We can say from above points jQuery is enhanced version of JavaScript. jQuery has tons of impressive effects, it is often used by web designers to make their designs much lovable and elegant. It minimizes tasks of web developers to great extent, by providing instant plugins.

There's still a lot of functionality that jQuery provides, to get a detailed insight into it, don't refrain to use the official documentation.