I'm writing a jQuery plugin, but I'm having a problem:
My HTML element
<a id="trac"></a>
My JS that calls the plugin
$('#trac').myplugin();
My plugin
$.fn.myplugin = function(){
var $root;
return this.each(function(){
$root = $(this);
$root.live('click',function(){
console.log('here');
});
});
}
It happens that "here" is never displayed. But if I use...
$('#trac').live('click',function(){
console.log('here');
});
..."here" is displayed. I don't understand why it is happening because $root and $('#trac') are exactly the same jQuery object.
How can I fix it?
Thanks!
jQuery click not working at the time page loading, jQuery Onclick Method is tried to an element or selector. As a result, the binding will fail if the element we wish to click isn't present when the page is ready.
click events only work when element gets rendered and are only attached to elements loaded when the DOM is ready. . on events are dynamically attached to DOM elements, which is helpful when you want to attach an event to DOM elements that are rendered on ajax request or something else (after the DOM is ready).
So onclick creates an attribute within the binded HTML tag, using a string which is linked to a function. Whereas . click binds the function itself to the property element.
The HTMLElement.click() method simulates a mouse click on an element. When click() is used with supported elements (such as an <input> ), it fires the element's click event. This event then bubbles up to elements higher in the document tree (or event chain) and fires their click events.
The ".live()" function needs a selector, and in your plugin you're not giving it one. The jQuery object you build ($(this)
) is a valid object but there's no selector string involved.
You could directly bind the handler:
$root.click(function() { ... });
To elaborate: you say, "... because $root and $('#trac') are exactly the same." The problem is that that is not really true. When you build a jQuery object with a selector string, the object keeps that selector string around. There's no string when you build "$root" from "$(this)". The ".live()" function operates by creating a handler on the <body>
element and then testing the target of each event that bubbles up against that selector.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With