This is on Shopify platform.
I am using JQuery and CSS to highlight an active link in a subcategory list by adding .active class to the element.
After adding the JQuery, the element is NOT working and doesn’t redirect to the link page.
{%- for block in section.blocks -%}
{%- assign image = block.settings.image -%}{%- assign url = block.settings.url -%}
<div id="subcategories" class="cat_space_item {{ccol}} brand_item nt_{{block.id}} tc">
<a href="{{ url }}" class="db" target="{{block.settings.open_link}}">
<p>{{ block.settings.coll_title }}</p>
</a>
</div>
{%- endfor -%}
<script>
$('document').ready(function() {
$('#subcategories a').click(function(e) {
e.preventDefault();
$('#subcategories a').removeClass('active');
$(this).addClass('active');
});
});
</script>
<style>
.active { font-weight: bold; font-size: 20px; background-color: yellow;}
</style>
I tried add the ‘on’ event delegation but it is still not working.
<script>
$('document').ready(function() {
$('#subcategories').on('click', 'a.db', function() {
e.preventDefault();
$('#subcategories a').removeClass('active');
$(this).addClass('active');
});
});
</script>
2
Answers
To those who want to know my final working code.
The issue with the code you provided seems to be that you are preventing the default behavior of the anchor tag () by calling e.preventDefault(); , but you’re not actually redirecting the user to the link’s URL.
To fix this, you can add a line of code that redirects the user to the clicked link’s URL using window.location.href after adding the .active class to the clicked link.
This will add the .active class to the clicked link, prevent the default behavior of the anchor tag, and then redirect the user to the clicked link’s URL.