Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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 class="work-list" data-thumb="http://url.to/test.jpg">
<a class="work-list" data-thumb="http://url.to/test.jpg">
<a class="work-list" data-thumb="http://url.to/test.jpg">
[...]
<img id="work-thumb" src="test.jpg">

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 class="work-list" data-thumb="https://via.placeholder.com/150x100/ff0000">ITEM-1</a>
<a class="work-list" data-thumb="https://via.placeholder.com/150x100/00ff00">ITEM-2</a>
<a class="work-list" data-thumb="https://via.placeholder.com/150x100/0000ff">ITEM-3</a>
 

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading