I’m trying to randomize the way a list appears after it’s been built from a HubL Db. I’m struggling to integrate the javascript into the HubL markup workflow. What I’m trying to do is create a list that reorders itself randomly anytime the page is refreshed.
I understand that built into HubL are filters (random, shuffle) but neither of those produces the results I’m looking for.
Below is my markup;
{% set table = hubdb_table_rows(5296993) %}
{% if table == [] %}
<p class='align-center'>Sorry, no one found for that Search. Try changing your filter and search again.</p>
{% else %}
<ul>
{% for row in table %}
<li>
<a href="/brands/{{ row.hs_path }}">
<img src="{{ row.logo_bw.url }}" width="500" {% if row.image.width>row.image.height %}class="landscape"{% endif %} alt="Logo for {{ row.name }}">
</a>
</li>
{% endfor %}
</ul>
{% endif %}
Any assistance would be greatly appreciated. Thank you.
{% set rand_table = table|random %}
<ul>
{% for row in rand_table %}
<li>
<a href=“/brands/{{ row.hs_path }}”>
<img src=“{{ row.logo_bw.url }}” width=“500” {% if row.image.width>row.image.height %}class=“landscape”{% endif %} alt=“Logo for {{ row.name }}”>
</a>
</li>
{% endfor %}
</ul>
{% for row in rand_table %}
And I wouldn’t recommend mixing Hubl with js.
If you want to do pure javascript / jquery it works. Then just give li a class and mix it with jquery.
Best regards
Özcan
I tried what you suggested earlier - but it breaks the link between the database and the loop. I’m no longer pulling any data…you can see from my screenshot below.
I did – the screenshot I sent you was after I implemented the {% set rand_table = table|random %} to the markup block.
I’ll look into those JQuery blocks you sent me. Thanks again for the assistance.
Wanted to drop you a note to let you know I found a simple solution to the issue. It’s actually really simple.
Solution
HTML
{% if table == [] %}
<p class='align-center'>Sorry, no one found for that Search. Try changing your filter and search again.</p>
{% else %}
<ul class='brand-list'>
{% for row in table %}
<li>
<a href="/brands/{{ row.hs_path }}">
<img src="{{ row.logo_bw.url }}" width="500" {% if row.image.width>row.image.height %}class="landscape"{% endif %} alt="Logo for {{ row.name }}">
</a>
</li>
{% endfor %}
</ul>
{% endif %}
Javascript
var shuffle = document.querySelector('ul.brand-list');
for(var i = shuffle.children.length; i >= 0; i--) {
shuffle.appendChild(shuffle.children[Math.random() * i | 0]);
}
It’s based on a tutorial that I found here and works really slick.