The active class consistently adds new menu options without removing the previous ones

I am facing an issue with my menu where the active class does not get added to the new menu item when clicked, despite being removed from the previous item.

Below is the code snippet:

<div class="row text-center" id="side-menu">
   <nav>
      <ol>
         <li>
            <a href="#page1" class="myanimate">
              <span class="icons iconactive"><i class="fa fa-circle"></i></span>
              <span class="namee">Home</span>
            </a>
        </li>
         <li>
            <a href="#page2" class="myanimate">
              <span class="icons"><i class="fa fa-circle"></i></span>
              <span class="namee">Design</span> 
            </a>
        </li>
         <li>
            <a href="#page3" class="myanimate">
              <span class="icons"><i class="fa fa-circle"></i></span>
              <span class="namee">Review</span>
            </a>
        </li>
     </ol>
  </nav>
</div>

CSS for Active Menu:

.iconactive{
    font-size: 15px;
    color: brown;
    margin-right: -3.2px;
}

Jquery Code Snippet:

$(document).ready(function() {
 var scrollLink = $('.myanimate');

  // Smooth scrolling
  scrollLink.click(function(e) {
    e.preventDefault();
     $('body,html').animate({
       scrollTop: $(this.hash).offset().top
     }, 2000 );
   });
     
     // Active link switching
  $(window).scroll(function() {
    var scrollbarLocation = $(this).scrollTop();
     scrollLink.each(function() {
      var sectionOffset = $(this.hash).offset().top - 20;
      if ( sectionOffset <= scrollbarLocation ) {
        $(this).children('.icons').addClass('iconactive');
        $(this).children('.icons').removeClass('iconactive');
      }
    });
  });
});

Answer №1

Here's a jQuery code snippet that toggles the active class on and off from the same element:

$(document).ready(function() {
 var scrollLink = $('.myanimate');

  // Smooth scrolling
  scrollLink.click(function(e) {
    e.preventDefault();
     $('body,html').animate({
       scrollTop: $(this.hash).offset().top
     }, 2000 );
   });
     // Active link switching
  $(window).scroll(function() {
    var scrollbarLocation = $(this).scrollTop();
     scrollLink.each(function() {
      var sectionOffset = $(this.hash).offset().top - 20;
      if ( sectionOffset <= scrollbarLocation ) { 
       $('.icons').removeClass('iconactive');
       $(this).children('.icons').addClass('iconactive'); 
      }
    });
  });
});

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

Having trouble sending an ajax request from localhost to a remote server

When attempting to make an ajax request (using jquery) from my local server to a remote page where I am the administrator, I encounter the following error: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin &ap ...

Using a table row as a counter in HTML

I am looking for a way to automatically assign IDs to table rows using XSLT in a systematic manner. The idea is to have the ID consist of a string followed by a counter, like this: <table> <tr id="Row1"> # it can be only a number => id=" ...

What is the best way to create a layout for Flexbox project boxes with three boxes per row?

My project cards are displaying in a single horizontal line and expanding infinitely to the right, rather than appearing in rows of three as intended. This causes them to extend outside the visible area in a long horizontal strip. See the issue in action ...

Once AJAX has successfully retrieved the data

I am exploring the option of using jQuery ajax to fetch data from a database and display it asynchronously. However, I am faced with the challenge of achieving this without refreshing the entire page each time. For instance, the PHP file called during an ...

using jquery, how can you send multiple parameters in an ajax request

Hello and welcome! I'm having trouble passing parameters through an ajax URL. I am attempting to send multiple data using the jQuery $.ajax method to my PHP script, but I can only pass a single data item when concatenating multiple data entries toget ...

Incorporate a 'Select All' functionality into ion-select by adding a dedicated button

Looking for a way to set custom buttons on ion-select through interfaceOptions in ionic 4? HTML <ion-item> <ion-label>Lines</ion-label> <ion-select multiple="true" [(ngModel)]="SelectedLines" [interfaceOptions]="customAlertOption ...

