2

My code for replacing my icon image on mouseover and mouseout isn't working. I'm trying to change each icon every time I mouseover and change it back to original on mouseout. I can't seem to find the problem and I would also like to know if there is any way to simplify my code. Thank you!

Assuming that all the id and image sources are correct! Image

window.addEventListener('load', function(){

var oImg1 = document.getElementById("image1").src = "images/fleche1.gif";
var oImg2 = document.getElementById("image2").src = "images/fleche1.gif";
var oImg3 = document.getElementById("image3").src = "images/fleche1.gif";
var oImg4 = document.getElementById("image4").src = "images/fleche1.gif";
var oImg5 = document.getElementById("image5").src = "images/fleche1.gif";
var oImg6 = document.getElementById("image6").src = "images/fleche1.gif";
var oImg7 = document.getElementById("image7").src = "images/fleche1.gif";
var oImg8 = document.getElementById("image8").src = "images/fleche1.gif";
var oImg9 = document.getElementById("image9").src = "images/fleche1.gif";

// Fonction Fleche2
oImg1.addEventListener("mouseover", function(){
    this.src="images/fleche2.gif";
});
// Fonction Fleche1
oImg1.addEventListener("mouseout", function() {
    this.src = "images/fleche1.gif";
// Fonction Fleche2
oImg2.addEventListener("mouseover", function(){
    this.src="images/fleche2.gif";
});
// Fonction Fleche1
oImg2.addEventListener("mouseout", function() {
    this.src = "images/fleche1.gif";
// Fonction Fleche2
oImg3.addEventListener("mouseover", function(){
    this.src="images/fleche2.gif";
});
// Fonction Fleche1
oImg3.addEventListener("mouseout", function() {
    this.src = "images/fleche1.gif";
// Fonction Fleche2
oImg4.addEventListener("mouseover", function(){
    this.src="images/fleche2.gif";
});
// Fonction Fleche1
oImg4.addEventListener("mouseout", function() {
    this.src = "images/fleche1.gif";
// Fonction Fleche2
oImg5.addEventListener("mouseover", function(){
    this.src="images/fleche2.gif";
});
// Fonction Fleche1
oImg5.addEventListener("mouseout", function() {
    this.src = "images/fleche1.gif";
// Fonction Fleche2
oImg6.addEventListener("mouseover", function(){
    this.src="images/fleche2.gif";
});
// Fonction Fleche1
oImg6.addEventListener("mouseout", function() {
    this.src = "images/fleche1.gif";
// Fonction Fleche2
oImg7.addEventListener("mouseover", function(){
    this.src="images/fleche2.gif";
});
// Fonction Fleche1
oImg7.addEventListener("mouseout", function() {
    this.src = "images/fleche1.gif";
// Fonction Fleche2
oImg8.addEventListener("mouseover", function(){
    this.src="images/fleche2.gif";
});
// Fonction Fleche1
oImg8.addEventListener("mouseout", function() {
    this.src = "images/fleche1.gif";
// Fonction Fleche2
oImg9.addEventListener("mouseover", function(){
    this.src="images/fleche2.gif";
});
// Fonction Fleche1
oImg9.addEventListener("mouseout", function() {
    this.src = "images/fleche1.gif";

});
1
  • 1
    You can simplify this code by adding the same class for each image element. That way you can select them all and add listeners with one line as well. Commented May 7, 2019 at 4:44

4 Answers 4

3

The code is not working because oImg1,.... are not HTML elements they are strings. var oImg1 = document.getElementById("image1").src = "images/fleche1.gif"; evaluates like.

var oImg1 = document.getElementById("image1").src = "images/fleche1.gif";
var oImg1 = "images/fleche1.gif";

There is too much code so there are many chances the code is not working due to any type error.You should use below approach.

  • Assign a same class to all the images which you want to select.
  • Then select them using querySelectorAll() and use forEach() loop.
  • And change innerHTML while iterating and also add listeners.

Here is an example using simple divs

document.querySelectorAll('.test').forEach(x => {
  x.innerHTML = 'default';
  x.addEventListener('mouseover',function(){
    this.innerHTML = 'changed'
  })
  x.addEventListener('mouseout',function(){
    this.innerHTML = 'default';
  })
})
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>

As suggested by @Kaiido in the comments "for the browser, it is always simpler to deal with delegated events than with a bunch of same events on multiple targets."

So based on that you can attach both the events to document and use matches() on event.target to check if its right element clicked. A demo is:

document.querySelectorAll('.test').forEach(x => {
  x.innerHTML = 'default';
});
document.addEventListener('mouseover',function(e){
  if(e.target.matches && e.target.matches('.test'))
    e.target.innerHTML = 'changed';
});
document.addEventListener('mouseout',function(e){
  if(e.target.matches && e.target.matches('.test'))
    e.target.innerHTML = 'default';
})
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>

Sign up to request clarification or add additional context in comments.

5 Comments

or even better, delegate to a single event listener on the common parent: jsfiddle.net/k9zwvc8s
@Kaiido Thanks for suggestion but I think it will make the code a little more complex.
That depends for whom you are talking about. For the reader? Might be, but if you use helper functions like delegateEvent(evt, commonParent, selector, callback) then it's clearer what is hapening (like jQuery .on(evt, selector, cb)), but for the browser, it is always simpler to deal with delegated events than with a bunch of same events on multiple targets.
@Kaiido I will add that to my answer. If you want to edit you are welcome to do that.
Oh no, do as you wish, it's your answer. If you think it's not worth adding it, I won't take offense and my comment might indeed be enough. If you do decide to include it, then you may flag my comments as "no longer needed".
1

Simplified working example below, replace id with class (or use both if needed for other operations) to select all elements easily and have a cleaner code.

let elementsArray = document.getElementsByClassName("image");
let src1 = "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d9/Icon-round-Question_mark.svg/1024px-Icon-round-Question_mark.svg.png";
let src2 = "https://cdn.thinglink.me/api/image/vM1pGDEAMLAe5KvPyP8NeLKMJRcozpVuXYtUU2QvKVcueJ8GeTpVuQmDLHs4LRMBHvMecZqTwpNzNXp34n4i6nZ7geXKM1TtrzdFXFjtnPrCroeWd6LvBv3qDoowckCkT3gGC94/320/320/scaledown";

for (let elem of elementsArray) {
    elem.addEventListener("mouseover", function(){
   	this.src=src2;
    });
    elem.addEventListener("mouseout", function(){
   	this.src=src1;
    });
};
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/d/d9/Icon-round-Question_mark.svg/1024px-Icon-round-Question_mark.svg.png" style="width:20px;" class="image"></img>
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/d/d9/Icon-round-Question_mark.svg/1024px-Icon-round-Question_mark.svg.png" style="width:20px;" class="image"></img>
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/d/d9/Icon-round-Question_mark.svg/1024px-Icon-round-Question_mark.svg.png" style="width:20px;" class="image"></img>
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/d/d9/Icon-round-Question_mark.svg/1024px-Icon-round-Question_mark.svg.png" style="width:20px;" class="image"></img>
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/d/d9/Icon-round-Question_mark.svg/1024px-Icon-round-Question_mark.svg.png" style="width:20px;" class="image"></img>
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/d/d9/Icon-round-Question_mark.svg/1024px-Icon-round-Question_mark.svg.png" style="width:20px;" class="image"></img>
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/d/d9/Icon-round-Question_mark.svg/1024px-Icon-round-Question_mark.svg.png" style="width:20px;" class="image"></img>

Comments

0

Try this one...

<img src='http://icons.iconarchive.com/icons/fasticon/web-2/256/Google-icon.png' class='img-hover' image="https://cdn.pixabay.com/photo/2018/02/09/21/46/rose-3142529__340.jpg" />
<img src='http://icons.iconarchive.com/icons/fasticon/web-2/256/Google-icon.png' class='img-hover' image="https://cdn.pixabay.com/photo/2018/02/09/21/46/rose-3142529__340.jpg" />


let altImage = '';
let originalImage = '';
$('.img-hover').mouseenter(function() {
  altImage = $(this).attr('image');
  originalImage = $(this).attr('src');
  $(this).attr('src', altImage).attr('image', originalImage);
}).mouseleave(function() {
  $(this).attr('src', originalImage).attr('image', altImage);   
});

Here us jsfiddle link: https://jsfiddle.net/erpkumar/5s1nbje4/4/

1 Comment

Im trying to use simple Javascript
0

you can do it using CSS only

body { display: flex }

li { list-style-type: none; cursor:pointer}

.image {
  width:        15px;
  height:       15px;
  margin-right: 10px;
  transition:   0.5s;
  display:      inline-block;
}

.image1 {          background: url(https://picsum.photos/id/237/15/15); }
li:hover .image1 { background: url(https://picsum.photos/id/239/15/15); }

.image2 {          background: url(https://picsum.photos/id/238/15/15); }
li:hover .image2 { background: url(https://picsum.photos/id/236/15/15); }
<ul>
  <li><div class="image image1"></div>Item A</li>
  <li><div class="image image2"></div>Item B</li>
<ul>

1 Comment

Everything is working perfect the only problem is I need to change the image when hover on the LI element if you can check the image I posted thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.