Reputation: 11
I have the following JavaScript code for a simple hover which uses JQuery:
$('.product_img_link').hover(function(){
$(this).prev('.hoverProduct').show();
},function(){
$(this).prev('.hoverProduct').hide();
});
(finds the previous div
with class hoverProduct
, and displays it on hover and hides it on mouse out).
How can I write this snippet without JQuery, using only plain JavaScript?
Upvotes: 1
Views: 1538
Reputation: 94101
Something like this:
var links = document.querySelectorAll('.product_img_link');
[].forEach.call(links, function(link) {
var prev = link.previousSibling;
link.addEventListener('mouseover', function() {
prev.style.display == 'block';
});
link.addEventListener('mouseout', function() {
prev.style.display == 'none';
});
});
In jQuery prev
with a selector gets the previous element only if it matches the selector. If you want the same behavior in plain JS you can test like this:
...
var prev = link.previousSibling;
var hasClass = /\bhoverProduct\b/.test(prev.className);
if (hasClass) {
// events
}
...
Upvotes: 5