Synchronize chosen navigation items using jQuery

I have implemented the following functionality, but I am encountering an issue where the selected navigation item does not get highlighted in red when using the next and previous buttons. I have also chosen not to use IDs on the panels to allow for flexibility in adding or removing them. Is there a more efficient way to code this?

$(function($) {
  $(document).on('click', ".slidenav", function() {

    $("span.slidenav").on('click', function() {
      $(".panel").removeClass("active");
      var newPanel = $(this).index();
      $(".panel").eq(newPanel).addClass("active");

      $("span.slidenav").removeClass("selected");
      $(this).addClass("selected");
    });

  });

});

$(document).on('click', "#next", function() {

  if ($('.active').next('.panel').length) {
    $('.active').removeClass('active')
      .next('.panel')
      .addClass('active');
  }

});

$(document).on('click', "#prev", function() {
  if ($('.active').prev('.panel').length) {
    $('.active').removeClass('active')
      .prev('.panel,.slidenav')
      .addClass("active");
  }
});
.panel {
  width: 300px;
  height: 300px;
  position: absolute;
  display: none;
}

.panel:nth-child(1) {
  background: #ddd;
}
.panel:nth-child(2) {
  background: #ccc;
}
.panel:nth-child(3) {
  background: #bbb;
}
.panel:nth-child(4) {
  background: #aaa;
}

.active {
  display: block;
}

.selected {
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<nav>
    <span class="slidenav selected">Panel 1</span>
    <span class="slidenav">Panel 2</span>
    <span class="slidenav">Panel 3</span>
    <span class="slidenav">Panel 4</span>
</nav>
<hr>
<div id="prev">Prev</div>
<div id="next">Next</div>
<hr>
<div class="panel-wrap">
    <div class="panel active">
    Panel 1
    </div>
    <div class="panel">
    Panel 2
    </div>
    <div class="panel">
    Panel 3
    </div>
    <div class="panel">
    Panel 4
    </div>
</div>

You can view the complete codepen here

Answer №1

To achieve the same effect that you currently have with the .active class on the .panel elements, apply it to the .selected class on the .slidenav elements as well.

Update: Additionally, there was an issue with your initial event binding: With each click on a .slidenav element, you were repeatedly attaching the click event handler.

$(function($) {

  $("span.slidenav").on('click', function() {
    $(".panel").removeClass("active");
    var newPanel = $(this).index();
    $(".panel").eq(newPanel).addClass("active");

    $("span.slidenav").removeClass("selected");
    $(this).addClass("selected");
  });
  
  $(document).on('click', "#next", function() {
    if ($('.active').next('.panel').length) {
        $('.active').removeClass('active')
                    .next('.panel')
                    .addClass('active');
        $('.selected').removeClass('selected')
                    .next('.slidenav')
                    .addClass('selected');
    }

  });

  $(document).on('click', "#prev", function() {
    if ($('.active').prev('.panel').length) {
        $('.active').removeClass('active')
                    .prev('.panel')
                    .addClass('active');
        $('.selected').removeClass('selected')
                    .prev('.slidenav')
                    .addClass('selected');
    }
  });
});
.panel {
  width: 300px;
  height: 300px;
  position: absolute;
  display: none;
}

.panel:nth-child(1) {
  background: #ddd;
}
.panel:nth-child(2) {
  background: #ccc;
}
.panel:nth-child(3) {
  background: #bbb;
}
.panel:nth-child(4) {
  background: #aaa;
}

.active {
  display: block;
}

.selected {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav>
    <span class="slidenav selected">Panel 1</span>
    <span class="slidenav">Panel 2</span>
    <span class="slidenav">Panel 3</span>
    <span class="slidenav">Panel 4</span>
</nav>
<hr>
<div id="prev">Prev</div>
<div id="next">Next</div>
<hr>
<div class="panel-wrap">
    <div class="panel active">
    Panel 1
    </div>
    <div class="panel">
    Panel 2
    </div>
    <div class="panel">
    Panel 3
    </div>
    <div class="panel">
    Panel 4
    </div>
</div>

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

Evolution from IE8 to IE11

Here is the code snippet I am currently using: container = document.getElementById("menuContainer"); Following this, I have the following lines of code: container.document.open("text/html"); container.document.writeln(content); container.doc ...

Tips for preventing PyCharm from automatically completing HTML and Django template tags

While working on Django templates in PyCharm, I noticed that it automatically closes the tags. This can be helpful when starting a new tag, but it becomes annoying when I want to place existing content within a different tag because I have to delete or mov ...

What is it about Kyle Simpson's OLOO methodology that seems to swim against the tide of Typescript's popularity?

Disclaimer: this post might come across as impulsive. Warning for Typescript beginners! Also, a bit of a vent session. Recently, I delved into the OLOO approach from the YDKJS book series within a Typescript and Node environment. // ideal JS syntax le ...

Execute a function in wxHtmlWindow after the page has finished loading

I'm currently facing an issue with wxPython that I could use some help with. My goal is to create a basic HTML window with forward and backwards navigation buttons. However, I'm encountering difficulties when users click on links within the page. ...

javascript - The onmessage event will not trigger when using a Java server

I have encountered an issue with my Java server and JavaScript websocket client. Despite trying various solutions from this site, I am still unable to resolve the problem. So, I decided to share my code here in hopes of getting some assistance. The proble ...

Display information based on the radio button chosen

I've set up a radio button with options for "no" and "yes", but neither is selected by default. Here's what I'm trying to achieve: If someone selects "no", nothing should happen. However, if they select "yes", then a message saying "hello w ...

How to efficiently insert multiple documents into MongoDB using JavaScript

I'm currently working on inserting data into a MongoDB collection. I have a loop set up where I am receiving sample data in each iteration as shown below: 13:24:24:007,Peter,male,3720,yes 13:24:24:007,John,female,1520,yes 13:24:24:023,John,female,972 ...

Challenges faced when using HTML templating in Express

Dear friends, I'm currently facing an issue with EJS and express while trying to modify my HTML file. My aim is to retrieve user data through an HTML form like so: <form action="/" method="post"> <input type="text&qu ...

Having Trouble Scooting Down the Page on Mobile?

Hello there! I'm having a bit of trouble trying to figure out why the scrolling functionality isn't working on my small web app when it reaches the media breakpoint for mobile devices. If you'd like to take a look, here's the link to ...

Leveraging the Power of SASS Variables Across Your Entire NativeScript Application

Currently, I am in the process of developing an app using NativeScript 6.4.1 along with Angular 8. In order to enhance my styling capabilities, I have decided to incorporate SASS due to its advantageous features like variable names. My designer has suppli ...

Tips on confirming the completion of my form when the next button is pressed

I am working on a multi-step form with a jQuery script to split the forms. The first form has only one button - the next button, which takes the client to the next form. However, when I click on the next button in the first form, it moves to the next form ...

What is the best way to connect a key to a specific sorting method in AngularJS?

In the current scenario, there is a GET request containing key:value data. I have a table header with keys and values which can be sorted as follows: <th> <a href="#" ng-click="sortType = 'scenarioNo'; sortReverse = !sortReverse ...

Conceal and reveal elements using v-if

Check out my fiddle: DEMO creating a new Vue instance: { el: '#app', data: { modules: ['abc', 'def'] } } I am looking for a way to hide or show elements using v-if based on the values in an array called modules[]. ...

Searching for a specific value within a hash in MongoDB

I am working with MongoDB documents formatted like this: { "_id": ObjectId("5406e4c49b324869198b456a"), "phones": { "12035508684": 1, "13399874497": 0, "15148399728": 1, "18721839971": 1, "9831132110 ...

Swap out video files using jQuery

I have a basic video player setup <video id="video" src="http://xyx.com/zzz.m3u8" controls="controls" width="480" height="280"></video> I would like the ability to switch between different video streams by clicking on a link, for example &l ...

Can AJAX be used to show only a specific echo response from the server?

I am currently exploring how to utilize Ajax in PHP to specifically display a certain response. In this scenario, I have a PHP script that generates the following responses - echo 'Success'; //I want to focus on displaying only this //Additiona ...

Creating a personalized error page with the .htaccess file

I want to create personalized error pages for different errors This is the layout of my directory: .htaccess error_pages: error_400.html error_401.html error_404.html ...

SwiperJS: Issue with slide order and slide per column functionality within grid layout

sandbox: demo Swiper version: ^11.0.5 The arrangement of slides and rows per column is not as expected. I am currently using Vue with the swiper component, but the issue persists even in a simple HTML demo. To achieve 3 rows per column in a single view, ...

Creating internal utility functions in Angular without exporting them as part of the module can be achieved by following a

Currently, I'm in the process of creating an angular module called MyModule. This module includes several sub-modules. angular.module('MyModule', [ 'MyModule.SubModule1', 'MyModule.SubModule2', 'MyModule.SubMo ...

Tips for resolving the issue: 'Unhandled Promise Rejection: Error: Unable to resolve bare specifier "app.js" from http://localhost:3000/'

While delving into TypeScript, I have come across an error related to node modules. https://i.sstatic.net/IPx5A.png Upon clicking the anonymous function, it leads me to the following code snippet. https://i.sstatic.net/4U8dY.png <!DOCTYPE html> & ...