'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 1:[1]
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="">
Solution 2:[2]
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 class="work-list" data-thumb="https://via.placeholder.com/150x100/ff0000">ITEM-1</li>
<li class="work-list" data-thumb="https://via.placeholder.com/150x100/00ff00">ITEM-2</li>
<li class="work-list" data-thumb="https://via.placeholder.com/150x100/0000ff">ITEM-3</li>
</ul>
<img id="work-thumb" src="https://via.placeholder.com/150x100/" alt="">
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 |