RhymeGuy
RhymeGuy

Reputation: 2112

jQuery - Hover after DOM change

With $('#sidebar').toggleClass('small'); Im adding adding/removing specified class from #sidebar.

When #sidebar has class small I should be able to perform additional actions when user hover over #sidebar.small.

I have tried to accomplish that with code bellow:

$("#sidebar.small").on({
    mouseenter: function () {
        alert(1);  //doesn't work
},
    mouseleave: function () {
        //stuff to do on mouse leave
    }
});

But that doesn't work.

How should I perform hover function on changed DOM element?

Upvotes: 2

Views: 991

Answers (2)

Plato
Plato

Reputation: 11052

Jquery only binds the handlers for the found elements at the time of binding.

The solution is to rebind the appropriate handlers when you add the class.

jsfiddle

code from the fiddle:

$('#foo').click(function(){
    $('<span></span>')
    .text('A Span')
    .appendTo('#container');
});

$('#bar').click(function(){
   $('span').first().toggleClass('small');
   bindHover();    
})

function bindHover(){
    $('span.small').unbind('hover'); // Avoid re-binding something
    $('span.small').hover(function(){
        alert('a')
    });
}

bindHover();

Upvotes: 0

Brian
Brian

Reputation: 1553

You should be able to use the jquery hover method to do this: https://api.jquery.com/hover/

Update: Sorry noticed one other thing... when you originally set your event handler, does #sidebar have the css tag or not? The way your code is written, if it doesn't, it will try to attach to the element $("#sidebar.small"), so if the css tag is not there it won't attach to anything.

I think you want more like this:

$("#sidebar").on({
    mouseenter: function() {
       if($('#sidebar').hasClass('small')) {
           alert(1);
       }
    }
});

Update again for a typo, sorry...

Upvotes: 1

Related Questions