Placing a pair of labels onto a bootstrap form while ensuring column alignment

I'm trying to format a form according to my UI/UX specifications, where there is a parent label and two sub-labels. Can this be achieved using Bootstrap? https://i.stack.imgur.com/J8wJZ.png However, I'm struggling to align the columns and rows ...

The functionality of the Datatable column select filter sort() is malfunctioning when there is a link present

I am encountering an issue with the datatable column select filter. One of the columns in my table contains HTML link tags, which is causing unsorted select options to appear at the top. <th><a href="{{route('customer.information', ...

Is there a way to keep Angular from automatically re-sorting my list when I make edits to it?

I have designed a small application with Angular for managing Todolists. Each list contains multiple todos, where each todo has attributes such as name, value1, and value2. To automatically sort each list using Angular, I utilized ng-repeat="todo in selec ...

Tips for personalizing PNG images within an SVG element

Looking to update the color of a PNG image within an SVG tag. The PNG images I have are transparent, and I want to customize their colors based on user selections. How can this be achieved? Is there anyone out there who can assist me? <HoodieSvg ...

Troubleshooting z-index conflict when using :before pseudo element to emphasize list entries

I am experiencing an issue with highlighting items in a list generated by JSTree using the :before pseudo element. The z-indexes seem to be causing some trouble, as adjusting them results in the highlighting appearing either behind all links or in front of ...

What is the method for selecting the "save as" option while downloading a file?

Imagine a scenario where you click on a link like this: <a href="1.txt">Download</a> After clicking the link, a save as window will appear. Is it feasible to utilize JavaScript in order to simulate button clicks within that window? Alternativ ...

Implement JQuery to display a loading message whenever an a tag is clicked

The website's various pages are filled with standard <a> tags, some of which have a class attribute that is utilized for styling using CSS. Each <a> tag includes a href="" attribute linking to another page on the same site. My goal is to d ...

Is there a way to append the current path to a link that leads to another URL?

I am currently in the process of separating a website, with the English version being on the subdomain en. and the French version residing on the www. Before making this change, I have a drop-down menu that allows users to select their preferred language ...

Updating dynamic content in IBM Worklight V6.1 with jQuery Mobile v1.4.3 requires waiting for the DOM to load

I need to dynamically update the content of a div within my HTML page structure. <!DOCTYPE HTML> <html> ... <body> <div data-role="page"> <div data-role="header"> //Image </div> <!-- Th ...

css - Tips for reducing the speed of inertia/momentum scrolling on mobile devices

I have been working on creating a scrollable card gallery using a CSS grid layout. The structure I am following is similar to this: <div class="gallery-wrapper"> <div class="gallery-container"> <div id="card-1" class="gallery-ca ...

Complete the form by following a hyperlink located on a different webpage

I recently developed three PHP pages. The first one consists of the following form: <form method="POST" name="go" action="search_form_all.php" > <input name="value" type="text" id="search_form_1" size="65" placeholder="enter name"/> <i ...

Using jqGrid to load additional JSON data after the initial local data has already been populated in the

I encountered a specific issue: I have a compact form with four choices. Users can choose to fill them out or not, and upon clicking 'Ok', a jqGrid is loaded with data based on those selections. To accommodate dynamic column formatting, my servle ...

A guide on rotating loaders and inserting custom text within loaders using CSS

Seeking assistance to modify my code for creating a unique loader design. The inner loader needs to remain static with only top and bottom segments, while the middle loader rotates anti-clockwise and the outer loader rotates clockwise. Additionally, the ...

Unravel the JSON structure

Here is the JSON response I received from an AJAX call: [{"id":null,"period":null,"until":null,"agent_id":"15","agent_zlecajacy_id":"15","offer_id":null,"status":"1","tytul":"Pobranie ksi\u0105g","tresc":"Pobranie ksi\u0105g","data_aktualizacji" ...