How can you pass the ID of an element that is clicked on to manipulate another corresponding element, without having to write a jQuery function for every single one?
So…. Let’s say that I have a list of some stuff (headlines, events, etc.) on a page. I show a headline then have a link that says "more" after each headline to hide/show the details of the headline or event or whatever. So it looks something like this…
<div id="SomeBlock"> Some text and stuff goes here
<a id="MoreDetailsLink1">More...</a>
<div id="MoreDetailsDiv1" style="display:none;">The rest of story goes here</div>
</div>
I know I should be able write:
$(document).ready(function(){
$("#MoreDetailsLink1").click(function(){
$("#MoreDetailsDiv1").toggle();
});
});
But, let’s say that I have 25 or 100 of those headline/details elements. I really do not want to rewrite a jQuery function for every single one. I should be able to do something to pass or grab the "More…" link id to toggle the correct more details div.
How do I do that? If I click on the "MoreDetailsLink47", I need the "MoreDetailsDiv47" div to toggle. I am just not sure at all, how to write it so that when the "more" is clicked on the appropriate more details div will be manipulated.
One more quick note, yes (especially if it makes it simpler), in this example all the elements will have the same prefix name, just the numbers will change.
2
Answers
HTML:
JavaScript:
While it would be possible to achieve what you require in the manner you suggest, ie. passing
id
attributes around to various method calls, the far better approach would be to follow DRY principles.To do this, use the same
class
attributes on your repeated HTML structure, where just the content changes. From there you can attach the same event handler to all those elements. Within that event handler you can traverse the DOM to find content based on the pre-determined structure, instead of targeting elements with incrementalid
attributes.Below is a working example of how to do this – note that the single jQuery event handler will work for an infinite number of the
.some-block
structures.