pavan kumar k pavan kumar k - 3 months ago 21
jQuery Question

Jquery resize() api confusion

Following jquery code displaying two alert() boxes. why?

$(window).resize(function(){
alert("called-1");
});

$(window).bind("resize.test",function(){
alert("called-2");
});


My question is why Jquery calling custom events(i.e event name starts with "resize") after resize() triggers?

jQuery version : 1.12.4

Answer

Your example code binds two event listeners for resize. The first one uses the resize() function and the second uses bind(), what is both basically the same. A third option would be to use on().

The only difference is that you gave the second listener a namespace called test, separated by a dot (.) between event name and namespace. But this is still a resize event listener, and not a custom event!

Namespaces helps you to seperate or group event listeners. For example, you can remove specific listeners:

$(window).on("resize", function() {
    console.log("- resize");
});

$(window).on("resize.test", function() {
    console.log("- resize.test");
});

// trigger resize
console.log("first trigger:");
$(window).trigger("resize");

// remove all listeners with '.test' namespace
$(window).off(".test"); // or more specific: $(window).off("resize.test");

// trigger resize again
console.log("second trigger:");
$(window).trigger("resize");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Official event.namespace doc.