Tag Archives: jQuery

jQuery is not defined

There could be many reasons for this.

  • You have forgot to include the reference of jQuery library and trying to access jQuery.
  • You have included the reference of the jQuery file, but it is after your jQuery code.
  • The order of the scripts is not correct. For example, if you are using any jQuery plugin and you have placed the reference of the plugin js before the jQuery library then you will face this error.

jQuery Caching

Caching is an area which can give you awesome performance, if used properly and at the right place. While using jQuery, you should also think about caching. For example, if you are using any element in jQuery more than one time, then you must cache it. See below code.

$(“#myID”).css(“color”, “red”);
//Doing some other stuff……
$(“#myID”).text(“Error occurred!”);

Now in above jQuery code, the element with #myID is used twice but without caching. So both the times jQuery had to traverse through DOM and get the element. But if you have saved this in a variable then you just need to reference the variable. So the better way would be,

var $myElement = $(“#myID”).css(“color”, “red”);
//Doing some other stuff……
$myElement.text(“Error occurred!”);

So now in this case, jQuery won’t need to traverse through the whole DOM tree when it is used second time. So in jQuery, Caching is like saving the jQuery selector in a variable. And using the variable reference when required instead of searching through DOM again.

jQuery Difference Between event.stopPropagation And event.stopImmediatePropagation

event.stopPropagation() allows other handlers on the same element to be executed, while event.stopImmediatePropagation() prevents every event from running. For example, see below jQuery code block.

$(“p”).click(function(event){
event.stopImmediatePropagation();
});
$(“p”).click(function(event){
// This function won’t be executed
$(this).css(“background-color”, “#f00”);
});

If event.stopPropagation was used in previous example, then the next click event on p element which changes the css will fire, but in case event.stopImmediatePropagation(), the next p click event will not fire.