J Anderson J Anderson - 1 year ago 59
Javascript Question

What does the jQuery method $.on return?

What does the jQuery method $.on return?


$(document).on("CustomEvent", CustomFunction);

Answer Source

What does the jQuery method $.on return?

$(document).on(...) returns the jQuery object created by $(document). This makes it chainable as in:

$(document).on("click", clickHandler).on("hover", hoverHandler);

In fact all jQuery methods that don't have a specific value to return will return the jQuery object so they can be chainable in this fashion.

Another commonly used example:


But, a method that has a specific value to return such as .prop() or .attr() will return that specific value:

var isChecked = $("#myCheckbox").prop("checked");
var imgSrc = $("#myImg").attr("src");

The return value for any jQuery API is listed in the documentation (here's a screen shot from the doc page for .on():

enter image description here

If you want to prevent an event handler from getting called again, you can either use .one() which will only trigger the event once or you can use .off(...) to remove the event handler as desired or you can use some sort of flag in your own code to tell the event handler whether it should do its work or not.

The cleanest architectural solution to preventing repeat calls to something triggered by .load() is to move the event handler setup code to a different area of your Javascript so it is not loaded again by .load() and is only loaded once by the parent page. That way it only gets called once. Exactly how to do that depends upon the specific circumstances of your design which you have not disclosed so we can't advise more specifically than that.