I’m trying to change the background image of a div when a user hovers over and clicks it. I’m stuck on limiting the images from changing to ONLY the element on which the user is hovering/clicking. In this example, all of the buttons will change when one div is hovered on/clicked. This is something I’m trying to replicate that’s already working in jQuery. I’m guessing it’s possible to use “this” but all of the ways I’ve tried so far result in errors.
Bonus points for anyone who cal tell me why the alert happens on page load in Firefox but not IE or Chrome
JavaScript
var buttons = document.getElementsByTagName('div');
var i;
function iconDown(e) {
for (i=0; i<buttons.length; i++) {
buttons[i].style.backgroundPosition = '0px -61px';
}
}
function iconUp(e) {
for (i=0; i<buttons.length; i++) {
buttons[i].style.backgroundPosition = '0px -122px';
}
}
function iconOver(e) {
for (i=0; i<buttons.length; i++) {
buttons[i].style.backgroundPosition = '0px -122px';
}
}
function iconOut(e) {
for (i=0; i<buttons.length; i++) {
buttons[i].style.backgroundPosition = '0px 0px';
}
}
function processAction() {
alert("Working!");
}
function Init () {
for (i=0; i<buttons.length; i++) {
if (document.addEventListener) { // all browsers except IE before version 9
buttons[i].addEventListener ("mousedown", iconDown, false);
buttons[i].addEventListener ("mouseup", iconUp, false);
buttons[i].addEventListener ("mouseover", iconOver, false);
buttons[i].addEventListener ("mouseout", iconOut, false);
buttons[i].addEventListener("click", processAction, false);
}
else { // IE before version 9
buttons[i].attachEvent ("onmousedown", iconDown);
buttons[i].attachEvent ("onmouseup", iconUp);
buttons[i].attachEvent ("onmouseover", iconOver);
buttons[i].attachEvent ("onmouseout", iconOut);
buttons[i].attachEvent("onclick", processAction);
}
}
}
Init();
CSS
.btn {width:100px; height:61px; float:left;}
#BackImg {background: url('images/Back.gif') no-repeat 0px 0px;}
#NextImg {background: url('images/Next.gif') no-repeat 0px 0px;}
HTML
<DIV class="btn" ID="BackImg"></DIV>
<DIV class="btn" ID="NextImg"></DIV>
You don’t need any javascript for this. Just use css.
For the clicky stuff: