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?
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();
});
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();
});
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