How to use jquery in javascript

3 minute read

jQuery was created in 2006 by John Resig. It was designed to handle Browser Incompatibilities and to simplify HTML DOM Manipulation, Event Handling, Animations, and Ajax.

Link : w3school - JS vs jQuery

Javascript vsjQuery

Selector

// Javascript
var myElement = document.getElementById("id01");
var myElements = document.getElementsByTagName("p");
var myElements = document.getElementsByClassName("intro");
var myElements = document.querySelectorAll("p.intro");

// jQuery
var myElement = $("#id01"); // Return the element with id="id01"
var myElements = $("p"); // Return all <p> elements
var myElements = $(".intro"); // Return all elements with class="intro"
var myElements = $("p.intro"); // Return a list of all <p> elements with class="intro"

HTML

// Javascript
myElement.textContent = "Hello World!";
var myText = myElement.textContent || myElement.innerText;

var myElement.innerHTML = "<p>Hello World</p>";
var myHtml = myElement.innerHTML;

document.getElementById("myinput").value = 'Your value here';
var myVal = document.getElementById("myinput").value;

// jQuery
myElement.text("Hello World!");
var myText = myElement.text();

var myElement.html("<p>Hello World</p>");
var myHtml = myElement.html();

myElement.val('Your value here');
var myVal = myElement.val();

CSS

// Javascript
myElement.style.display = "none";
myElement.style.display = "";
myElement.style.fontSize = "35px";

// jQuery
myElement.hide();
myElement.show();
myElement.css("font-size","35px");

DOM

// Javascript
element.parentNode.removeChild(element);
var myParent = myElement.parentNode;

// jQuery
$("#id").remove();
var myParent = myElement.parent();

jQuery

Link : w3school - jquery selectors

$(function() {
  // Document is ready
});

jQuery(function( $ ) {
  // Your code using failsafe $ alias here...
});


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

Functions

$(window).height();   // returns height of browser viewport
$(document).height(); // returns height of HTML document
$(window).width();   // returns width of browser viewport
$(document).width(); // returns width of HTML document

$.Deferred()

Link : jQuery.Deferred

function deferredfun(pos) {
    var deferred = $.Deferred();
    
    // do your job
    if (job_successful)
      deferred.resolve(); // successful - calls done() (cf. resolveWith())
    else
      deferred.reject(); // failed - calls fail() (cf. rejectWith())

    return deferred.promise();
}

$.ajax()

$.ajax({
    url: url,
    data: data,
    success: success,
    dataType: dataType ('xml', 'html', 'text', 'script', 'json', 'jsonp')
});

$.ajax({
    type: "POST",
    url: url,
    data: data,
    success: success,
    dataType: dataType
});

$.ajax({
    type: "POST",
    url: "your_url",
    data: JSON.stringify({ count: Math.ceil(Math.random() * 30) }),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {
        alert("RECV:" + JSON.stringify(data));
    },
    error: function (data) {
        alert("ERROR:" + JSON.stringify(data));
    }
});

$.ajax({
    type: 'GET',
    url: url,
    success: function (data) {
        alert("ajax success : " + JSON.stringify(data));
        try {
            deferred.resolve(data);
        } catch (e) {
            deferred.reject();
        }
    },
    error: function (error) {
        alert("ajax error : " + error);
        deferred.reject();
    }
});

$.ajax({
    url: url,
    dataType : 'jsonp',
    beforeSend : function(xhr) {
      // generate base 64 string from username + password
      var bytes = Crypto.charenc.Binary.stringToBytes(username + ":" + password);
      var base64 = Crypto.util.bytesToBase64(bytes);
      // set header
      xhr.setRequestHeader("Authorization", "Basic " + base64);
    },
    error : function() {
      // error handler
    },
    success: function(data) {
        // success handler
    }
});

$.get()

$.get(URL, data, function(data,status,xhr), dataType)

  • URL : Required. Specifies the URL you wish to request
  • data : Optional. Specifies data to send to the server along with the request
  • function(data,status,xhr) : Optional. Specifies a function to run if the request succeeds

    Additional parameters:

    • data - contains the resulting data from the request
    • status - contains the status of the request (“success”, “notmodified”, “error”, “timeout”, or “parsererror”)
    • xhr - contains the XMLHttpRequest object
  • dataType: Optional. Specifies the data type expected of the server response. By default jQuery performs an automatic guess. (Possible Types : ‘xml’, ‘html’, ‘text’, ‘script’, ‘json’, ‘jsonp’)
// Case #1
var jqxhr = $.get("http://your_url", function (data, status) {
    var parsed_json = $.parseJSON(data);
    alert("Status: " + status);
}, "json");

jqxhr.done(function () {
    alert("second success");
    d.resolve([{ "Name": "John success" }], {});
});

jqxhr.fail(function () {
    //alert("error");
    d.resolve([{ "Name": "John error" }], {});
});

jqxhr.always(function () {
    //alert("finished");
    d.resolve([{ "Name": "John always" }], {});
});

// Case #2
var jqxhr = $.get("http://your_url", function (data) {
            alert("success " + data);
            })
            .done(function () {
                alert("second success");
            })
            .fail(function (error) {
                alert("error : " + error);
            })
            .always(function () {
                //alert("finished");
            });
    // Perform other work here ...

    // Set another completion function for the request above
    jqxhr.always(function (data) {
        alert("second finished " + data);
    });

// Case #3
    $.get("test.php", { name:"Donald", town:"Ducktown" });

$.when()

If no arguments are passed to jQuery.when(), it will return a resolved Promise. If a single argument is passed to jQuery.when() and it is not a Deferred or a Promise, it will be treated as a resolved Deferred and any doneCallbacks attached will be executed immediately.

Link : Jquery when

// no arguments
$.when().then(function( x ) {
  alert( "I fired immediately" );
});

// single argument
$.when( $.ajax( "test.aspx" ) ).then(function( data, textStatus, jqXHR ) {
  alert( jqXHR.status ); // Alerts 200
});

// when, done
$.when( { testing: 123 } ).done(function( x ) {
  alert( x.testing ); // Alerts "123"
});

Leave a comment