Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I reduce the redundancies in my jQuery code?

The size of my JavaScript file is getting out of hand because I have hundreds of links, and each one has its own jQuery function even though they all peform basically the same task.

Here's a short excerpt:

$("#link1").click(function ()
{
  $(".myDiv").hide();
  $("#myDiv1").toggle();
});

$("#link2").click(function ()
{
  $(".myDiv").hide();
  $("#myDiv2").toggle();
});

$("#link3").click(function ()
{
  $(".myDiv").hide();
  $("#myDiv3").toggle();
});

Would there be a way to abstract some of this logic so that I have only a single function instead of hundreds that do the same thing?

like image 991
ipso facto Avatar asked Jul 08 '09 19:07

ipso facto


2 Answers

You can add a class to all the links that do the same thing and act with jQuery on that class.

<a href='whatever' id='link_1' class='toggler'>text</a>
<a href='whatever' id='link_2' class='toggler'>text</a>

jQuery code will be:

$(".toggler").click( function(){
    // toggle the divs
    var number = $(this).attr("id").split('_')[1];
    $(".myDiv").hide();
    $("#myDiv"+ number).toggle();
});
like image 175
Elzo Valugi Avatar answered Oct 31 '22 14:10

Elzo Valugi


The general approach that I use is to use the traversal methods to find related elements rather than using absolute selectors. This will allow you to apply the same code to elements that are similarly configured without any complicated dependencies on the format of the ids, etc. Done correctly it's also reasonably robust against minor changes to the mark up.

For example, say I have a series of links, each followed by a div that will be toggled by clicking on that link. The links each have a particular class so they can easily be referenced.

<a href="#" class="linkClass">Toggle</a>
<div>
     Some content...
</div>

<a href="#" class="linkClass">Toggle</a>
<div>
     Other content
</div>

I would then find all the links by class, then use the next method to find the associated div and toggle it's visibility. Note that this is a simple example. You may need to use more complicated traversal mechanisms and filter by element type or class, too, depending on your exact mark up.

$('.linkClass').click( function() {
    $(this).next().toggle();
});
like image 3
tvanfosson Avatar answered Oct 31 '22 14:10

tvanfosson