Dynamic toggling of divs using jQuery animation.

Recently I had to create a toggling of a div based upon a series of radio buttons the user clicks. All of the divs I needed to toggle were in the same place, with a slide animation to toggle them. I knew I could count on putting the values in the input types. This was the key.

 

First let’s define our variables. Our listener will be, of course, the input elements the user clicks on. Lets give them a value of “selectedForm”. Ignore the quotations in your code but you already knew that, you’re a pro!

Now  wrap each div you need to toggle into separate wrapping divs. This will give you an easy place to grab each form once you know which one to grab.

Now that we know the value of the listener, lets make a logical id selection for the wrapper of each div. The selection I chose was “+X+”Form”, appending the word Form at the end of the EXACT string value of the inputs.

Two variables we need to know to toggle is which div is CURRENTLY being viewed and which div we WANT to see.

I added a class to the currently visible div. That class is “visible”. Now time for the fun part!

Ask the computer, if the visible  div is the same as the div we want to see. If so, do nothing.
Secondly, as if there even IS a visible div. If there is, hide the div. Then, once the div is hidden, use  a callback to show the div we want.

And last, if there isn’t even a visible div, just show the div we want!.

The Javascript function looked like this.

function selectformToggle(selectedForm)
{
	if($(".visible").attr("id") == selectedForm+"Form")
	{
		return;
	}else if($(".visible").length > 0 && $(".visible").css("display") != "none")
	{
		$(".visible").slideUp(300, "linear", function(){$("#"+selectedForm+"Form").slideDown(300); $(".visible").removeClass("visible"); $("#"+selectedForm+"Form").addClass("visible");});
	}else{
		$("#"+selectedForm+"Form").slideDown(300);
		$("#"+selectedForm+"Form").addClass("visible");
	}
}