Remove the active class from a list item using History.js

My goal is to add the active class to a link when clicked in my AJAX app, triggering statechange on History.js. I'm struggling with saving the current active link(s) with the state so that the active class is appropriately added or removed when navigating back or forward using the browser buttons. Can you help me understand how to achieve this?

Answer №1

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:

  1. Trigger the activate_items() method on the History.js statechange event
  2. Determine if there are any URL parameters named "product_cats" or "color" and whether they contain values
  3. Create a jQuery collection of list items
  4. Check if each list item in the collection has a data attribute named "value" that corresponds to one of the URL parameter values
  5. If a match is found, apply the active class to the list item
  6. 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.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting issue with multer code failing to save files in designated directory within nodejs server when using reactjs frontend

I'm facing an issue while trying to upload a photo into my server folder. Even though the submission process adds the picture to my database, it does not display the image in my server folder. The frontend of my application is built using React JS, an ...

Is there a way to remove a certain child category post from appearing in a parent category?

I'm having trouble with displaying related posts by category while excluding a specific category. I've tried different methods but none seem to work, and I'm not sure how else to approach this issue. <?php $categories = get_the_terms ...

How to encase HTML content within a scope variable without relying on ng-bind-html

Is there a way to include HTML content using a scope variable in AngularJS without utilizing ng-bind-html-unsafe? <div ng-controller="dataController">{{test}}</div> $scope.test = "<div>Html content</div>" ...

Errors are not displayed or validated when a FormControl is disabled in Angular 4

My FormControl is connected to an input element. <input matInput [formControl]="nameControl"> This setup looks like the following during initialization: this.nameControl = new FormControl({value: initValue, disabled: true}, [Validators.required, U ...

Changing VueJS duplicate values with v-model (:value, @input)

I'm encountering an issue with v-model in my custom component. I prefer not to use State or Bus. Currently, the component successfully returns a single value in App.js, but it duplicates itself. I'm struggling to resolve this problem, so any help ...

Using Python Selenium to create a login page with Javascript

Attempting to access a page using Python selenium package for certain activities is proving challenging. Despite the following code being written, an error message of "the Class is not found" keeps appearing. To proceed with using send_keys(), it's ne ...

Conceal the option to "show more" when there are no additional posts to display

Is there a way to dynamically hide the load button when no more posts are available? I've included my code below: function.php function load_more_posts_ajax(){ $offset = $_POST["offset"]; $ppp = $_POST["ppp"]; header("Content-Type: tex ...

AngularJS testing typically involves the use of the inject module injection process

Currently, I am working on testing a service called documentViewer, which relies on another service named authService. angular .module('someModule') .service('documentViewer', DocumentViewer); /* @ngInject */ function Do ...

Troubleshooting my nodejs websocket chat for message sending glitches

The chat system is built on nodejs using websockets from socket.io library. While I have a client that also utilizes websockets from socket.io, I'm facing challenges in making the two communicate effectively. The issue seems to be with the client not ...

Issue with onClientClick not functioning properly when performing a jQuery function call

How can I make a jQuery form appear when an ASP.NET server-side button is clicked by the user? Currently, when I click on the button during runtime, the page reloads quickly without displaying the jQuery form. I am aiming to achieve a similar effect show ...

Glass-pane or angular/HTML overlay on a designated element

Is there a way to create a glass-pane effect, like an hourglass symbol on a semi-transparent layer, within the boundaries of an HTML element E? The goal is to have the glass-pane only overlap the area within E's boundaries. When the glass-pane is ac ...

What is the distinction between selecting and entering a date input value?

When a user selects a date, it needs to be immediately sent to the server. If they manually type in the date, it should be sent on blur. The issue arises when the oninput event is triggered for each keydown event, causing unnecessary server requests while ...

Exploring the possibilities of toggling between a personalized CSS design and a Bootstrap CSS layout

Is it possible to implement a dropdown menu on my sample-page using javascript/jquery in order to switch between a custom layout and a bootstrap layout? ...

Mastering the art of switching between different application statuses in ReactJS

As a newcomer to reactJS, I am exploring ways to make one of my components cycle through various CRUD states (creating object, listing objects, updating objects, deleting objects). Each state will correspond to displaying the appropriate form... I have co ...

The event bus I'm using isn't functioning properly within the axios interceptor, yet it operates smoothly in all my Vue components

Currently, I am utilizing VueJs and mitt for the eventBus. The mitt is globally loaded and functioning correctly as shown below: main.js const emitter = mitt(); const app = createApp(App) app.config.globalProperties.emitter = emitter I am able to call t ...

Use jQuery to trigger a click event when an element is in focus, unless it was clicked to

I am currently developing a website using the MDL framework. One issue I encountered is that there is no default select form element provided. After some research, I found a solution by utilizing a menu component that displays when the input is clicked. Th ...

MongooseError: The parameter `uri` passed to the `openUri()` function must be of type string, but instead received "undefined"

Recently delving into mongo, I encountered a connection error that has me stumped. The error message reads as follows: MongooseError: The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose ...

The upload directory in KCFinder can be accessed and selected using a URL

Issue: While using the link to open kcfinder as defined in kcfinder, I encountered a problem. The link is intended to open kcfinder with the provided parameters: window.open('/kcfinder/browse.php?type=files&dir=files/public&subDi ...

Node interprets string as an object

I encountered the following code: <a class="btn-primary btn" href="/employer/booth/<%= user._id.toString() %>" <% console.log(typeof user._id, user._id) %> target="_blank"> Preview your booth </a> Upon running this ...

How to Retrieve the Value of <input type=date> Using TypeScript

I am currently developing a survey website and need assistance with retrieving user input for two specific dates: the start date and end date. I aim to make the survey accessible only between these dates, disabling the "take survey" button after the end da ...