I have the following code:
<script type="text/javascript">
$(function() {
//div1 toggle
function runEffect(){
var options = {};
//run the effect
$("#div1_toggle").toggle("blind",options,350);
};
$("#div1").click(function() {
runEffect();
return false;
});
});
</script>
Imagine the above code literally duplicated for a number of divs named div1, div2, div3, etc.
This is horrendously bad, and I would like to rewrite the code such that it applies to a div of any name to toggle a div of (equal name + _toggle).
Bonus: how could I still allow some of these divs to incorporate a different toggle speed (i.e. the 350ms specified above) while reducing redundancy?
A lot of the time, simplifying your javascript is best done by simplifying your HTML first.
It would be best if you don’t use IDs for the Divs (you don’t want to have to keep increasing the ID number yourself do you?) but instead used classes (classes are generic and repeatable). This would work best if the “toggle div” is related to the “clicked div” somehow, for example, one is after the other. I would do it like this:
Then your script is simple:
As for some divs toggling at a different speed? Sure, just add another class:
Now change the script to:
There are other ways to do this. You can stick the “fast” class on the “clickable” div instead, then you’d have two different click handlers. You could have a “normal” and a “fast” class, so you don’t have to do
:not(.fast)and can just do.normalinstead. Hope this gives you some ideas…