Change image with mouseover [duplicated]

3

Having an event mouseover , I would like that when you move the mouse over the image, the image changes depending on what the current image is, if not, it is not changed.

HTML

<body>
 <img src="ikefeliz_2.png" id="imagen">
</body>

JS

var ikefeliz="ikefeliz_2.png";
var marthfeliz="marthfeliz_2.png";
var ikepeligro="ikepeligro_2.png";
var marthpeligro="marthpeligro_2.png";

window.addEventListener('load', iniciar, false);

function iniciar(){
  var imagen=document.getElementById('imagen');
  imagen.addEventListener('mouseover', peligro, false);
 }

function peligro(){
  var imagen=document.getElementById('imagen');
  switch (imagen.src) {
    case ikefeliz:
     document.getElementById('imagen').src=ikepeligro;
     break;

    case marthfeliz:
     document.getElementById('imagen').src=marthpeligro;
     break;
   }
 }
    
asked by Vendetta 13.08.2017 в 17:40
source

1 answer

4

Code

var imagenNormal = "http://requirementsinc.com/img/icon/PNG/danger.png";

var imagenPeligro = "https://img.utdstc.com/icons/256/app-danger-check-android.png";

var imagenExtra = "https://www.technodyan.com/wp-content/uploads/2016/06/LinuxAndroid.png";

window.addEventListener('load', iniciar, false);

function iniciar() {

  var imagen = document.getElementById('imagen');
  
  imagen.addEventListener('mouseover', peligro, false);
}

function peligro() {

  var imagen = document.getElementById('imagen');

  switch(imagen.src){
  
    case imagenNormal:
      document.getElementById('imagen').src = imagenPeligro;
      break;
      
    case imagenPeligro:
      document.getElementById('imagen').src = imagenExtra;
      break;
  
    case imagenExtra:
      alert("No debo cambiar la imagen");
      break;
  
  }

}
<body>
  <img src="http://requirementsinc.com/img/icon/PNG/danger.png" id="imagen">
</body>

Explanation

You do not need to do this:

var imagen=document.getElementById('imagen').src="ikepeligro_2.png";

Since imagen was previously declared and any change you make to the object, it will always keep it updated .

What I have done is to simplify the code a bit, using the statement switch and leaving the names of the images in variables, so you can make use of a comparison and in case it is a or another image you can make the change.

    
answered by 13.08.2017 / 18:18
source