I was wondering if anyone has any idea on how I could rewrite this simple jquery code to be more efficient. It's of course working fine now but I imagine adding say 10 more items would make the code really big. I thought maybe I could add the classes to arrays and use some kind of loop? Not sure if that's the right approach though.
Here it is on jsfiddle: http://jsfiddle.net/QVS9X/42/
and here's a sample of it: JS:
$(".image1").mouseout(function() {
$(".default").show();
$(".cat1").hide();
}).mouseover(function() {
$(".default").hide();
$(".cat1").show();
});
$(".image2").mouseout(function() {
$(".default").show();
$(".cat2").hide();
}).mouseover(function() {
$(".default").hide();
$(".cat2").show();
});
HTML:
<div class="image1 image">
<p>Hover for cat 1</p>
</div>
<div class="image2 image">
<p>Hover for cat 2</p>
</div>
<div class="image3 image">
<p>Hover for cat 3</p>
</div>
<div class="default">
<p>Default Text</p>
</div>
<div id="cats">
<p class="cat1">Category 1 text</p>
<p class="cat2">Category 2 text</p>
<p class="cat3">Category 3 text</p>
</div>
If you can put a class of image on the divs that current have image1, image2 etc, then you can do this:
$(".image").hover(function() {
$(".default").toggle();
$("#cats p").eq($(this).index()).toggle();
});
This assumes that the image divs will be in the same order as the p tags inside #cats.
http://jsfiddle.net/QVS9X/44/
Example using data attributes:
JS:
$(".image").hover(function() {
$(".default").toggle();
$($(this).data('id')).toggle()
});
HTML:
<div class="image" data-id="#cat1">
<p>Hover for cat 1</p>
</div>
<div id="cats">
<p id="cat1">Category 1 text</p>
</div>
http://jsfiddle.net/QVS9X/55/
var myDefault = $(".default");
var myCat1 = $(".cat1");
var myCat2 = $(".cat2");
and then
$(".image1").mouseout(function() {
myDefault.show();
myCat1.hide();
}).mouseover(function() {
myDefault .hide();
myCat1 .show();
});
$(".image2").mouseout(function() {
myDefault.show();
myCat2.hide();
}).mouseover(function() {
myDefault.hide();
myCat2.show();
});
will reduce dom traversal, and improve performance
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With