View Full Version : Resolved jquery toggle/hide problem

10-28-2009, 12:47 AM

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

$("h2.portfolio-title").click(function() {
$(this).replaceWith("<h2 class='portfolio-title1' >" + $(this).text() + "</div>");

$("h2.portfolio-title1").click(function() {
$(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?


10-28-2009, 01:13 AM
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).


10-28-2009, 01:25 AM
makes perfect sense, thank you!

and yes that worked perfectly, cheers.