More on This & Siblings

Menus; index, this, siblings

I’m obsessed with this, now that I understand how to better use it to my advantage.

I’m even more obsessed with using it with it’s siblings. I wrote a blog post the first time I tried this and siblings on my portfolio website, here, but I’m back with an update on how I took what was 10 lines of code x how many authors we were adding to a landing page, currently the code was sitting at 30 lines and soon another author was going to be added, 40 lines.

I was then given another project that wanted to use the same layout and menu, with three authors, so I wanted to find a way to compact the code into a smaller amount of javascript that also didn’t need to be added to if we wanted to add more authors down the line, this also helps when you have multiple developers working on the same landing pages at different times.

The original code (that lives on this page) looks like this:

This doesn’t look bad, but when you have to do it for each author it turns to a lot of javascript. Using this and siblings(); I was able to change it to a smaller amount of code (here) and that no one has to update or add more to as we add authors. Which became this:

I also used nth-child and index(); and some variables to tell it which menu item was clicked on and what article (author section) it relates to to show that one and not the others. The index starts at 0, but my author articles start at 1, therefore (line 540) I had to add a 1 to my menu index.

I am really happy that I was able to figure this out for myself with the help of google and my notebook, which looks like a rambling mess of dots and single quotes.

Okay bye! You can find me on twitter @erkdonovan