Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Click event does not work properly in jQuery plugin

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!

like image 837
Frias Avatar asked Jun 20 '11 12:06

Frias


People also ask

Why click function is not working in jQuery?

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.

What is the difference between .click and .on (' click in jQuery?

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).

What is the difference between .on click function ()) and .click function?

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.

What does .click do in JavaScript?

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.


1 Answers

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.

like image 184
Pointy Avatar answered Sep 30 '22 06:09

Pointy