I have a problem with the following JavaScript code:
$( "#toggleLog-1" ).click(function() {
$( "#toggled-1" ).slideToggle( "slow" );
});
$( "#toggleLog-2" ).click(function() {
$( "#toggled-2" ).slideToggle( "slow" );
});
$( "#toggleLog-3" ).click(function() {
$( "#toggled-3" ).slideToggle( "slow" );
});
/// ... and many other IDs
As you can see, I want to know how to increment the id and compact my code, because I have many IDs in my css file. In php I know how I would do this (with a foreach and increment function), but how can I do it in JavaScript?
2 Answers 2
Hmm, how about:
$("[id^=toggleLog]").click(function() {
var idNum = this.id.split("-")[1];
$("#toggled-" + idNum).slideToggle("slow");
});
1 Comment
Although all your clickable elements seem to conform to a specific convention with their id attributes, it would be easier and cleaner to give all the clickable elements a specific class, and a data-* attribute specifying a selector for what element to toggle. For example, have this structure:
<div class="toggler" data-toggler="#toggled-2"></div>
<div id="toggled-2"></div>
And use this:
$(".toggler").on("click", function () {
var $this = $(this),
toggler = $this.attr("data-toggler");
$(toggler).slideToggle("slow");
});
It targets all the clickable elements by the toggler class. In the click handler, it looks at its specific data-toggler attribute, and selects elements by that, calling .slideToggle() on any found.