Toggle Image JavaScript
Here is a quick JavaScript that I had to put together. It toggles between two images when clicked.
One of the odd isuues that I ran into was the image path for comparision. Firefox returns the full path — including “http://”, etc. IE returned what I would expect, which is the path that I assigned. To get around this issue, I had to add extra logic to locate “.com” and remove any domain information.
<script type = 'text/javascript'>
function toggleImage() {
// Toggle Script - Version 1.0 - April 11, 2007.
// Retrieve banner and SRC attribute.
var toggleBanner = document.getElementById('sourceBanner');
var currentImage = toggleBanner.getAttribute('src');
// Retrieve path after domain for comparison.
if (currentImage.indexOf('.com') != -1) {
currentImage = currentImage.split('.com')[1];
}
// Set image values.
var firstImage = '/images/banner_01.jpg';
var firstAlt = 'Alt Text 01';
var secondImage = '/images/banner_02.jpg';
var secondAlt = 'Alt Text 02';;
// Toggle image based on current SRC.
if (currentImage == firstImage) {
toggleBanner.setAttribute('src', secondImage);
toggleBanner.setAttribute('alt', firstAlt);
} else {
toggleBanner.setAttribute('src', firstImage);
toggleBanner.setAttribute('alt', secondAlt);
}
}
</script>
<img id="sourceBanner" onclick="toggleImage();"
style="cursor:pointer;" alt="Alt Text 01"
src="/images/banner_01.jpg" />
I am open to any tips or improvements.
About this entry
You’re currently reading “Toggle Image JavaScript,” an entry on Wercshop
- Published:
- 04.12.07 / 1pm
- Category:
- JavaScript, Web
No comments
Jump to comment form | comments rss [?] | trackback uri [?]