1

I have three images which need the transform style. The value for this style is generated and saved in array.

var img = [1.jpg, 2.jpg, 3.jpg]
var translateHoverValues = [60,120,180]

I get the the id of the image on hover, I have no idea how to pick the needed value from array based on id. Maybe there is some kind of index/position number of the img in the div, so I can pick the right value form array.

On hover I get the id of a image, like this:

onmouseover="imgHover(this)" //html
function imgHover(obj){      //JS
  var idImg = obj.id       //if logged gives back: img1, img2 or img3
  var z = document.getElementById(idImg) //hovered image
  z.style.transform = 'translateX(-'+translateHoverValues[n]+'px)'
  ......
}

My research: https://www.w3schools.com/jsref/prop_element_children.asp With children.length I can tell that my div has length of 3, because 3 images. With children[2] we can select specific child, but how can we find out the index of hovered image?

Thank you.

Mamun
  • 66,969
  • 9
  • 47
  • 59
miomate
  • 45
  • 1
  • 7
  • 1
    Have you changed the integer prototype? Otherwise `1.jpg` is certainly gonna throw an exception... – idmean May 15 '19 at 06:39

1 Answers1

1

You can use indexOf() like the following way:

var images = Array.prototype.slice.call(document.getElementById('container').children);
images.forEach(function(el){
  el.addEventListener('mouseover', getIndex);
});
function getIndex(){
  //console.clear(); // clear the console
  var index = images.indexOf(this);
  document.getElementById('index').textContent = 'The index of the image is: ' + index;
}
<div id="container">
  <img src="img_1.jpg" alt="Image 1">
  <img src="img_2.jpg" alt="Image 2">
  <img src="img_3.jpg" alt="Image 3">
</div>
<div id="index"></div>
Mamun
  • 66,969
  • 9
  • 47
  • 59
  • Thank you! Loved your comment: clear the console :^) I have a question: How could I make out of this images.forEach(function(el){ a seperate function? Because I need to return the index in this function. – miomate May 15 '19 at 07:30
  • 1
    @miomate, `forEach()` does not `return`. You can maintain a variable instead of `return`:) – Mamun May 15 '19 at 07:42
  • Yes true, I managed to do so but the solution hurt my eyes https://codepen.io/miomate/pen/arpVPQ – miomate May 15 '19 at 07:52
  • @miomate, you probably would like to show them in an element like I did in the updated answer:) – Mamun May 15 '19 at 11:33