Jquery Switching Content

Whenever i need to do something using javascript i try to create it myself before searching the web for something that might meet my needs and in time these bits and pieces of code improve. Which is something im going to go over today.

Switching content with javascript is something i have done quite alot but not much using jquery. Infact i haven’t been using jquery that long at all, i had always used regular javascript or scriptaculous libraries to do certain effects.

Anyway i had created something sloppy to switch content but involved me having all kinds of classes or ids which seemed unneccessary. Which led me to create the following for switching over content.

The html is essentially just a list item with links for switching the content and the new content hidden under that item in a div.

<ul id="test">
    	<li>
    		<a href="#"></a>
    		<div>
    			This is the new content from link 1
    		</div>
    	</li>
    	<li>
    		<a href="#"></a>
    		<div>
    			New content new stuff from link 2
    		</div>
    	</li>
    	<li>
    		<a href="#"></a>
    		<div>
    			suprise suprise this is the content to change when you click on the 3rd link
    		</div>
    	</li>
</ul>
<div id="content">
    	This is the current content
</div>

Make sure you set the css to hide the content that is going to change

ul#test li div {
    	display:none;
}

Then setup the jquery to target all the links in the list and when it is clicked to take the html content of the hidden div and place it into the #content

$("ul#test li a").click(function () {
    	//get the divs html content
    	var html = $(this).parent().find('div').html();
    	//set the link content to the content div
    	$("#content").html(html);
    	//return false to stop the link going to the href
    	return false;
});

Thats it, i haven’t actually tested this example but its based on what i have created before. So hopefully it should work and best of all its very simple requires just a few lines and doesn’t need any additional ids or classes or anything like that.

Comments

    Comments are currently closed