How could i show/hide elements on click when it can has various styles starting from one. I need the first sub-item to be clicked – to show 1st item and etc.
Code goes something like this:
$('sub-item-' + (i + 1)).click ->
$('item-' + (i + 1)).show()
#coffeescript
<div class="item-1">1</div>
<div class="item-2">2</div>
<div class="item-3">3</div>
<div class="item-4">4</div>
etc..
<a href="#" class="sub-item-1">Click 1</a>
<a href="#" class="sub-item-2">Click 2</a>
<a href="#" class="sub-item-3">Click 3</a>
<a href="#" class="sub-item-4">Click 4</a>
etc..
Thanks in advance!
With your specific example, you can use an attribute starts with selector, then parse the class name on the actual element that was clicked. But I wouldn’t do that, it’s fragile. (For instance, suppose you added a second class to your
classattribute? That would complicate the parsing, and if you put it before thesub-item-*class, would mess up the selector.) Instead I’d probably either use the position of the item in its container (if you can), or change the markup to use adata-*attribute instead.Here’s an example that assumes your items are the only thing in their container:
Live example | source
You can then use
indexto find out which div was clicked:(You need the
+ 1becauseindexis zero-based.)But if they’re not the only thing in the container, you can use a
data-*attribute:Live example | source
…which makes it really easy: