Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How the heck is this jQuery selector working?

Tags:

jquery

dom

I am writing a simple tooltip:

$(function() {

$('a').hover(function() {
    var curLink = $(this);
    var toolTipText = curLink.attr('title');
    if (toolTipText)
    {
        var theOffset = curLink.offset();

        $('body').prepend('<div id="toolTip">'+toolTipText+'</div>');           

        // how the heck is this working???
        $('#toolTip').css({
            'left' : theOffset.left+'px',
            'top' : theOffset.top - 30+'px'
        });     
    }   
}, function() {
    $('#toolTip').remove(); 
});

});

As you can see a div with the id of "toolTip" is dynamically added to the DOM when a user hovers over a link. That div isn't there initially when the DOM loads but is added later. So I assumed I had to use the live() function and attach an event to it. But some how it works if I just treat it as a regular selector. Not that I'm complaining but how is this working?

like image 546
Sammy Avatar asked Aug 16 '11 02:08

Sammy


1 Answers

You don't need live because that selector doesn't run before the element is in the DOM.

  • OnMouseOver tooltip is added into the DOM.
  • Onmouseout that selector runs and tooltip is removed from the DOM. It works fine because by the time the mouseout function is called the tooltip has been added to the DOM already by the mouseover.

You would only need to use 'live()' if your <a> element wasn't in the DOM yet when you attach the events. IE. Any anchors added to your page after that code executes won't have tooltips.

like image 174
Paul Avatar answered Sep 30 '22 21:09

Paul