jQuery(document).ready(function(){
jQuery(".artists-main .artists-name1 a ").mouseover(function(){
jQuery(".artists-image .artists-img1").show();
});
jQuery(".artists-main .artists-name1 a ").mouseout(function(){
jQuery(".artists-image .artists-img1").hide();
});
jQuery(".artists-main .artists-name2 a ").mouseover(function(){
jQuery(".artists-image .artists-img2").show();
});
jQuery(".artists-main .artists-name2 a ").mouseout(function(){
jQuery(".artists-image .artists-img2").hide();
});
jQuery(".artists-main .artists-name3 a ").mouseover(function(){
jQuery(".artists-image .artists-img3").show();
});
jQuery(".artists-main .artists-name3 a ").mouseout(function(){
jQuery(".artists-image .artists-img3").hide();
});
jQuery(".artists-main .artists-name4 a ").mouseover(function(){
jQuery(".artists-image .artists-img4").show();
});
jQuery(".artists-main .artists-name4 a ").mouseout(function(){
jQuery(".artists-image .artists-img4").hide();
});
});
.artists-image img{display: none;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="artists-main">
<div class="artists-name1"><a href="#">Artist 1</a></div>
<div class="artists-name2"><a href="#">Artist 2</a></div>
<div class="artists-name3"><a href="#">Artist 3</a></div>
</div>
<div class="artists-image">
<img class="artists-img1" src="https://picsum.photos/200/300?random=1">
<img class="artists-img2" src="https://picsum.photos/200/300?random=2">
<img class="artists-img3" src="https://picsum.photos/200/300?random=3">
</div>
Hide and show images on hover. Class artists-main has artists names and class artists-image has images of the artists. It’s working fine but my code is lengthy. I have round about 50+ artists and page will be filled by jQuery code. I want to shorten it.
7
Answers
You can also use native javascript code:
Fiddle snippet
use same class name
The SIMPLEST way to do this would be using purely CSS, you may follow the example given here :
Solution reference :
https://www.w3schools.com/howto/howto_css_display_element_hover.asp
You can use the index of the element, and control visibility by adding CSS class:
using index() and avoiding to number your class:
This is a no effort solution. But I really recommand that you settle this up with pure CSS (pseudo-elements).
CSS = Presentation
JS = Behaviour