jQuery CheatSheet

Our jQuery cheat sheet is the ultimate tool for developers looking to master the art of jQuery programming. Designed with both beginners and advanced users in mind, this comprehensive reference guide covers all the essential syntax and functions you need to create dynamic and interactive web pages with ease. With our cheat sheet at your fingertips, you'll be able to streamline your coding workflow and save valuable time, allowing you to focus on building high-quality applications that meet the needs of your users. So if you want to take your jQuery skills to the next level, download our professional-grade cheat sheet today and start building amazing websites and applications!


Table of Content




# Getting started jQuery


What is jQuery ?

jQuery is a JavaScript library designed to simplify HTML DOM tree traversal and manipulation, as well as event handling, CSS animation, and Ajax.

jQuery is a lightweight, "write less, do more", JavaScript library.

jQuery has plugins for almost any task

The purpose of jQuery is to make it much easier to use JavaScript on your website.

It is free, open-source software using the permissive MIT License.

How to use jQuery ?

<!-- google api -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<!-- CDN -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>

# Selectors in jQuery


Example

$("button").click(() => {
    $(":button").css("background-color", "green");
});


// Combining selectors
$("selector1, selector2 ... selectorn")

Basics

* Selects all elements.
.class Selects all elements with the given class.
element Selects all elements with the given tag name.
#id Selects a single element with the given id attribute.
:hidden Selects all elements that are hidden.
:visible Selects all elements that are visible.
:contains() Select all elements that contain the specified text.
:empty Select all elements that have no children (including text nodes).
:has() Selects elements which contain at least one element that matches the specified selector.
:parent Select all elements that have at least one child node (either an element or text).
parent> child Selects all direct child elements specified by child of elements specified by parent.
ancestor descendant Selects all elements that are descendants of a given ancestor.
prev + next Selects all next elements matching next that are immediately preceded by a sibling prev.
prev ~ siblings Selects all sibling elements that follow after the prev element, have the same parent, and match the filtering siblings selector.

Basic Filters

:animated Select all elements that are in the progress of an animation at the time the selector is run.
:eq() Select the element at index n within the matched set.
:even Selects even elements, zero-indexed. See also :odd.
:first Selects the first matched DOM element.
:gt() Select all elements at an index greater than index within the matched set.
:header Selects all elements that are headers, like h1, h2, h3 and so on.
:lang() Selects all elements of the specified language.
:last Selects the last matched element.
:lt() Select all elements at an index less than index within the matched set.
:not() Selects all elements that do not match the given selector.
:odd Selects odd elements, zero-indexed. See also :even.
:root Selects the element that is the root of the document.
:target Selects the target element indicated by the fragment identifier of the document's URI.

Attribute

[name|="value"] Selects elements that have the specified attribute with a value either equal to a given string or starting with that string followed by a hyphen (-).
[name*="value"] Selects elements that have the specified attribute with a value containing a given substring.
[name~="value"] Selects elements that have the specified attribute with a value containing a given word, delimited by spaces.
[name$="value"] Selects elements that have the specified attribute with a value ending exactly with a given string. The comparison is case sensitive.
[name="value"] Selects elements that have the specified attribute with a value exactly equal to a certain value.
[name!="value"] Select elements that either don't have the specified attribute, or do have the specified attribute but not with a certain value.
[name^="value"] Selects elements that have the specified attribute with a value beginning exactly with a given string.
[name] Selects elements that have the specified attribute, with any value.
[name="value"][name2="value2"] Matches elements that match all of the specified attribute filters.

Child Filters

:first-child Selects all elements that are the first child of their parent.
:first-of-type Selects all elements that are the first among siblings of the same element name.
:last-child Selects all elements that are the last child of their parent.
:last-of-type Selects all elements that are the last among siblings of the same element name.
:nth-child() Selects all elements that are the nth-child of their parent.
:nth-last-child() Selects all elements that are the nth-child of their parent, counting from the last element to the first.
:nth-last-of-type() Selects all the elements that are the nth-child of their parent in relation to siblings with the same element name, counting from the last element to the first.
:nth-of-type() Selects all elements that are the nth child of their parent in relation to siblings with the same element name.
:only-child Selects all elements that are the only child of their parent.
:only-of-type() Selects all elements that have no siblings with the same element name.

Forms

:button Selects all button elements and elements of type button.
:checkbox Selects all elements of type checkbox.
:checked Matches all elements that are checked or selected.
:disabled Selects all elements that are disabled.
:enabled Selects all elements that are enabled.
:focus Selects element if it is currently focused.
:file Selects all elements of type file.
:image Selects all elements of type image.
:input Selects all input, textarea, select and button elements.
:password Selects all elements of type password.
:radio Selects all elements of type radio.
:reset Selects all elements of type reset.
:selected Selects all elements that are selected.
:submit Selects all elements of type submit.
:text Selects all input elements of type text.

# Attributes in jQuery


Examples

$(document).ready(function () {
    $("button").click(function () {
        $('p').css({
            color: 'yellow',
            backgroundColor: 'red',
            fontSize: '50px'
        });
    });
});


// jQuery addClass
$("button").click(function () {
    $("p:first").addClass("active");
});


// jQuery removeClass
$("button").click(function () {
    $("h1").removeClass("page-header");
    $("p").removeClass("hint highlight");
});


// jQuery toggleClass
$('.choice').toggleClass('highlighted');

Attributes

.attr() Get the value of an attribute for the first element in the set of matched elements.
.prop() Get the value of a property for the first element in the set of matched elements.
.removeAttr() Remove an attribute from each element in the set of matched elements.
.removeProp() Remove a property for the set of matched elements.
.val() Get the current value of the first element in the set of matched elements.

Attributes Data

jQuery.data() Store arbitrary data associated with the specified element. Returns the value that was set.
.data() Store arbitrary data associated with the matched elements.
jQuery.hasData() Determine whether an element has any jQuery data associated with it.
jQuery.removeData() Remove a previously-stored piece of data.
.removeData() Remove a previously-stored piece of data.

CSS

.addClass() Adds the specified class(es) to each element in the set of matched elements.
.hasClass() Determine whether any of the matched elements are assigned the given class.
.removeClass() Remove a single class, multiple classes, or all classes from each element in the set of matched elements.
.toggleClass() Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the state argument.
.css() Get the computed style properties for the first element in the set of matched elements.
jQuery.cssHooks Hook directly into jQuery to override how particular CSS properties are retrieved or set, normalize CSS property naming, or create custom properties.
jQuery.cssNumber An object containing all CSS properties that may be used without a unit. The .css() method uses this object to see if it may append px to unitless values.
jQuery.escapeSelector() Escapes any character that has a special meaning in a CSS selector.

Dimensions

.height() Get the current computed height for the first element in the set of matched elements.
.innerHeight() Get the current computed height for the first element in the set of matched elements, including padding but not border.
.innerWidth() Get the current computed inner width for the first element in the set of matched elements, including padding but not border.
.outerHeight() Get the current computed outer height (including padding, border, and optionally margin) for the first element in the set of matched elements.
.outerWidth() Get the current computed outer width (including padding, border, and optionally margin) for the first element in the set of matched elements.
.width() Get the current computed width for the first element in the set of matched elements.

Offset

.offset() Get the current coordinates of the first element in the set of matched elements, relative to the document.
.offsetParent() Get the closest ancestor element that is positioned.
.position() Get the current coordinates of the first element in the set of matched elements, relative to the offset parent.
.scrollLeft() Get the current horizontal position of the scroll bar for the first element in the set of matched elements.
.scrollTop() Get the current vertical position of the scroll bar for the first element in the set of matched elements or set the vertical position of the scroll bar for every matched element.

# Manipulation in jQuery


Manipulation Example

// <span>Hello</span>
$('span').after('<p>bestforstudy.com</p>');
// Output: <span>Hello,</span><p>bestforstudy.com</p>


// <span>Welcome to bestforstudy.com</span>
$('span').wrap('<p></p>');
// Output: <p><span>Welcome to bestforstudy.com</span></p>


// <p>Welcome to </p>
$("p").append("<b>bestforstudy.com</b>.");
// Output: Welcome to bestforstudy.com


$('<span>Hello World</span>').replaceAll('p');
// Output: <p>Hello World</p>

Copying

.clone() Create a deep copy of the set of matched elements.

DOM Insertion, Around

.wrap() Wrap an HTML structure around each element in the set of matched elements.
.wrapAll() Wrap an HTML structure around all elements in the set of matched elements.
.wrapInner() Wrap an HTML structure around the content of each element in the set of matched elements.

DOM Insertion, Outside

.after() Insert content, specified by the parameter, after each element in the set of matched elements.
.before() Insert content, specified by the parameter, before each element in the set of matched elements.
.insertAfter() Insert every element in the set of matched elements after the target.
.insertBefore() Insert every element in the set of matched elements before the target.

DOM Insertion, Inside

.append() Insert content, specified by the parameter, to the end of each element in the set of matched elements.
.appendTo() Insert every element in the set of matched elements to the end of the target.
.html() Get the HTML contents of the first element in the set of matched elements.
.prepend() Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.
.prependTo() Insert every element in the set of matched elements to the beginning of the target.
.text() Get the combined text contents of each element in the set of matched elements, including their descendants.

