0

I know the title isn't the best, I didn't know how to put this in one sentence. Anyway, I've got some php code creating pairs of links and corresponding boxes which should toggle, when I hit the link. Now I was wondering how you do this in jQuery "the right way".

Until now I gave every link the class togglelink and an ID togglelink1, togglelink2 etc. The boxes then have the ID togglebox1... So I respond to $(".togglelink").click(), get the current ID, parse the number, add it to the box-ID and toggle the object.

This doensn't seem very straight foward as it's a task I'm sure is pretty common. Any suggestions on how I could improve this?

3 Answers 3

1

Depending on how your page is layed out you could use next to find the div to toggle. This way there would be no need for IDs.

$('.togglelink').click(function() {
    $(this).next('.togglebox').toggle();
});

<a href="#" class="togglelink">Link 1</a>
<div class="togglebox">Box 1</div>

<a href="#" class="togglelink">Link 2</a>
<div class="togglebox">Box 2</div>
Sign up to request clarification or add additional context in comments.

2 Comments

In this case this really seems to be the best way. Thanks.
Imho this is generally not a really good solution for a toggler because it depends on your HTML structure, but since you generate the list with php it will do the job.
1

This actually is quite straight forward. One thing you may want to change is setting the IDs like this "togglelink-num" and "togglebox-num", you can then easily get the number with elem.id.split('-')[1]; instead of a pretty inconsistent parseInt(elem.id).

Comments

0

Not sure what you want to do but it sound like you should check out jquery .toggle() here.

Comments

Your Answer

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.