I need to change color title with equal data-id on hover img
<div class="left_box">
<div data-id="1">
title 1
</div>
<div data-id="2">
title 2
</div>
<div data-id="3">
title 3
</div>
</div>
<div class="right_box">
<a href="#" data-id="1">
<img src="url_image">
</a>
<a href="#" data-id="3">
<img src="url_image">
</a>
<a href="#" data-id="2">
<img src="url_image">
</a>
</div>
On hover of a[data-id="2"]
I need to change color of .left_box div[data-id="2"]
in js or jquery. Can you help me?
3
Answers
Find the right selector for you
a
–>a[data-id="2"]
Use the jquery hover to act on it when hovered
Find the selector for your
div
–>.left_box div[data-id="2"]
Get its color by using jquery CSS
Change the color of your link using the same method.
$(‘a[data-id="2"]’).hover(function(event) {
$(event.target).css("color", $(‘.left_box div[data-id="2"]’).css("color"));
})
Pure Javascript solution:
Uses
querySelectorAll
to get all the.right_box > a[data-id]
Then get the id from
e.dataset.id
and use that to find it’s friendThen apply
onmouseover
andonmouseleave
to change any styling you’d likeBased on OP’s comment; same idea using
onmousedown
andonmouseup
jquery solution. Within the hover callback, get the id of the element being hovered with
then your "title" selector becomes:
without the variable, this would generate the selector:
.left_box > div[data-id='2']
Updated snippet: