1

Say I want to change a container's class when the image it contains is loaded, probably something like this:

$('.image').load(function(){
    $(this).parents('.image-wrapper').removeClass('image-wrapper').addClass('image-wrapper-new');
});

…And then add a click event, referencing the newly-added class, like this:

$('.image-wrapper-new').click(function(){
    //Do stuff
});

I've tried something similar to this, with no success. Am I missing something?

Using Developer Tools, it appears that the browser is rendering it as .image-wrapper-new, but since it retains the .image-wrapper class in the physical code, Jquery/JS doesn't honor it. Is that possible?

Thanks.

-Ryan

3
  • Your JS is syntactically invalid - you're missing a closing single quote. Is that what your actual code looks like, or did you just type it into the question incorrectly? Commented Feb 22, 2011 at 15:49
  • 1
    No, that's not possible. Please show us an example. Commented Feb 22, 2011 at 15:50
  • Oops, you're right about the single quote. This is not my actual code, but this is identical to what I was trying to do. Is there another way to do it? Commented Feb 22, 2011 at 15:52

3 Answers 3

4

To fix the syntax error:

$('.image').load(function(){
    $(this).parents('.image-wrapper').removeClass('image-wrapper').addClass('image-wrapper-new');
});

I would also recommend using .on() rather than .click() so you don't have to re-bind event handlers every time you change the class:

$(document).on('click', '.image-wrapper-new', function(){
    //Do stuff
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for mentioning .live. That seems to have done the trick.
@dvdnhm .live() is deprecated and was removed in jQuery 1.9. You should use .on() instead. I've updated my answer accordingly.
1

You should be using .live('click', function() {}); due to the fact that you are updating the DOM. .click() will not pick up on new data automatically. If you are building an ajax application this should be standard imo

Comments

0

Just add your click event handler in the same function, as you change class:

$('.image').load(function(){
    $(this).parents('.image-wrapper')
           .removeClass('image-wrapper')
           .addClass('image-wrapper-new')
           .click(function(){
               //Do stuff
            });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.