Hellnar
Hellnar

Reputation: 64793

Jquery: delegate and this

Having a such jQuery snipplet, I really need to improve the quality:

$foo.focus(function() {
    if (!user_input)
    {
        jQuery(this).val('');
        user_input = true;
    }
    else
    {
        jQuery(this).live("mouseup", function () {
            $(this).select();
        });
    }
})

How can I change live part to delegate ? I'm confused about the part about pointing to a parent element.

Upvotes: 0

Views: 2068

Answers (2)

Matthew Booth
Matthew Booth

Reputation: 71

I know this thread is SUPER old, but I was having a particular problem and this thread came up in the search results. If I understand the question correctly, there is confusion using the delegate feature of jQuery's on() method and what this refers to. Maybe this will help someone else that finds this thread.

Given the code below:

$('#parentElement').on('click', '.childElement', function(){
    console.log(this);
});

With delegated events, you might be tempted into thinking that this will point to the parent element (#parentElement), but it doesn't. this still refers to the element (.childElement) that was clicked (or whatever the event listener is).

For most elements, clicking on them triggers a click event, but that event "bubbles" up to parent elements. The idea behind delegate is that the event listener is the parent element since it cannot not be a dynamic element. If children elements are then added dynamically, clicking them will also trigger an event on their parent.

Using the additional ".selector" parameter of the on() method will limit executing the callback (the function(){} block of code) to elements in the ".selector" jQuery object.

Upvotes: 2

rkw
rkw

Reputation: 7297

To convert from .live() to .delegate(), you just have to have an outer container.

jQuery("selector").live("mouseup", function () {})

is equivalent to

jQuery(document).delegate("mouseup", "selector", function() {})

The benefit of using delegate is that you can target when to catch that event. .live() bubbles up all the way to the document, but with delegate, you can stop it at some containing div for example.

In your scenario, just replace document with whatever is containing $foo.

That answers your question, but in reality, you should include what your are, functionally, trying to achieve with that code up there so we can help you out better.

My only guess is that you want to highlight text when the user clicks into a textbox?

also: If you have the jQuery 1.7, use .on() instead. It replaces .bind(), .live(), and .delegate()

Upvotes: 0

Related Questions