0

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?

Joshua Dwire
5,4515 gold badges32 silver badges51 bronze badges
asked Oct 4, 2013 at 14:42

2 Answers 2

4

Hmm, how about:

$("[id^=toggleLog]").click(function() {
 var idNum = this.id.split("-")[1];
 $("#toggled-" + idNum).slideToggle("slow");
});
answered Oct 4, 2013 at 14:44
Sign up to request clarification or add additional context in comments.

1 Comment

Beat me to it! Clean solution :) +1
4

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.

answered Oct 4, 2013 at 14:44

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.