I have a simple hide/show which shows the hidden message and changes the links text when the link is clicked, everything works but, my problem is when I click one link, all the hidden messages gets shown instead of just the one that I’ve clicked.
I need to add something like $(this).parent().show(); but I’m not sure where to put this or is there an easier way?
<p><a href="#" class="hideshow">Show</a></p>
<div class="message">
some text here
</div>
<p><a href="#" class="hideshow">Show</a></p>
<div class="message">
some text here
</div>
The problem is occurring because you are telling the script to affect everything on the page that matches the class name.
In the toggle function, the this keyword will refer to the link that was clicked, so you can work with only that one particular link with:
$(this).text('Hide');
With the message, you want to restrict the selection to just the one that is next after the para that the link is in, so something like this would work:
Now the message is not showing, please see my updated code.
I also need the .hideshow text to work in the same way… what do you suggest? Much appreciated
I think that jQuery selectors are selected from inside of the chosen context, so if we’re starting from the div it won’t select the .message class on that same div, only on what’s inside of the div.
So, either the HTML code needs to be restructured so that the show/hide is contained within the same block as the div, or the code needs to change.
If the code is to change it could be something like:
$(this).parent() takes it up to the paragraph element, and the next(‘div’) part then moves on down to the message that immediately comes after the paragraph.
Having .message is useful if there’s an outer context from which you can then select the message, but in this case with the way you have structured your HTML that’s not possible.
If the HTML were instead something that keeps the link and message in a separate area from the other ones, then using .message would be useful.
For example:
<div>
<p><a href="#" class="hideshow">Show</a></p>
<div class="message">some text here</div>
</div>
<div>
<p><a href="#" class="hideshow">Show</a></p>
<div class="message">some text here</div>
</div>
With that type of HTML code you can go up to the parent of the paragraph, then select the message from there.