Cool, easy way to toggle elements using show and hide

I was looking around, trying to find a way to have 2 form elements hidden when a page loaded, then show and hide them as needed by clicking on a (link,radio button, etc). Using jQuery, this was insanely easy.

1. Wrap the element(s) you want to show and hide with span or div tags and set style to display none. Make sure to give each span/div a unique id, eg:

<span id=’one’>Text 1</span>
<span id=’two’>Text 2</span>

2. Somewhere above these elements, you’ll need to put the following:

$(document).ready(function() {
$(“#itemtoclick1”).click(function() {
$(“#one”).show();
$(“#two”).hide();
});
$(“#itemtoclick2”).click(function() {
$(“#one”).show();
$(“#two”).hide();
});
});

For my needs, I had 2 radio buttons, and both id’s one and two were hidden when the page loaded. When a user clicked on one of the radio buttons (given id “itemtoclick1” and “itemtoclick2”, respectively), the appropriate section would appear.

For cooler effects you can add ‘fast’ or ‘slow’ between the show/hide parentheses.

Hope this was helpful! 🙂

Advertisements