Using JavaScript to switch the classes of buttons and elements

Hey there!

I received this code from a friend who was trying to modify the switch buttons. I made some changes so that each button can now change the state of two separate elements when pressed. Here's the altered code:

function toggleClass(ev){
  var el = document.querySelector(".pressed");
  var fro = document.querySelector(".visible"); <--line added
  el.className = 'notpressed';
  ev.target.className = 'pressed';

  fro.className = 'notvisible'; <--line added
  ev.target.className = 'visible'; <--line added
}

span{
  cursor:pointer;
  padding:10px;
  border:1px solid #FCFCFC;
}
.notpressed{
  background:#CCC;
}
.pressed{
  background: #DFF789;
}
.visible{
  display:block;
}
.notvisible{
  display: none;
}

<span id="but1" class="pressed" onclick="toggleClass(event);">BUTTON 1</span>
<span id="but2" class="notpressed" onclick="toggleClass(event);">BUTTON 2</span>

<div id="elem1">hello<div>
<div id="elem2">bye<div>

However, I'm facing an issue as it's not working as expected. Can you help me figure out what I'm missing?

Thanks in advance!

Answer №1

Make sure to properly close all of your div tags. Here is a suggested way to structure your code:

//initial setup
document.getElementById('elem2').className = 'notvisible';
document.getElementById('elem1').className = 'visible';
//on change
function toggleClass(ev){
  var fro = document.querySelector(".visible");
  var fro2 = document.querySelector(".notvisible");
  if(ev.target.id == 'but1'){
document.getElementById('elem2').className = 'notvisible';
document.getElementById('elem1').className = 'visible';
ev.target.className = 'pressed';
document.getElementById('but2').className = 'notpressed';
  }
  else if(ev.target.id == 'but2'){
document.getElementById('elem1').className = 'notvisible'; 
document.getElementById('elem2').className = 'visible';
ev.target.className = 'pressed';
document.getElementById('but1').className = 'notpressed';
  }
}
span{
  cursor:pointer;
  padding:10px;
  border:1px solid #FCFCFC;
}
.notpressed{
  background:#CCC;
}
.pressed{
  background: #DFF789;
}
.visible{
  display:block;
}
.notvisible{
  display: none;
}
<span id="but1" class="pressed" onclick="toggleClass(event);">BUTTON 1</span>
<span id="but2" class="notpressed" onclick="toggleClass(event);">BUTTON 2</span>



<div id="elem1" class="visible">hello</div>
<div id="elem2" class="notvisible">bye</div>

Answer №2

Within your toggle class method, you are assigning the 'visible' class to the button that was clicked. It appears that you intend to assign this class to either #elem1 or #elem2.

Furthermore, you must establish a method to link the button element with the corresponding div that should be toggled.

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

Is there a way to add a scrollbar to the ChartJS tooltip to avoid data

I'm currently working on a chartJS project where I have a callback function to display data in tooltips. However, as the data increases, the overflow section of the tooltip gets hidden from the canvas. Is there a solution to prevent this overflow and ...

The typescript error TS2339 is triggered by the property 'webkitURL' not being found on the 'Window' type

Currently utilizing Angular 2 in a project that is compiled with TypeScript. Encountering an issue when attempting to generate a blob image: Error TS2339: Property 'webkitURL' does not exist on type 'Window' The TypeScript code causi ...

When a barcode scanner is used, it will trigger a "keypress" event only if the user is currently focused on an input box. Is there a specific event to monitor when the user is not on an input

Scenario: In the development of my web application, I am utilizing a barcode scanner device that allows users to scan barcodes for navigation to specific pages. Challenge: The current barcode scanning device is set up to only trigger "keypress" events w ...

How can you extract path information from an SVG file and utilize it as a marker on Google Maps?

I want to implement a custom SVG icon as a marker on Google Maps. I have obtained this SVG file: <svg xmlns="http://www.w3.org/2000/svg" width="510px" height="510px" viewBox="0 0 510 510"> <g stroke="black" stroke-width="10" ...

Removing a session when the client has left

I wanted to simplify what I'm trying to achieve. Imagine two people have PHP sessions on a webpage. One person leaves the page while the other remains. After 60 seconds, the session of the person who left should be terminated automatically (like a ti ...

Why is my background image also rotating when I rotate the text using 'transform: rotate'?

I have been attempting to rotate text on a background-image, but I am facing an issue where my background image also moves with the text rotation. Can someone explain why this is happening? Below is the code snippet: HTML code snippet: <ul> <li ...

Could someone provide me with guidance on how to troubleshoot this error message?

[0] Unhandled rejection MongoError: (Unauthorized) not authorized on admin to execute command { listIndexes: "sessions", cursor: { } } [0] at MongoError.create (/Users/biggahd/Desktop/Mars-EMS-1/backend/node_modules/mongodb-core/lib/error.j ...

Code not functioning properly in Internet Explorer

In one of my JavaScript functions, I have the following CSS line which works well in all browsers except for IE (Internet Explorer). When the page loads, the height of the element is only about 4px. element.setAttribute('style', "height: 15px;") ...

How can I change the text of a single button by clicking on it without affecting the other buttons that share the same

Currently, I am implementing a posting system where posts can be added using a button. The posts have two additional buttons - one to show/hide content and the other to delete content. I am utilizing jQuery's slideToggle event to toggle the visibility ...

"Enhance your networking capabilities with a Node.js HTTP proxy featuring a dynamic proxy

I'm attempting to make websockets function properly with node-http-proxy. The unique aspect is that I am using a proxy table configuration: var options = { router: { 'a.websterten.com': '127.0.0.1:150', 'b.websterten. ...

What is the best way to group Angular $http.get() requests for efficiency?

My challenge involves a controller that must retrieve two distinct REST resources to populate two dropdowns. I want to ensure that neither dropdown is populated until both $http.get() calls have completed, so that the options are displayed simultaneously r ...

NodeJS - Retrieving files from Google Drive

Here is a code snippet that I'm using to download files from Google Drive: function downloadDrive(fileId, callback) { var fileExt = fileId.split("."); var file = Date.now() + "." + fileExt[fileExt.length - 1]; var dest = fs.createWriteStream(". ...

JavaScript - issue with event relatedTarget not functioning properly when using onClick

I encountered an issue while using event.relatedTarget for onClick events, as it gives an error, but surprisingly works fine for onMouseout. Below is the code snippet causing the problem: <html> <head> <style type="text/css"> ...

What is the best way to iterate through an ID using jQuery?

After pulling the list of doctors in my area from the database and displaying it on my webpage, I now want to load each doctor's "About" content inside a Bootstrap modal. I added an "about" column within the same database table where the doctors' ...

A single column in Bootstrap displaying text vertically

Looking to rotate the "VERTICAL_TEXT" (third bootstrap column) by 90 degrees, I attempted the code below: <div class="row"> <div class="col-xs-2" style="background-color: yellow;"> <span>FOO1</span><br/> & ...

I'm struggling to update a value in my view with Angularjs and Socket.io. It seems impossible to

In order to master AngularJS and NodeJS, I am embarking on creating a chatroom project. Everything seems to be functioning smoothly with Angular controllers and sending data to my NodeJS server using socket.io. However, I have encountered a problem: When m ...

Leveraging environmental variables in a Vue.js web application

The article I recently came across discussed how to effectively utilize environment variables in vuejs. Following the instructions, I set up my local .env.local file and also installed dotenv. VUE_APP_AUTH_AUTHORITY = 'http://localhost/auth' I ...

Creating a dynamic input box with an add/remove button in each row using jQuery

Need help with a jQuery-based UI that allows users to dynamically add input boxes. The desired look is as follows: Default appearance: INPUT_BOX [ADD_BUTTON] [REMOVE_BUTTON] Clicking on the [Add_Button] should add another row like this, and so on: ...

How can you insert a title or key into an array containing numerous objects using javascript?

I have a function that extracts data from files and returns it in an array const extractTestCases = () => { const filesArray = [] const filterTestSuite = files.filter(test => test.includes('.test.ts')) filterTestSuite.forEach(te ...

What steps should I take to delete a class from my calendar after it has reached the maximum capacity of 20

I am trying to create a feature that automatically removes a class from the calendar if more than 20 people have booked it. On the admin side of the system, I can add classes to the database but need help implementing this check. Below is my current code ...