I want to create a little side navigation for on-page navigation. The site contains multiple images one above the other, the navigation is inside every single image and is linking to the individual id's.
I am using jekyll with the liquid templating engine. To not hard code every single element I created a for-loop which gets its data of a seperat .yml file.
This is how it should looks like:
Image
My problem is that its not working on the first element. Inside the first navigation element the first circle should be selected. But its not:
Image
This is the code:
{% for element in site.data.elements %}
{% capture number %}{{ forloop.length }}{% endcapture %}
<section id="spezial-{{forloop.index}}" {% assign imgIndex = {{forloop.index0}} %} class="spezial-img" style="background-image:url('{{ element.bild }}');">
<div class="container spezial-container">
<div class="sub-navi">
<ul>
{% for y in (1..number) %}
{% if imgIndex == naviIndex %}
<li><a href="#spezial-{{forloop.index}}" {% assign naviIndex = {{forloop.index}} %} {{ naviIndex }} class="active" ><i class="fa fa-dot-circle-o"></i></a></li>
{% else %}
<li><a href="#spezial-{{forloop.index}}" {% assign naviIndex = {{forloop.index}} %}><i class="fa fa-circle-o"></i></a></li>
{% endif %}
{% endfor %}
</ul>
</div>
</div>
</section>
{% endfor %}
You're comparing two counter that are not working the same way.
{% assign imgIndex = {{forloop.index0}}
This will count from 0 to array.size-1
{% assign naviIndex = {{forloop.index}}
This will count from 1 to array.size
As your not in the same "time zone", for the first image you have
imgIndex == naviIndex
0 == 1 -> false
And then, starting from the second loop,one time in each loop you will reach an equality but not on the right element.
On the second imgIndex element, for example, the active class will be set on the first naviIndex element but it's wrong. And it's the same for all following elements.
Correct code can be :
{% for element in site.data.elements %}
{% capture number %}{{ forloop.length }}{% endcapture %}
{% assign imgIndex = {{forloop.index}} %}
<section id="spezial-{{imgIndex}}" class="spezial-img" style="background-image:url('{{ element.bild }}');">
<div class="container spezial-container">
<div class="sub-navi">
<ul>
{% for naviIndex in (1..number) %}
{% if imgIndex == naviIndex %}
<li><a href="#spezial-{{forloop.index}}" %} {{ naviIndex }} class="active" ><i class="fa fa-dot-circle-o"></i></a></li>
{% else %}
<li><a href="#spezial-{{forloop.index}}" {% assign naviIndex = {{forloop.index}} %}><i class="fa fa-circle-o"></i></a></li>
{% endif %}
{% endfor %}
</ul>
</div>
</div>
</section>
{% endfor %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With