Upon revisiting the issue, I have come up with a more efficient solution. Instead of adding an active class to list items on click events as before...
$(".products ul li a").on("click", function(e) {
$this.closest("li").toggleClass("active");
}
I now believe it would be better to assign the active class to list items when the History statechange event occurs. This approach involves extracting GET URL parameters first, then identifying list items whose data-value attribute matches the URL values.
Outlined below are the steps required to locate the correct matching elements:
- Trigger the activate_items() method on the History.js statechange event
- Determine if there are any URL parameters named "product_cats" or "color" and whether they contain values
- Create a jQuery collection of list items
- Check if each list item in the collection has a data attribute named "value" that corresponds to one of the URL parameter values
- If a match is found, apply the active class to the list item
- Remove the active class if no match is found
For instance, consider the following example of my URL parameters containing two arguments, each with multiple values:
localhost/mytheme/?product_cats=17,60&color=13,14
History.Adapter.bind(window,'statechange',function(e){
activate_items();
}
// GET PARAMETER
function get_parameter( name ){
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var state = History.getState();
var current_url = state.cleanUrl;
var results = regex.exec( current_url );
if( results == null )
return "";
else {
return results[1];
}
}
// ACTIVATE ITEMS
function activate_items( url ){
var items;
// Categories
var cats = get_parameter("product_cats");
var colors = get_parameter("color");
if (cats.length > 0) {
items = jQuery(".product ul li a");
// Check each <li> for a match. If its data-value attribute matches
// one of the values from cats than add an active class to the <li>
};
if (colors.length > 0) {
items = jQuery(".product ul li a");
// Check each <li> for a match. If its data-value attribute matches
// one of the values from colors than add an active class to the <li>
};
}
It's evident from the code that I am still working on implementing the matching functionality.
In summary, my goal is to ensure that when users navigate using the back, forward, or refresh buttons, the list items retain the correct active state based on the URL parameters. I welcome any suggestions or alternative approaches to tackle this challenge.