Last Updated: September 09, 2019
·
4.982K
· steveniseki

jQuery tutorial

This is just a simple jquery tutorial, more of a reference guide for common jQuery methods and features. For complete documentation visit http://api.jquery.com/

A jQuery object contains a collection of DOM elements that have been created from an HTML string or selected from a document. The jQuery object itself behaves much like an array it has a length property and the elements in the object can be accessed by their numeric indices [0] to [length-1]

extend the jQuery fn prototype to create a custom function or plugin

$.fn.customFunction = function (n) {
    // custom function
    }

get a jQuery object from an iframe

$("iFrame").contents().find("div.xclass")

to get a list of attached events

$.data(document, 'events')

get element by id using jQuery

var element = $('#section')[0];

The .promise() method returns a dynamically generated Promise that is resolved once all actions of a certain type bound to the collection, queued or not, have ended.

$( "div" ).promise().done(function() {
    $( "p" ).append( " Finished! " );
 });

chaining is possible because every setter method in jQuery returns
the selection on which it was called.

var $elem = $( 'li' ).children('li').first().next();

delete a cookie

$.cookie("name", $(this).val(), { path: '/', expires: -1 });
$.cookie("name", $("cookie-value"), { path: '/', expires: -1 });
$.cookie("name", null);

effects in jQuery

// .animate()
.animate({ fontSize: "24px" }, 1500 )

// .delay()
$("div.second").slideUp(300).fadeIn(400);

// .fadeIn / .fadeOut()
$("span").fadeIn(300);

// .hide()
$("p").hide("slow");

// .show()
$("div").show("fast");

// .stop()
$(".block").animate({left: '+=100px'}, 2000);
$(".block").stop();

// .toggle()
$("p").toggle();

retrieve json data using ajax

// jQuery.ajax()
$.ajax({
  url: 'ajax/test.html',
  success: function(data) {
    $('.result').html(data);
    alert('Load was performed.');
  }
});

// .ajaxSuccess() / .ajaxError() / .ajaxComplete()
$("#msg").ajaxSuccess(function(evt, request, settings){
      $(this).append("Successful Request!");
 });

dom selectors

// *
// selects all elements.
var elementCount = $("*").length;

// .
// selects all elements with the given class.
$(".myclass.otherclass")

// #
// selects a single element with the given id attribute.
$("#myDiv")

// :animated
// select all elements that are in the progress of an animation at the time the selector is run.
$("div:animated")

// :button
// Selects all button elements and elements of type button
$(":button")

// :checkbox
// selects all elements of type checkbox.
$("form input:checkbox")

// :checked
// matches all elements that are checked.
$("input:checked")

// :contains()
// select all elements that contain the specified text.
$("div:contains('Steven')")

// :disabled
// selects all elements that are disabled.
$("input:disabled")

// :empty
// select all elements that have no children (including text nodes).
$("td:empty")

// :enabled
// selects all elements that are enabled.
$("input:enabled")

// :eq()
// select the element at index n within the matched set.
$("td:eq(2)")

// :even :odd
// selects even / odd elements, zero-indexed.
$("tr:even")

// :file
// selects all elements of type file.
$("input:file")

// :first-child
// selects all elements that are the first child of their parent.
$("div span:first-child")

// :first / :last
// selects the first / last matched element.
$("tr:first")

// :focus
// selects element if it is currently focused.
elem.toggleClass( "focused", elem.is(":focus") );

// :has()
// selects elements which contain at least one element that matches the specified selector.
$("div:has(p)")

// :hidden :visible
// selects all elements that are hidden / visible.
$("div:hidden")

// :image
// selects all elements of type image.
 $("input:image")

// :input
// selects all input, textarea, select and button elements.
$(":input");

// :text
// selects all elements of type text.
$("form input:text")

// :not()
// selects all elements that do not match the given selector.
$("input:not(:checked)")

// :password
// selects all elements of type password.
$("input:password")

// :parent
// select all elements that are the parent of another element, including text nodes.
$("td:parent")

// :radio
// selects all elements of type radio.
$("form input:radio")

// :reset
// selects all elements of type reset.
$("input:reset")

// :selected
// selects all elements that are selected.
$("select option:selected")

// :submit
// selects all elements of type submit.
$(":submit")

changing styles in jQuery

// .addClass
$("p").addClass("selected");

// .css()
var color = $(this).css("background-color");
$(this).css("color","red");

// .hasClass
$('#mydiv').hasClass('foo')

// .removeClass
$("p").removeClass("blue");

// .toggleClass
$("p").click( function () { 
    $(this).toggleClass("highlight");
});

traversing the dom in jQuery

// .add()
$("p").add("Again")
$("p").add("span").css("background", "yellow");

// .children()
$("div").children()

// .closest()
var x = $("div").closest("li");

// .contents()
$("p").contents()

// .each()
$("li").each(function(){
        $(this).toggleClass("example");
  });

// .end()
$("p").showTags(0)
          .find("span")
          .css("background", "yellow")
          .end()
          .css("font-style", "italic");

