Change Image Using jQuery
This tutorial will show you how to change images by clicking on a hyperlink, using jQuery. I hope it helps!
First, we will look at the html:
<section id="contentwrapper"> <div id="contentpane"> <img src="img/facebook.jpg" id="image" /> </div> <div id="linkpane"> <p><a href="#" id="fb" class="active">Facebook Image</a></p> <p><a href="#" id="twitter">Twitter Image</a></p> <p><a href="#" id="rss">Really Simple Syndicated Image</a></p> </div> </section> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script>window.jQuery || document.write('<script src="js/vendor/jquery-1.9.1.min.js"><\/script>')</script> <script src="js/plugins.js"></script> <script src="js/main.js"></script>
Nothing fancy, just a section containing a couple of divs with an image in one and some links in the other… but you will notice that there are ids specified for each of the links. These ids will be used to control which image is displayed, so let’s take a look at the javascript (found in js/main.js):
$(document).ready(function() { // when the document is loaded var img; $('#linkpane p a#fb').click(function() { img = 'img/facebook.jpg'; $('#contentpane img').attr("src", img); return false; }); $('#linkpane p a#twitter').click(function() { img = 'img/twitter.jpg'; $('#contentpane img').attr("src", img); return false; }); $('#linkpane p a#rss').click(function() { img = 'img/rss.jpg'; $('#contentpane img').attr("src", img); return false; }); });
Basically what is happening here is when the document is ready, we instruct each of the 3 links in the div with the id of linkpane to change the src attribute of the image tag in the div with the id of contentpane when they are clicked. The “return false” statement stops the default behaviour of the link and keeps the page from refreshing.
I hope this is helpful and if you want to download the project, you may do so by clicking this link. Please feel free to comment below if you have questions or comments!
Thanks,
Bud