Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    met
    met is offline
    Regular Coder
    Join Date
    Oct 2009
    Location
    United Kingdom
    Posts
    728
    Thanks
    4
    Thanked 119 Times in 119 Posts

    jquery toggle/hide problem

    hi

    can someone more enlightened than myself work out why this won't work?

    Code:
        $("h2.portfolio-title").click(function() {
    	$('#portfolio').toggle("slow");
    	$(this).replaceWith("<h2 class='portfolio-title1' >" + $(this).text() + "</div>");
       });
       
        $("h2.portfolio-title1").click(function() {
    	$('#portfolio').hide("slow");
    	$(this).replaceWith("<h2 class='portfolio-title' >" + $(this).text() + "</div>");
    
       });
    essentially. I click the H2 with a class of "portfolio-title", and the #portfolio DIV scrolls nicely in to place, and I replace the class "portfolio-title" with "portfolio-title1".

    This is reflected in the source, so the first part is definitely working - I am able to toggle a DIV on a click and replace its class with another.

    I would then like to be able to click the header again, and hide the DIV and replace the class so the user is able to show/hide a div at will.

    Toggle on its own works fine, but I would like to apply a different class to the "shown" header so the user is aware that they have clicked it.

    What's wrong?

    thanks.
    Last edited by met; 10-28-2009 at 01:28 AM.

  • #2
    UE Antagonizer Fumigator's Avatar
    Join Date
    Dec 2005
    Location
    Utah, USA, Northwestern hemisphere, Earth, Solar System, Milky Way Galaxy, Alpha Quadrant
    Posts
    7,691
    Thanks
    42
    Thanked 637 Times in 625 Posts
    The problem is this code is all loaded and interpreted right as soon the page loads. Well, when the page loads, the selector $("h2.portfolio-title1") has no match! You haven't created it yet! Vexing.

    Fortunately the latest version of jQuery has a function called live() that you can replace the bind() function with (that click() function you are using is just a shortcut for bind(click(function{})) ). This live() function performs some magic to re-evaluate itself whenever the DOM is modified (or something like that... don't really know exactly how jQuery does its magic).

    http://docs.jquery.com/Events/live#typefn

  • Users who have thanked Fumigator for this post:

    met (10-28-2009)

  • #3
    met
    met is offline
    Regular Coder
    Join Date
    Oct 2009
    Location
    United Kingdom
    Posts
    728
    Thanks
    4
    Thanked 119 Times in 119 Posts
    makes perfect sense, thank you!

    and yes that worked perfectly, cheers.


  •  

    Posting Permissions

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