Change the visibility of a div element by leveraging the data-target attribute

Hey there, I have a question about how to use the data-target attribute to set the display of a div. Check out my HTML code below:

<div class="page page-current" id="home">
PAGE 1
  <a href="#" class="next" data-target="#about">Go to about</a>
</div>

<div class="page page-section" id="about">
PAGE 2
  <a href="#" class="next" data-target="#portfolio">Go to portfolio</a>
</div>

<div class="page page-section" id="portfolio">
  PAGE 3
</div>

In the code above, the divs with the class: page-section are initially hidden using CSS with: display:none. I was able to write a generic JavaScript function that determines which div should be visible:

$(".next").click(function(){
    var target = $(this).data("target");
  $(target).addClass("page-current");  
})

The issue now is that, while it adds the class: page-current to the second div, the first one still has this class as well.

Can anyone give me some advice on how to solve this in a way that ensures only one div at a time can have the class: page-current?

I've created a JSFIDDLE to demonstrate this problem.

Answer №1

If you want to achieve what you are looking for, you will need to eliminate the page-current from the current page and transfer it to the new element. Then, remove page-section from the new element and re-add it to the old one.

To accomplish this task, you can utilize the toggleClass() method in the following way:

$(".next").click(function() {
    var target = $(this).data("target");
    $('.page-current').add(target).toggleClass('page-current page-section');
})

Take a look at the live demo here

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

Modifying the clone() property in three.js affects all the meshes in my project

I am looking to create 100 identical cubes with a gradual decrease in opacity for each cube. This is my current loop implementation: var geometry = new THREE.BoxGeometry(0.15,0.15,0.15); var material = new THREE.MeshNormalMaterial(); var cube = new THREE. ...

The logical OR operator in JavaScript (denoted as ||)

Can anyone explain the functionality of this operator in JavaScript? I have come across this operator in two different contexts: //context 1 function(e){ e = e || window.event; //context 2 if(a || b) In C or C++, I understand that the return value of th ...

What causes React JS to continuously render in an infinite loop when using hooks and useState

I am struggling with updating the current state of my component based on a result using a custom hook in React. Whenever I try to update it, I end up in an infinite loop rendering due to my usage of the useState() hook. I am still new to working with Rea ...

Creating an HTML and CSS Dropdown Navigation Menu with Mouse-over Functionality

Is it possible to create a mouse-over dropdown menu using CSS and HTML? I have noticed websites like Google that have implemented such menus, where passing through triggers a hidden tag to become visible. Can anyone provide source code for this idea? Than ...

No internet connection detected - please check your connection and try again

In the scenario where the internet connection is not available, when the user clicks a button, an error message should be displayed using a dialog box. I attempted to use navigator.online in my Android mobile webview but it did not work. How can I show t ...

Establishing the controller to set the default order

Would appreciate some assistance with what may appear to be a beginner's question, please? This is the HTML code I'm working with: <!doctype html> <html> <head> <title>Starting Angular</title> </head> < ...

error when trying to bind attributes to knockout components

I am trying to dynamically add an id attribute to a tag, but it keeps giving me an error. "Uncaught ReferenceError: Unable to process binding "attr: function (){return {id:id} }" Message: id is not defined" Here is my HTML code- <label data-bind= ...

Angular Pagination: An issue arises when deleting records from the first page, as the following page's records are not automatically refilling the first page

I have implemented angular pagination to display records. Each record has a button labeled 'Assign to me'. Clicking on this button removes the selected record from the list. However, I am facing an issue where I display 10 records per page and if ...

Exploring the proper method for closing connections in Node JS and the pg module

I'm experiencing frustration with the node pg module as I keep encountering a 'too many clients already' error. For instance, in my app.js file, I handle various routes where I query data from postgres. Here's a snippet of how app.js i ...

Issue with Hover Behavior in Bootstrap 5 Navbar Dropdown

While developing a website using Bootstrap 5, I encountered an issue with the navbar dropdown not opening on hover despite attempting to add custom CSS. Strangely, the CSS code worked perfectly in isolation when I tested it in a code snippet, but failed to ...

Encountering the error "undefined object" while using the yield keyword in JavaScript

var pi = document.getElementById("pi"); function * calculatePi(){ let q = 1; let r = 0; let t = 1; let k = 1; let n = 3; let l = 3; while (true){ if (4*q+r-t < n*t){ alert(n); yield n; ...

The feature of scrolling to a specific element within a bootstrap modal is not functioning as expected

I recently encountered an issue while using a Bootstrap modal. The problem arose when I tried to scroll to a specific element within the modal, but my code didn't produce the desired results. $('#centralModalLg').on('show.bs.modal&apo ...

Maintaining checkbox state using fetch arrays

Included below is the code present on my site, pulling data for each season including numbers of home wins, win percentage, and win lsp. It functions correctly by creating a new table row for each season. Furthermore, there are two columns featuring filte ...

The mute feature in Discord.js along with setting up a muterole seems to be malfunctioning and encountering errors

Currently, I am working on implementing a mute command feature. The main goal is to have the bot automatically create a role called Muted if it doesn't already exist, and then overwrite the permissions for every channel to prevent users with that role ...

Arranging elements in an array based on two different properties

Trying to organize an array of elements (orders details). https://i.stack.imgur.com/T2DQe.png [{"id":"myid","base":{"brands":["KI", "SA"],"country":"BG","status":&qu ...

Display <video> component using Angular 2

When attempting to display videos sourced from an API link, I encountered a problem where only the player was visible without the actual video content. The navigation controls of the player were also unresponsive. Interestingly, when manually inputting the ...

Convert a file into an empty array when sending a post request from Angular to Laravel

I am currently working on a simple Laravel 5 post request that aims to achieve the following tasks: Save some data to a database. Store a file (image) in public storage with a name consisting of 20 random numbers followed by '.jpg'. Save a URL ...

Pause and then resume the submit() function after conducting an ajax validation

I recently posted a query [here] but unfortunately, I haven't received any answers yet. Here's what I am trying to accomplish and you can view my initial attempt at the provided link: User fills out form Prevent default form submission Check if ...

"Retrieve JSON data from MongoDB without any extra spaces or formatting, also known as unpretty

In my current setup with mongodb 2.2.0, I am working on a way to display json data in a single line format instead of the "pretty" printing typically achieved with printjson() or find().pretty(). Essentially, I want the documents to be listed in json forma ...

Angular2/TypeScript Coding Guidelines

I am curious about the common practices and consensus among the Angular2 community when it comes to writing reusable code in TypeScript. I have gathered some information and questions related to Angular2 that I would like to discuss. Organizing Module/A ...