This is a two-part question. I’m using jQuery for a project and wanting to click a link and toggle the class name “highlight” to that link and also to the div with the same id as the rel attribute of the link. I then want to be able to link to the next div without the classname of “highlight”. Here’s the HTML for it:
<ul>
<li><a href="#" rel="panel1">Item 1</a></li>
<li><a href="#" rel="panel2">Item 2</a></li>
<li><a href="#" rel="panel3">Item 3</a></li>
</ul>
<a href="">go to next div without class of highlight</a>
<div id="panel1">some text</div>
<div id="panel2">some text</div>
<div id="panel3">some text</div>
Can anyone help with jQuery side of things?
Many thanks in advance!
Assuming HTML like this:
You can use JS like this:
Note that, if the final panel is already highlighted, then this code does not update the
hrefattribute fora#next-unhighlighted, but removes it. It’s a trivial exercise to add wrap-around behavior, such that highlighting the final panel would link back to the first panel.A note about the odd syntax
if (nextDiv[0]): If the first element in the jQuery collectionnextDivexists, then there is at least one element in the collection. This behaves similarly to (but not exactly the same as)nextDiv.length > 0, but is marginally faster and smaller.As discussed in the comments, to link each panel to the next unhighlighted one, add
<a rel="next-panel">Next panel</a>to each panel’s HTML, then add something like this to the main click handler:Depending on your project requirements, you’ll need to initialize each of these
next-panellinks (or else they’ll only initialize after the first click), and you may want to make the final panel’s ;oml wrap around to the first.