|
jQuery - Changing image src with toggle function
|
|
| |
Rating: 31 user(s) have rated this article
4.4 out of 5 stars
Posted by: jstrosch01,
on 6/26/2008,
in category "jQuery"
Views: this article has been read 24004 times
Using jQuery to do more than just toggle the display of an element is fairly straight-forward. All of the code here is depenedent on the core jQuery library, which can be found at jQuery.com. Make sure you include this in your head tags like so:
< script type="text/javascript" src="jquery.js" >< /script>
Here is some sample html to help illustrate this example:
|
< div id="toggler">
< img src="arrowDown.gif" id="imgArrows" / > Click Me
< /div>
< div id="box" style="width:200px;height:200px;display:none;background-color:#CCC;">
Some Content...
< /div>
|
Now all you have to do is write a few lines of jQuery:
|
< script type="text/javascript">
$(document).ready(function(){
$('#toggler').toggle(
function(){ // you can add as much here as you'd like
$('#box').show('slow');
$('#imgArrow').attr('src','path/to/image');
}, function() { // same here
$('#box').hide('slow');
$('#imgArrow').attr('src','path/to/different_image');
});
});
< /script>
|
So, combine this and you get the following:
|
< html xmlns="http://www.w3.org/1999/xhtml">
< head>
< script type="text/javascript" src="jquery.js" >< /script>
< script type="text/javascript">
$(document).ready(function(){
$('#toggler').toggle(
function(){ // you can add as much here as you'd like
$('#box').show('slow');
$('#imgArrow').attr('src','path/to/image');
}, function() { // same here
$('#box').hide('slow');
$('#imgArrow').attr('src','path/to/different_image');
});
});
< /script>
< /head>
< body>
< div id="toggler">
< img src="arrowDown.gif" id="imgArrows" /> Click Me
< /div>
< div id="box" style="width:200px;height:200px;display:none;background-color:#CCC;">
Some Content...
< /div>
< /body>
< /html>
|
Live Example:
Click here to toggle
Some content here