I would like top know if there is a way to create several slides and panels using minimal code and avoid this:
$(document).ready(function(){
$("#slide1").click(function(){
$("#panel1").slideToggle("slow");
});
$("#slide2").click(function(){
$("#panel2").slideToggle("slow");
});
});
As you can see, for every pair of panel and slide I have to create 3 new lines of jQuery. Is there a way to avoid this? I'm open to solutions that use Javascript as well. The goal of this is to simply have a few lines of code, and for every panel and slide involved, I don't have to add any code whatsoever. I simply have to add a slide and panel, and it will function.
Including your HTML would be very important in this case. Depending on the relationship between your panels and slides, you may be able to make use of .siblings()
, .parent()
, children()
, etc.
However, assuming they're not related at all and need to be selected by unique ID...
Give all your slides a common class:
<div id="slide1" class="slide"></div>
<div id="slide2" class="slide"></div>
<div id="slide3" class="slide"></div>
Put the handler on the common class instead of separate ID's, and get the "slide number", using $(this)
to refer to the clicked slide. You can get the ID and remove the word "slide" from it, so all you're left with is the "slide number". Then, "#panel" + slideNumber
should give you the associated panel.
$(".slide").click(function(){
var slideNumber = $(this).attr("id").replace("slide","");
$("#panel" + slideNumber).slideToggle("slow");
});
As DaniP suggests in the comments below, if your slides are the only elements that begin with the word "slide", you could use a wildcard selector to match them by "ID starting with 'slide'", like so:
$([id=^"slide"]).click(function() { ... });
You wouldn't need to implement the common class as I suggested earlier in this case.