// .eq()
$("body").find("div").eq(2).addClass("blue");

// .find()
var $allListElements = $('li');
$('li.item-ii').find($allListElements);

// .first()
$('li').first().css('background-color', 'red');

// .has()
$('li').has('ul').css('background-color', 'red');

// .is()
if ($(this).is(":first-child")) {
    // execute code
}

// .last()
$('li').last().css('background-color', 'red')

// .map()
$(':checkbox').map(function() {
  return this.id;
}).get();

// .next() / .prev()
$('li.third-item').next().css('background-color', 'red');

// .nextAll()
// begin at the third item, we can find the elements which come after it
$('li.third-item').nextAll().css('background-color', 'red');

// .nextUntil()
$("#term2").nextUntil("term6")
  .css("background-color", "red");

// .parent()
$('li.item-a').parent().css('background-color', 'red');

// .parents()
// begin at item a, we can find its ancestors:
$('li.item-a').parents().css('background-color', 'red');

// .siblings()
$('li.third-item').siblings().css('background-color', 'red');

// .slice()
$('li').slice(2).css('background-color', 'red');

dom manipulation in jQuery

// .after() /  .before()
$("p").after("Hello");

// .append() / .prepend()
 $("p").append("Hello");

// .appendTo() / .prependTo()
$("span").appendTo("#foo"); 

// .attr
var title = $("em").attr("title");

// .clone()
$("b").clone().prependTo("p");

// .detach()
$("p").detach();

// .empty()
$("p").empty();

// .height() / .width()
$(this).height(30)

// .html
$("div").html("Wow...");

// .insertAfter() / .insertBefore()
$("p").insertAfter("#foo"); 

// .offset()
$("p:last").offset({ top: 10, left: 30 });

// .position()
var position = $("p").position();

// .prop
$("input[type='checkbox']").prop({  
    disabled: true
});

// .remove()
$("p").remove();

// .text()
var str = $("p:first").text();

// .val()
var value = $(this).val();

// .wrap()
$("p").wrap("
");

binding to events in jQuery

// .bind()
// attach a handler to an event for the elements.
$('#foo').bind('click', function() {
  alert('User clicked on "foo."');
});

// .unbind()
// remove a previously-attached event handler from the elements.
$('#foo').unbind();

// .change()
// bind an event handler to the "change" javaScript event, or trigger that event on an element.
$('.target').change(function() {
  alert('Handler for .change() called.');
});

// .click() / .dblclick
// bind an event handler to the "click" javaScript event, or trigger that event on an element.
$("#target").click(function() {
  alert("Handler for .click() called.");
});

// .delegate()
// attach a handler to one or more events for all elements that match the selector, now or in the future
$("table").delegate("td", "click", function() {
  $(this).toggleClass("chosen");
});

// .die()
// remove all event handlers previously attached using .live() from the elements.
$("p").die( "click")

// .error()
// bind an event handler to the "error" JavaScript event.
$("img")
  .error(function(){
    $(this).hide();
 })

// .focus()
// bind an event handler to the "focus" javaScript event, or trigger that event on an element.
$('#target').focus(function() {
  alert('Handler for .focus() called.');
});

// .hover()
$(function () {
    $("#mapping").hover(
        function () {
        $(this).addClass("hover");
        },
        function () {
        $(this).removeClass("hover");
        }
    );
});

// .keyup() / .keypress() / .keydown()
$('#target').keyup(function() {
  alert('Handler for .keyup() called.');
});

// .mouseover() mousedown() ...
// trigger a mouseover event.
$('#outer').mouseover();

// .on()
// attach an event handler function for one or more events to the selected elements.
$("#dataTable").on("click", function(event){
    alert($(this).text());
});

// .off()
// remove an event handler.
$("p").off( "click", "**" )

// .ready()
// specify a function to execute when the DOM is fully loaded.
$(document).ready(function() {
  // Handler for .ready() called.
});

// .resize()
// bind an event handler to the "resize" javaScript event, or trigger that event on an element.
$(window).resize(function() {
  $('#log').append('Handler for .resize() called.
');
});

// .scroll()
// trigger a scroll
$('#target').scroll();

// .select()
// bind an event handler to the "select" javaScript event, or trigger that event on an element.
$('#target').select(function() {
  alert('Handler for .select() called.');
});

// .submit()
// bind an event handler to the "submit" javaScript event, or trigger that event on an element.
$('#target').submit(function() {
  alert('Handler for .submit() called.');
  return false;
});

// .toggle()
// bind two or more handlers to the matched elements, to be executed on alternate clicks.
$('#target').toggle(function() {
  alert('First handler for .toggle() called.');
}, function() {
  alert('Second handler for .toggle() called.');
});

// .trigger()
$(document).ready(function(){ 
  $('#some-id').trigger('click'); 
});

3 Responses
Add your response

Very useful, thanks!

over 1 year ago ·

Really very useful need more stuff to get in practice. Please keep posting..

over 1 year ago ·

Very useful, nice resource.

It's worth noting that .cookie() is a plugin, and not native to jQuery.

over 1 year ago ·