I have a pretty specific need in JavaScript/jQuery and I can’t find the perfect solution, there is always a criterion that I can’t fulfill.
Here is a summary of the situation:
I have 3 titles each with their own id and a common class.
I also have 3 contents each with their own id and a common class.
At the code level, it looks like this:
<h3 id="title1" class"triggers">Title 1</h3>
<h3 id="title2" class"triggers">Title 2</h3>
<h3 id="title3" class"triggers">Title 3</h3>
<p id="content1" class="myContents">Content 1</p>
<p id="content2" class="myContents">Content 2</p>
<p id="content3" class="myContents">Content 3</p>
My constraints are as follows:
- all content is hidden by default
- when I click on a title, the related content is displayed (Ex: I click on the title1 the content1 is displayed) and the selected title changes color
- When I click on another title, the one that was previously selected returns to its original color and its content disappears. On the other hand, the title I just clicked on changes its color and its specific content appears (Ex: I click on the title2, the title1 returns to its original color and the content1 disappears while the title2 changes color and the content2 appears). Only one content can appear at a time.
- When I click a second time on the currently selected title, it returns to its original color and its content disappears (but if I click a third time, it reappears again, basically one shot it appears and one shot it disappears, so a click on two).
- That the title id is automatically attached to the content id (since in my example, there are only 3 titles and 3 contents but there could very well be 20, 30, etc.).
A situation in appearance "basic" for the common developers, except that I can not meet all these conditions at the same time, there is always a time when it sticks… Be lenient, I’m still a beginner in the trade
So if you are able to help me solve this block, I would be enormously grateful! Thanking you already for the time you will take to read me 🙂
So far, I have managed to meet some of my requirements on the display of content, but I have not managed to fulfill all these requirements at the same time.
2
Answers
Since you have multiple requirements I would just toggle some data attribute values and match up the CSS; you can put any selector in that matches the target, then toggle that. You can even have "special" css as I show for the Five element – or even have a stoplight effect with Green/Yellow/Red etc. this way.
I added a couple more targets with differing selectors just so you could see it is flexible.
Note that you could even have TWO and wrap them in a div so the siblings matches. Triggers and Content can be in any order as long as the selectors match.