Numbering links within a section using .data()

Hi there,

I’ve got a page which is split into separate sections. Within each section I need to number a link relevant to that section.

For example:

  • Section 1 (with 1 link) has its link numbered as 1
  • Section 2 (with 3 links) has it’s links numbered 1, 2 & 3 according to the order they are in

My approach is I’m using .data() to assign information to each section and also to each link within those sections so I can then extract this later on. At the moment though, rather than numbering each link in relation to the link’s parent section, the JS is numbering according to all of the links within the page.

I believe the problem is the .each I’ve specified for the links within the section, as it’s relational to the page, rather than relational to each section. Essentially what I want to do is reset the count for each section so that the sections are treated separately.

Here’s what I have so far (see console log and click each of the buttons):
https://codepen.io/Shoxt3r/pen/PooPPzZ

Thanks in advance!

So… do exactly that.
Break your each loop up into two loops:
For each Section:
Set the link count to 0.
For each Link in this section:
Add 1 to link count.
Set data. (Bonus points: Do these two instructions in one line.)
EndForeach
EndForeach.

Ah of course… that makes sense:
https://codepen.io/Shoxt3r/pen/XWWmdxz

EDIT: Not sure I follow about doing two instructions in one line though - do you mean set data on different elements in one line? How would that be possible if I’m setting data on different elements and with different specificity? :slight_smile:

1 Like

No you actually DID do it. The point was that someone could take it literally:

and translate it as

link++;
$(this).data('link',link);

or whatever. The putting it in one line bit meant understanding prefix-vs-postfix returns, and that you can do

$(this).data(..otherstuff... ++link)

and combine the increment and assignment lines.

1 Like

Ah ok fair enough - thank you for your help!
I realised that resetting i to 0 when selecting each “a” was redundant so I removed that line and it works regardless haha.

Ok, so now I’m working with it slightly differently and assigning the data to each ‘a’ element via the ‘name’ attribute and also console logging it when the user clicks on a CTA (for now; eventually it will form part of an event that I’ll pass across via the Data Layer).

What I’m trying to avoid is duplication of code as the value of the variable linkIdent is identical but I can’t declare it outside of the ‘each’ and ‘click’ functions as the context of ‘this’ obviously isn’t available until later on.

The code works as it is but I’m just trying to do a bit of housekeeping so that I can adapt it in one place later on if I need to.

https://codepen.io/Shoxt3r/pen/BaaoGqp

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.