1

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?

3
  • sorry, what is your question? Commented Feb 27, 2013 at 8:36
  • 3
    I think he want to convert this to basic javascript without jQuery Commented Feb 27, 2013 at 8:36
  • Yes Arun. I want to convert this code in basic javascript without jQuery. Commented Feb 27, 2013 at 8:40

1 Answer 1

5

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
}
...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.