BlueHorse BlueHorse - 7 months ago 29
HTML Question

changing an image when hover with javascript

Title.

I've seen a lot of ways of doing it when the

IMG
element is used :

<img src="blah" id="get" onmouseover="newImage()" onmouseout="oldImage()


Javavscript

function newImage() { document.getElementById(get").src="blah2"}
function oldImage() { document.getElementById("get").src="blah"}


But I keep my images on CSS as
background-image: url()
inside an id:

<div id="image"


How I apply the same principle but when images are on CSS and its on a
div
id


NEW TO JAVASCRIPT PLEASE NO FRAMEWORKS.

Answer

You don't need JavaScript for this (but I give a JavaScript alternative below), just use CSS's :hover pseudo-class.

#get {
    background-image: url(/path/to/image/when/not/hovering.png);
}
#get:hover {
    background-image: url(/path/to/image/when/hovering.png);
}

Example: This div shows your user icon normally, then shows mine if you hover it:

#get {
  width: 50px;
  height: 50px;
  background-image: url(https://graph.facebook.com/950389301719024/picture?type=small);
}
#get:hover {
  background-image: url(https://www.gravatar.com/avatar/ca3e484c121268e4c8302616b2395eb9?s=50&d=identicon&r=PG
);
}
<div id="get"></div>

But if you really want to use JavaScript, it's very similar to the code you've quoted, you just change .style.backgroundImage on your element instead of changing .src:

function startHover(element) {
  element.style.backgroundImage = "url(https://www.gravatar.com/avatar/ca3e484c121268e4c8302616b2395eb9?s=50&d=identicon&r=PG)";
}
function stopHover(element) {
  element.style.backgroundImage = "url(https://graph.facebook.com/950389301719024/picture?type=small)";
}
#get {
  width: 50px;
  height: 50px;
}
<div id="get" style="background-image: url(https://graph.facebook.com/950389301719024/picture?type=small)" onmouseover="startHover(this)" onmouseout="stopHover(this)"></div>

But I discourage use of onxyz attributes; use modern event handling instead:

(function() {
  var div = document.getElementById("get");
  div.addEventListener("mouseover", function() {
    div.style.backgroundImage = "url(https://www.gravatar.com/avatar/ca3e484c121268e4c8302616b2395eb9?s=50&d=identicon&r=PG)";
  }, false);
  div.addEventListener("mouseout", function() {
    div.style.backgroundImage = "url(https://graph.facebook.com/950389301719024/picture?type=small)";
  }, false);
})();
#get {
  width: 50px;
  height: 50px;
}
<div id="get" style="background-image: url(https://graph.facebook.com/950389301719024/picture?type=small)"></div>

That uses addEventListener, which is supported by all modern browsers (not by IE8, or IE9-IE11 in their broken "compatibility" mode). If you need to support those, this answer has a function you can use for cross-browser event handling without a library.

Comments