Reputation: 786
I have an image with a few javascript calls on it, most of which work OK.
Basically, what I want it to do, is when clicked swap image and then depending on which image it is currently on, to swap on mouseover too.
Here's my HTML:
<a href="#show" class="show_hide">
<img src="<?php echo WEB_URL; ?>/images/show-more-arrow.jpg" width="61" height="45" id="clicktoggleimage" onclick="changeImage()" onMouseOver="checkMouseOver()" onMouseOut="checkMouseOut()" /></a>
And my Javascript:
function changeImage() {
if (document.getElementById("clicktoggleimage").src == "http://www.pete.com/images/show-less-arrow.jpg") {
document.getElementById("clicktoggleimage").src = "http://www.pete.com/images/show-more-arrow.jpg";
} else {
document.getElementById("clicktoggleimage").src = "http://www.pete.com/images/show-less-arrow.jpg";
}
}
function checkMouseOver() {
if (document.getElementById("clicktoggleimage").src == "http://www.pete.com/images/show-less-arrow.jpg") {
document.getElementById("clicktoggleimage").src = "http://www.pete.com/images/show-less-arrow-over.jpg";
} else if (document.getElementById("clicktoggleimage").src == "http://www.pete.com/images/show-more-arrow.jpg") {
document.getElementById("clicktoggleimage").src = "http://www.pete.com/images/show-more-arrow-over.jpg";
}
}
function checkMouseOut() {
if (document.getElementById("clicktoggleimage").src == "http://www.pete.com/images/show-less-arrow-over.jpg") {
document.getElementById("clicktoggleimage").src = "http://www.pete.com/images/show-less-arrow.jpg";
} else if (document.getElementById("clicktoggleimage").src == "http://www.pete.com/images/show-more-arrow-over.jpg") {
document.getElementById("clicktoggleimage").src = "http://www.pete.com/images/show-more-arrow.jpg";
}
}
This works fine, except when the button is clicked for the second time, the image doesn't revert back to the show-less-arrow.jpg
Many thanks for your help
Upvotes: 0
Views: 2876
Reputation: 72849
You can make this JS a lot more efficient.
Since it appears you're only replacing 'more'
with 'less'
and vice versa, in your changeImage
function, that is exactly what your function should do. The mouse over/off is only toggling the '-over'
section of your string.
So, remove the event listeners from your HTML:
<a href="#show" class="show_hide">
<img src="<?php echo WEB_URL; ?>/images/show-more-arrow.jpg" width="61" height="45" id="clicktoggleimage" />
</a>
And use this Javascript:
var img = document.getElementById("clicktoggleimage");
function changeImage() {
if (img.src.indexOf('less') == -1) {
img.src = img.src.replace('more', 'less');
} else {
img.src = img.src.replace('less', 'more');
}
}
function hoverImage() {
if (img.src.indexOf('arrow-over') == -1) {
img.src = img.src.replace('arrow', 'arrow-over');
} else {
img.src = img.src.replace('arrow-over', 'arrow');
}
}
img.onclick = cangeImage;
img.onmouseover = img.onmouseout = hoverImage;
Upvotes: 1