Josh
Josh

Reputation: 1019

How to trigger a class-targeted method AFTER the class has been added to an element?

In the below markup, the #enable button will add a class to the #show div. This class has a method attached to it that fades in/out the #hidden span.

However, even though the class is added to the #show div, the method attached to the class isn't triggered.

HTML

<input type='button' id='enable' value='Enable' />

<div id='show'>
Testing.. <span id='hidden'>Testing, 1, 2, 3.</span>
</div>​

JS

$(function() {

    // Adds .testing class after the button is clicked. however..
    $('#enable').click(function() { 
        $('#show').addClass('testing')
    });

    // It will not trigger after .testing class has been added to DIV?            
    $('.testing').hover(function() { 
        $('#hidden').fadeIn(); 
    }, function() {
        $('#hidden').fadeOut(); 
    });
});​

Fiddle to work with: http://jsfiddle.net/jS3nM/

It seems I am missing something conceptually. What is the correct way to handle this?

Upvotes: 0

Views: 56

Answers (2)

Ram
Ram

Reputation: 144699

Because when you bind the hover handler there is no element with class of testing in the document, you should delegate the event, you can use the on method, try the following"

$(document).on('mouseenter', '.testing', function(e) { 
        $('#hidden').fadeIn(); 
});

$(document).on('mouseleave', '.testing', function(e) { 
        $('#hidden').fadeOut(); 
});

Upvotes: 1

Esailija
Esailija

Reputation: 140228

jQuery does not work like CSS. When you do, $("selector"), it will return a list of elements in the document that match that selector right now.

You will then operate on those elements with jQuery methods. There is no magic like "class-targeted method" going on.

You can find add a event listener to document:

$(document).on({
    mouseenter: function() {
        $('#hidden').fadeIn();
    },
    mouseleave: function() {
        $('#hidden').fadeOut();
    }
}, ".testing");

document is always found and always exists, and the event listener is added to that. The selector at the end filters out what elements are qualified for the event.

Upvotes: 2

Related Questions