SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Guru downtroden's Avatar
    Join Date
    Dec 2004
    Location
    illinois
    Posts
    974
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    what I THOUGHT was a basic jquery function

    I'm trying to swap the class of an element when it's clicked on. Using jquery 1.6.1, here's what it looks like:

    Code JavaScript:
    	$('.checked_container').click(function() {
    		$(this).removeClass('checked_container').addClass('unchecked_container');
    	});
     
    	$('.unchecked_container').click(function() {
    		$(this).removeClass('unchecked_container').addClass('checked_container');
    	});

    Now, for the sake of brevity…*i omitted some other stuff that is happening when they're clicked on. The problem is that the click event for .unchecked_container is firing fine and the class is changed, BUT when clicked on again…*the '.checked_container' click event is NOT firing.

    I think this is pretty basic, but for some reason it's not working.

    Any ideas?
    your brain reacts in the same way whether you are
    looking at something or thinking about it...

  2. #2
    Utopia, Inc. silver trophy
    ScallioXTX's Avatar
    Join Date
    Aug 2008
    Location
    The Netherlands
    Posts
    9,085
    Mentioned
    153 Post(s)
    Tagged
    2 Thread(s)
    The event for .unchecked_container is not firing because at the moment the script is run there is no element with that class yet. There only is an element with that class after an element with .checked-container is clicked, but then it's too late.
    You might want to look at .live() to solve this. Something like

    Code css:
    $('.checked_container .unchecked_container').live(function() {
      $(this).toggleClass('checked_container unchecked_container');
    });

    If you're using jQuery > 1.4.2 .delegate() would be even better.
    Suppose these elements are in an element with id "main", you'd use

    Code css:
    $('#main').delegate('.checked_container .unchecked_container', 'click', function() {
      $(this).toggleClass('checked_container unchecked_container');
    });

    HTH
    Rémon - Hosting Advisor

    SitePoint forums will switch to Discourse soon! Make sure you're ready for it!

    Minimal Bookmarks Tree
    My Google Chrome extension: browsing bookmarks made easy


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •