Display information upon the clicking of a button and update the color of the selected button

When a button is pressed, I want to display content and change the color of the active button. Currently, I can do each operation individually, but I'm struggling to merge these functionalities.

This is how my script looks like for displaying the content:

function toggleData(parameter){
  if(parameter==0){
    document.getElementById('myreport').style.display = 'none';
    document.getElementById('mydata').style.display = 'block';
  }
  else{
    document.getElementById('mydata').style.display = 'none';
    document.getElementById('myreport').style.display = 'flex';
  }
}
* {
  margin: 0;
  padding: 0;
}
#mydata{
  display:none;
  font-size: 25;
}
.chartCard {
  width: 100vw;
  height: calc(80vh - 100px);
  background: rgb(133, 43, 43);
  display: flex;
  align-items: center;
  justify-content: center;
}
.chartBox {
  width: 650px;
  padding: 30px;
  border-radius: 20px;
  margin: 1px 22px;
  border: solid 3px rgba(255, 26, 104, 1);
  background: white;
}
.button:hover{
  background-color: #005201;
  color: rgb(255, 253, 250);;
}
.button {
  background-color: rgb(69, 9, 188);
  border: none;
  color: white;
  padding: 16px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 20px;
  margin: 2px 2px;
  transition-duration: 0.4s;
  cursor: pointer;
}
<button class="button" onclick="toggleData(1)">Myreport</button>
<button class="button" onclick="toggleData(0)">Mydata</button>
<div id="mydata">
  <h1>This is my Data</h1>
</div>
  <div class="chartCard" id="myreport">
    <div class="chartBox">
      <p>Ram</p>
    </div>
    <div class="chartBox">
      <p>Shyam</p>
  </div>
</div>

In order to highlight the active button, I added

.highlight{background-color: green;}
in CSS and included a new script:

var buttons = document.querySelectorAll("button");
for (button in buttons) {
  buttons[button].onclick = function() {
    console.log('test')
    buttons.forEach(function(btn){
      btn.classList.remove('highlight');
    })
    this.classList.add('highlight');
  }
}

function toggleData(parameter){
  if(parameter==0){
    document.getElementById('myreport').style.display = 'none';
    document.getElementById('mydata').style.display = 'block';
  }
  else{
    document.getElementById('mydata').style.display = 'none';
    document.getElementById('myreport').style.display = 'flex';
  }
}

var buttons = document.querySelectorAll("button");
for (button in buttons) {
  buttons[button].onclick = function() {
    console.log('test')
    buttons.forEach(function(btn){
      btn.classList.remove('highlight');
    })
    this.classList.add('highlight');
  }
}
* {
  margin: 0;
  padding: 0;
}
#mydata{
  display:none;
  font-size: 25;
}
.chartCard {
  width: 100vw;
  height: calc(90vh - 100px);
  background: rgb(133, 43, 43);
  display: flex;
  align-items: center;
  justify-content: center;
}
.chartBox {
  width: 650px;
  padding: 30px;
  border-radius: 20px;
  margin: 1px 22px;
  border: solid 3px rgba(255, 26, 104, 1);
  background: white;
}
.button:hover{
  background-color: #005201;
  color: rgb(255, 253, 250);
}
.button {
  background-color: rgb(69, 9, 188);
  border: none;
  color: white;
  padding: 16px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 20px;
  margin: 2px 2px;
  transition-duration: 0.4s;
  cursor: pointer;
}
.highlight {
  background-color: green;
}
<button class="button" onclick="toggleData(1)">Myreport</button>
<button class="button" onclick="toggleData(0)">Mydata</button>
<div id="mydata">
  <h1>This is my Data</h1>
</div>
<div class="chartCard" id="myreport">
  <div class="chartBox">
    <p>Ram</p>
  </div>
  <div class="chartBox">
    <p>Shyam</p>
  </div>
</div>

I am seeking help on how to achieve both functionalities together. Any assistance would be greatly appreciated.

Answer №1

To update the functionality in your code, ensure to remove the existing class in changedata() and then add it to the clicked element.

document.querySelectorAll(".button").forEach((e) => {
    e.classList.remove('highlight');
});
event.target.classList.add('highlight');

function changedata(parameter){
  document.querySelectorAll(".button").forEach((e) => {
    e.classList.remove('highlight');
  });
  event.target.classList.add('highlight');
  if(parameter==0){
    document.getElementById('myreport').style.display = 'none';
    document.getElementById('mydata').style.display = 'block';
  }
  else{
    document.getElementById('mydata').style.display = 'none';
    document.getElementById('myreport').style.display = 'flex';
  }
}
* {
  margin: 0;
  padding: 0;
}
#mydata{
  display:none;
  font-size: 25;
}
.chartCard {
  width: 100vw;
  height: calc(90vh - 100px);
  background: rgb(133, 43, 43);
  display: flex;
  align-items: center;
  justify-content: center;
}
.chartBox {
  width: 650px;
  padding: 50px;
  border-radius: 20px;
  margin: 1px 22px;
  border: solid 3px rgba(255, 26, 104, 1);
  background: white;
}
.button:hover{
  background-color: #005201;
  color: rgb(255, 253, 250);;
}
.button {
  background-color: rgb(69, 9, 188);
  border: none;
  color: white;
  padding: 16px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 20px;
  margin: 2px 2px;
  transition-duration: 0.4s;
  cursor: pointer;
}
.highlight {
  background-color: green;
}
<button class="button highlight" onclick="changedata(1)">Myreport</button>
<button class="button" onclick="changedata(0)">Mydata</button>
<div id="mydata">
  <h1>This is my Data</h1>
</div>
<div class="chartCard" id="myreport">
  <div class="chartBox">
  <p>Ram</p>
</div>
<div class="chartBox">
  <p>Shyam</p>
  </div>
</div>

Answer №2

Using the .onclick method on buttons twice can lead to the first function being overwritten by the second function. One way to avoid this issue is by using the addEventListener() method, which allows you to attach specific event handlers to elements. With this method, you can also add multiple event handlers for an event.

In JavaScript, it is considered good practice to keep functions separate. In the code snippet below, there is a function called setActiveClass() with two parameters: element and classname. By changing the value of the variable activeClassName, you can easily modify the classname without having to update it everywhere in your code.

let myReportBtn = document.getElementById("reportBtn");
let myDataBtn = document.getElementById("dataBtn");

let buttons = document.querySelectorAll("button");

function changedata(bool) {
  let myReport = document.getElementById('myreport');
  let myData = document.getElementById('mydata');

  const activeClassName = 'highlight';

  if (!bool) {
    myReport.style.display = 'none';
    myData.style.display = 'block';
    setActiveClass(myDataBtn, activeClassName);
  } else {
    myData.style.display = 'none';
    myReport.style.display = 'flex';
    setActiveClass(myReportBtn, activeClassName);
  }
}

function setActiveClass(elem, classname){
  buttons.forEach(function(btn) {
    btn.classList.remove(`${classname}`);
  });
  elem.classList.add(`${classname}`);
}

myReportBtn.addEventListener("click", function(){
  changedata(true);
});

myDataBtn.addEventListener("click", function(){
  changedata(false);
});
* {
  margin: 0;
  padding: 0;
}

#mydata {
  display: none;
  font-size: 25;
}

.chartCard {
  width: 100vw;
  height: calc(50vh - 100px);
  background: rgb(133, 43, 43);
  display: flex;
  align-items: center;
  justify-content: center;
}

.chartBox {
  width: 650px;
  padding: 50px;
  border-radius: 20px;
  margin: 1px 22px;
  border: solid 3px rgba(255, 26, 104, 1);
  background: white;
}

.button:hover {
  background-color: #005201;
  color: rgb(255, 253, 250);
}

.button {
  background-color: rgb(69, 9, 188);
  border: none;
  color: white;
  padding: 16px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 20px;
  margin: 2px 2px;
  transition-duration: 0.4s;
  cursor: pointer;
}

.highlight {
  background-color: yellow;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <button class="button" id="reportBtn">Myreport</button>
  <button class="button" id="dataBtn">Mydata</button>
  <div id="mydata">
    <h1>This is my Data</h1>
  </div>
  <div class="chartCard" id="myreport">
    <div class="chartBox">
      <p>Ram</p>
    </div>
    <div class="chartBox">
      <p>Shyam</p>
    </div>
  </div>

</body>

</html>

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

Guide on creating a project for developing an npm package

Within my git root project, I am utilizing a git subproject called UIComponents. For instance, my main project is named MyApp and the subproject is UIComponents. Currently, I have cloned the UIComponents repository inside my project folder and added UIComp ...

Tips for incorporating an outside model into vue.js with babylon js

Struggling with importing a gltf file into vue.js using babylon.js to create a 3D view on a webpage. The documentation online isn't very clear, and I've tried the following steps in my Hello.vue file: <div> <h1> Hello </h1> < ...

Capture Your Scene with Three.js

I am facing an issue where I need to capture a screenshot of a website. I have tried using html2canvas and it is working fine. However, the problem arises because I am using both THREE.WebGLRenderer and THREE.CSS3DRenderer (for HTML in webGL). The screen ...

Highlighting the home page in the navigation menu even when on a subroute such as blog/post in the next.js framework

After creating a navigation component in Next JS and framer-motion to emphasize the current page, I encountered an issue. The problem arises when navigating to a sub route like 'localhost:3000/blog/post', where the home tab remains highlighted i ...

Implementing image change on dropdown selection using jQuery click event

I'm new to Jquery and JavaScript. I have a dropdown in my Keen template that displays 2 flags. I want to be able to click on the dropdown and select the corresponding flag. Most of the examples I found online use the select and options tags, but my co ...

Tips for Uploading Large Images to Backend API in Next.js

As I work on building my portfolio using NextJS, I encountered an issue with the Project Functionality. When converting images to base64 and sending them to an API for uploading on Cloudinary, everything runs smoothly as long as the total size of the req ...

The functionality of resizing a layout in Html5/CSS3 is not functioning correctly

Whenever I resize the window, I am looking to have A B C displayed one after the other in a vertical sequence, I have been struggling with this for quite some time. Can someone please help me figure out how to achieve this? Thank you! A B C div#me ...

Is there a way to align both JSX elements in a single row without having one overlap the other?

Is there a way to showcase both conditions side by side on the same line? If Condition 1 is met, display the images; if Condition 2 is met, show the video. import React, { useState } from "react"; import { Card } from "react-bootstrap" ...

Executing operations on subdocuments in Mongoose without having to fetch the parent

Currently, when I need to delete a subdocument, I follow this process: Post.findById(post_id).exec(function(err, post) { post.comments.remove({'_id': comment_id}); post.save(function(err) { res.end("Success!"); }); }); This method doe ...

Extracting data from websites and importing it into Excel with VBA

I am venturing into the world of web scraping for the first time using VBA. My goal is to extract pricing information from our company's distributors and save it in an Excel file for our sales team to analyze. The process involves taking the URL from ...

Unable to scroll following an ajax request

I am encountering an issue where I need to make an ajax call that populates a DIV and the content becomes as long as 2 web pages. However, I am unable to scroll unless I resize the window. How can I instruct the browser to recalculate the page content size ...

Utilizing Angular's capabilities to smoothly transfer objects between controllers

Currently, I am in the midst of developing an AngularJS application integrated with a C# Web API. I have two controllers: A and B. In controller A, there is a list of objects. When I click "Add" (in between two list items), I am redirected to controller ...

Google Maps fails to load when triggered by the jQuery show() function

One issue I'm facing is that the Google Map is not loading after the show() function is called in jQuery. Initially, I use display:none to close a division on page load. After some research, I found out that it can be resolved by using google.maps.eve ...

Is the validation for the 'prop' property missing in props?

Seeking assistance with react's forwardRef feature. Currently encountering errors related to missing props validation in FadeContents. Is there a way to resolve this issue? It seems like the props need to be defined somewhere in order to be used withi ...

Creating a Stylish CSS Table Utilizing DIV Elements: Preventing the Top Row from Scrolling

Utilizing a pure DIV table with the display: table, table-row, table-cell format for styling, I have managed to make the entire table scroll except for the header row. However, I am in search of methods that can prevent the header row (1st row) from scroll ...

Is there a different method I can utilize to create a conditional statement for assigning a value in JavaScript?

I have this code snippet that seems a bit unclear to me: if (!app.config.admin.examStatusId) { app.config.admin.examStatusId = exam.examStatus.dataPlus[0].id; } Do you have any suggestions on how I could rewrite this more clearly without using an if s ...

What is the impact of sending a JavaScript request to a Rails method every 15 seconds in terms of efficiency?

I have a method that scans for notifications and initiates a js.erb in response. Here is the JavaScript code triggering this method: setInterval(function () { $.ajax({ url: "http://localhost:3000/checkNotification", type: "GET" }); }, 15000); ...

Sending data from Ruby to JavaScript

I'm currently implementing an SMS validation feature on a Sinatra website. Here is the code snippet that I am using: post '/coop/sendcode' do @code = Random.rand(1000..9999).to_s phone = params[:phone].to_s HTTParty.get('http:// ...

Is there a way to accomplish this using Bootstrap?

Hello there! I have a piece of code that is working with both bootstrap and Pixedelic camera. Here it is: <section id="slider" class="container-fluid"> <div class="row fluid"> <div id="camera_wrap_1"> <div data-src="conten ...

What is the best way to handle the return value from using indexOf on a string?

I am looking to manipulate the value returned by a specific conditional statement. {{#each maindata-hold.[2].qa}} <div class="section"> <a href="javascript:void(0)" class="person-link" id="{{id}}"> <span class="name- ...