Paul Mason
Paul Mason

Reputation: 1818

jQuery - how to refresh selectors after adding a class

I've made this example in jsfiddle to demonstrate my problem: http://jsfiddle.net/paulmason411/7E6vG/

See how the grey class is added and yet it doesn't apply the left margin when u hover a second time. I'm guessing this is because the $('.block.grey') selector is declared before the class is grey class is added.

Is there anyway I can get the $('.block.grey') selector to re-parse the dom after the class is added?

Any help would be great, cheers!

EDIT: I have a more complicated example

$('.accordion h3').not('.ui-state-active').find('a').live('hover', function(){

Where the ui-state-active class is added dynamically. bitsMix has pointed out that this code is making the a live. So I've updated it to

$('.accordion h3').live('hover', function(){
  $(this).not('.ui-state-active').find('a').stop().animate({

and it works! Thanks guys!

Upvotes: 1

Views: 4996

Answers (4)

Ahmet Kakıcı
Ahmet Kakıcı

Reputation: 6404

Here it comes:

$('.block').hover(function(){
    $(this).css('background-color', '#CCC'); 
    $(this).addClass('grey');
});

$('.block.grey').live('hover',function(){
    $(this).css('margin-left', '10px');    
});

jQuery Live

Upvotes: 2

Kimtho6
Kimtho6

Reputation: 6184

you need to add live to the like this:

$('.block.grey').live( "hover",function(){
    $(this).css('margin-left', '10px');    
});

fiddle

Upvotes: 2

Ya Zhuang
Ya Zhuang

Reputation: 4660

$('.grey').live('hover',function(){
    $(this).css('margin-left', '100px');    
});

http://jsfiddle.net/bitsmix/7E6vG/2/ live demo :)

Upvotes: 2

Richard Dalton
Richard Dalton

Reputation: 35803

You can use .live()

$('.block.grey').live('hover', function() {
    $(this).css('margin-left', '10px');    
});

http://jsfiddle.net/7E6vG/1/

Upvotes: 1

Related Questions