DOM Removal

.detach() Remove the set of matched elements from the DOM.
.empty() Remove all child nodes of the set of matched elements from the DOM.
.remove() Remove the set of matched elements from the DOM.
.unwrap() Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place.

DOM Replacement

.replaceAll() Replace each target element with the set of matched elements.
.replaceWith() Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed.

# Traversing in jQuey


Filtering

.eq() Reduce the set of matched elements to the one at the specified index.
.filter() Reduce the set of matched elements to those that match the selector or pass the function's test.
.first() Reduce the set of matched elements to the first in the set.
.has() Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element.
.is() Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.
.last() Reduce the set of matched elements to the final one in the set.
.map() Pass each element in the current matched set through a function, producing a new jQuery object containing the return values.
.not() Remove elements from the set of matched elements.
.slice() Reduce the set of matched elements to a subset specified by a range of indices.

Miscellaneous Traversing

.add() Create a new jQuery object with elements added to the set of matched elements.
.addBack() Add the previous set of elements on the stack to the current set, optionally filtered by a selector.
.andSelf() Add the previous set of elements on the stack to the current set.
.contents() Get the children of each element in the set of matched elements, including text and comment nodes.
.each() Iterate over a jQuery object, executing a function for each matched element.
.end() End the most recent filtering operation in the current chain and return the set of matched elements to its previous state.

Tree Traversal

.children() Get the children of each element in the set of matched elements, optionally filtered by a selector.
.closest() For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.
.find() Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.
.next() Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.
.nextAll() Get all following siblings of each element in the set of matched elements, optionally filtered by a selector.
.nextUntil() Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed.
.parent() Get the parent of each element in the current set of matched elements, optionally filtered by a selector.
.parents() Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector.
.parentsUntil() Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object.
.prev() Get the immediately preceding sibling of each element in the set of matched elements. If a selector is provided, it retrieves the previous sibling only if it matches that selector.
.prevAll() Get all preceding siblings of each element in the set of matched elements, optionally filtered by a selector.
.prevUntil() Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object.
.siblings() Get the siblings of each element in the set of matched elements, optionally filtered by a selector.

# Events in jQuery


Examples

// Mouse "Click" Event Example
$('#helloButton').on('click', () => {
    alert('Hello Wellcome to bestforstudy.com !!!');
});


// Keyboard 'keyup' event Example
$('#messageButton').on('keyup', () => {
    alert('Hello Wellcome to bestforstudy.com !!!');
});
  

//   Scroll event
$('#scrollButton').on('scroll', () => {
    console.log("We are scrolling")
});

Examples Event object

$('#helloButton').on('click', event => {
  alert('Hello Wellcome to bestforstudy.com !!!');
  $(event.currentTarget).hide();
});

Example Method chaining

$('#exampleButton').on('mouseenter', () => {
    console.log("Menu is showing");
    $('#menu').show();
}).on('mouseleave', () => {
    console.log("Menu is hiding");
    $('#menu').hide();
});

Example Prevents the event

$( "p" ).click(function( event ) {
    event.stopPropagation();

    // Do something
    console.log("Your logic will be here...")
});

Browser Events

.error() Bind an event handler to the error JavaScript event.
.resize() Bind an event handler to the resize JavaScript event, or trigger that event on an element.
.scroll() Bind an event handler to the scroll JavaScript event, or trigger that event on an element.

Document Loading

.load() Bind an event handler to the load JavaScript event.
.ready() Specify a function to execute when the DOM is fully loaded.
.unload() Bind an event handler to the unload JavaScript event.

Event Handler Attachment

.bind() Attach a handler to an event for the elements.
.delegate() Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.
.die() Remove event handlers previously attached using .live() from the elements.
.live() Attach an event handler for all elements which match the current selector, now and in the future.
.off() Remove an event handler.
.on() Attach an event handler function for one or more events to the selected elements.
.one() Attach a handler to an event for the elements. The handler is executed at most once per element per event type.
.trigger() Execute all handlers and behaviors attached to the matched elements for the given event type.
.triggerHandler() Execute all handlers attached to an element for an event.
.unbind() Remove a previously-attached event handler from the elements.
.undelegate() Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements.

Form Events

.blur() Bind an event handler to the blur JavaScript event, or trigger that event on an element.
.change() Bind an event handler to the change JavaScript event, or trigger that event on an element.
.focus() Bind an event handler to the focus JavaScript event, or trigger that event on an element.
.focusin() Bind an event handler to the focusin event.
.focusout() Bind an event handler to the focusout JavaScript event.
.select() Bind an event handler to the select JavaScript event, or trigger that event on an element.
.submit() Bind an event handler to the submit JavaScript event, or trigger that event on an element.

Keyboard Events

.keydown() Bind an event handler to the keydown JavaScript event, or trigger that event on an element.
.keypress() Bind an event handler to the keypress JavaScript event, or trigger that event on an element.
.keyup() Bind an event handler to the keyup JavaScript event, or trigger that event on an element.

Mouse Events

.click() Bind an event handler to the click JavaScript event, or trigger that event on an element.
.contextMenu() Bind an event handler to the contextmenu JavaScript event, or trigger that event on an element.
.dblclick() Bind an event handler to the dblclick JavaScript event, or trigger that event on an element.
.hover() Bind two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements.
.mousedown() Bind an event handler to the mousedown JavaScript event, or trigger that event on an element.
.mouseenter() Bind an event handler to be fired when the mouse enters an element, or trigger that handler on an element.
.mouseleave() Bind an event handler to be fired when the mouse leaves an element, or trigger that handler on an element.
.mousemove() Bind an event handler to the mousemove JavaScript event, or trigger that event on an element.
.mouseout() Bind an event handler to the mouseout JavaScript event, or trigger that event on an element.
.mouseover() Bind an event handler to the mouseover JavaScript event, or trigger that event on an element.
.mouseup() Bind an event handler to the mouseup JavaScript event, or trigger that event on an element.
.toggle() Bind two or more handlers to the matched elements, to be executed on alternate clicks.

# Events Objects in jQuery


Event Object

event.currentTarget The current DOM element within the event bubbling phase.
event.delegateTarget The element where the currently-called jQuery event handler was attached.
event.data An optional object of data passed to an event method when the current executing handler is bound.
event.isDefaultPrevented() Returns whether event.preventDefault() was ever called on this event object.
event.isImmediatePropagationStopped() Returns whether event.stopImmediatePropagation() was ever called on this event object.
event.isPropagationStopped() Returns whether event.stopPropagation() was ever called on this event object.
event.metaKey Indicates whether the META key was pressed when the event fired.
event.namespace The namespace specified when the event was triggered.
event.pageX The mouse position relative to the left edge of the document.
event.pageY The mouse position relative to the top edge of the document.
event.preventDefault() If this method is called, the default action of the event will not be triggered.
event.relatedTarget The other DOM element involved in the event, if any.
event.result The last value returned by an event handler that was triggered by this event, unless the value was undefined.
event.stopImmediatePropagation() Keeps the rest of the handlers from being executed and prevents the event from bubbling up the DOM tree.
event.stopPropagation() Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
event.target The DOM element that initiated the event.
event.timeStamp The difference in milliseconds between the time the browser created the event and January 1, 1970.
event.type Describes the nature of the event.
event.which For key or mouse events, this property indicates the specific key or button that was pressed.

# Effects in jQuery


Some Effect Example

// fadeIn effect
$('#effectButton').on('click', () => {
    $('#effectMenu').fadeIn();
});

// faceOut effect
$('#effectButton').on('click', () => {
    $('#effectMenu').fadeOut();
});

// toggle
$("#clickme").click(function() {
    $("#book").toggle( "slow", function() {
        // Animation complete.
    });
});

// animate
$("button").click(function(){
    $("#box").animate({height: "100px"});
});

Basics

.hide() Hide the matched elements.
.show() Display the matched elements.
.toggle() Display or hide the matched elements.

Sliding

.slideDown() Display the matched elements with a sliding motion.
.slideToggle() Display or hide the matched elements with a sliding motion.
.slideUp() Hide the matched elements with a sliding motion.

Custom

.animate() Perform a custom animation of a set of CSS properties.
.clearQueue() Remove from the queue all items that have not yet been run.
.delay() Set a timer to delay execution of subsequent items in the queue.
.dequeue() Execute the next function on the queue for the matched elements.
jQuery.dequeue() Execute the next function on the queue for the matched element.
.finish() Stop the currently-running animation, remove all queued animations, and complete all animations for the matched elements.
jQuery.fx.interval The rate (in milliseconds) at which animations fire.
jQuery.fx.off Globally disable all animations.
jQuery.speed Creates an object containing a set of properties ready to be used in the definition of custom animations.
.queue() Show the queue of functions to be executed on the matched elements.
jQuery.queue() Show the queue of functions to be executed on the matched element.
.stop() Stop the currently-running animation on the matched elements.

Fading

.fadeIn() Display the matched elements by fading them to opaque.
.fadeOut() Hide the matched elements by fading them to transparent.
.fadeTo() Adjust the opacity of the matched elements.
.fadeToggle() Display or hide the matched elements by animating their opacity.


Best Suggest