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.
Advertisement
Answer
use same class name
$.each($(".artists-main .artists-name a"), function(index, element) { $(element).mouseover(function() { $('.artists-image .artists-img:eq(' + index + ')').show(); }) $(element).mouseout(function() { $('.artists-image .artists-img:eq(' + index + ')').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-name"><a href="#">Artist 1</a></div> <div class="artists-name"><a href="#">Artist 2</a></div> <div class="artists-name"><a href="#">Artist 3</a></div> </div> <div class="artists-image"> <img class="artists-img" src="https://picsum.photos/200/300?random=1"> <img class="artists-img" src="https://picsum.photos/200/300?random=2"> <img class="artists-img" src="https://picsum.photos/200/300?random=3"> </div>