Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making smarter jQuery code

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>
like image 244
Alex Berg Avatar asked Dec 28 '25 02:12

Alex Berg


2 Answers

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/

like image 60
Richard Dalton Avatar answered Dec 30 '25 17:12

Richard Dalton


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

like image 29
NimChimpsky Avatar answered Dec 30 '25 16:12

NimChimpsky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!