Home > Software engineering >  Hover over div, use its data-attribute to change the src of an img
Hover over div, use its data-attribute to change the src of an img

Time:04-26

I want to hover over a div and use its unique data-attribute to change the src of an img somewhere else on the page. So you go through the list and the url is changing depending on which div it hovers over. My approach so far was to append a mouseover event to all my list elements and triggering a function each time which will get the data-attribute of the current hovered over element. But it doesn't work and i have the feeling i am approaching this from the wrong angle. I am aware that this is easily solved by using a few lines of jquery, but i would like to not use it, as i would need it solely for this. There is a way to do this in plain old javascript, right?

const workThumb = document.querySelectorAll('#work-thumb');
const works = document.querySelectorAll('.work-list').forEach(item => {
  item.addEventListener('mouseover', event => {
    var src = this.getAttribute('data-thumb');
    workThumb.setAttribute("src", url);
  })
})
<a  data-thumb="http://url.to/test.jpg">
<a  data-thumb="http://url.to/test.jpg">
<a  data-thumb="http://url.to/test.jpg">
[...]
<img id="work-thumb" src="test.jpg">

CodePudding user response:

use querySelector (not querySelectorAll) :

working example...

const workThumb = document.querySelector('#work-thumb')

document.querySelectorAll('.work-list').forEach( item => 
  {
  item.onmouseover = () => workThumb.src = item.dataset.thumb
  })
 a {
  display : block;
  margin  : .3em;
  cursor  : pointer;
  }
<a  data-thumb="https://via.placeholder.com/150x100/ff0000">ITEM-1</a>
<a  data-thumb="https://via.placeholder.com/150x100/00ff00">ITEM-2</a>
<a  data-thumb="https://via.placeholder.com/150x100/0000ff">ITEM-3</a>
 

<img id="work-thumb" src="https://via.placeholder.com/150/" alt="">

CodePudding user response:

I cleaned up your code and here you have working example. <a> tags are used for links, not for list elements, use <ul> <li></li> </ul> instead.

Check out my demo. Hover over each item and the image source will change.

const workThumb = document.getElementById('work-thumb');
const works = document.querySelectorAll('.work-list');

works.forEach(item => {
  item.addEventListener('mouseover', event => {
    workThumb.src = event.target.dataset.thumb;
  });
});
<ul>
    <li  data-thumb="https://via.placeholder.com/150x100/ff0000">ITEM-1</li>
    <li  data-thumb="https://via.placeholder.com/150x100/00ff00">ITEM-2</li>
    <li  data-thumb="https://via.placeholder.com/150x100/0000ff">ITEM-3</li>
</ul>

<img id="work-thumb" src="https://via.placeholder.com/150x100/" alt="">

  • Related