I’m trying to code a page which has many “articles”.
Each article’s title is listed. If the viewer wants to read the article, they click the title.
This causes the div containing the article’s text to be displayed.
By default, no article’s text should be visible.
I’m having a lot of trouble dealing with the fact that every article title must only toggle it’s own text, and not all of the texts, even though they share the same class.
Is it possible to code something like this without manually giving every article text it’s own unique ID?
I was thinking I could wrap each article title + text in it’s own div. Then have some sort of check that tells it only to show visibility if the div is at the same level (i.e. is in the same div the title is in).
Could someone offer some guidance?
Thanks!
PS: I’d like to stick to a pure html/javascript solution, but I’ve tagged jquery in case there is an easy way to do it with that solution. I need to avoid PHP because this is not on a server.
jQuery does indeed make it easy. If your HTML looks like this:
Then this is all the JavaScript (w/ jQuery) you need:
Try it on JSFiddle.
If you for some reason do not want to use jQuery (because you’re not using it for anything else and it’s too big to justify for just this, say), you could use plain JavaScript: (note: probably only works in newer browsers)
Try it on JSFiddle.