Steps to altering the color of a second button with a button click

My goal is to create a button click function that allows only one button to be clicked at a time. For instance, when btn1 is clicked, its background color changes from transparent to green. Then, if btn2 is clicked, btn1's background color should change from green to red, and btn2's background color should become transparent. Additionally, I want to implement a toggle feature for both buttons.

function myFunction(str) {

 var element = document.getElementById("btn1");
 var element1 = document.getElementById("btn2");

   if(str==1){

   document.getElementById("btn2").style.backgroundColor ="";
   element.classList.toggle("mystyle");

    }else{

   element1.classList.toggle("mystyle1");
   document.getElementById("btn1").style.backgroundColor ="";

    }

}
.mystyle {
          background-color: green;
          color: white;
}
.mystyle1 { 
          background-color: red;
          color: white;
}
<button class="" id="btn1" onclick="myFunction(1)">Upvote </button>
<button  class=""id="btn2" onclick="myFunction(-1)">Down Vote</button>

Answer №1

To remove a class from an element, you can utilize the element.classList.remove() method.

function myFunction(str) {

 var element = document.getElementById("btn1");
 var element1 = document.getElementById("btn2");

   if(str==1){

   element1.classList.remove("mystyle1");
   element.classList.toggle("mystyle");

    }else{

   element1.classList.toggle("mystyle1");
   element.classList.remove("mystyle");

    }

}
.mystyle {
          background-color: green;
          color: white;
}
.mystyle1 { 
          background-color: red;
          color: white;
}
<button class="" id="btn1" onclick="myFunction(1)">Upvote </button>
<button  class=""id="btn2" onclick="myFunction(-1)">Down Vote</button>

Answer №2

By using jQuery's toggleClass, you can create a neat solution for dynamically altering the background color of buttons.

var btnUp = $('#btn-up');
var btnDown = $('#btn-down');

btnUp.click(function() {
  $(this).toggleClass('btn-green');
  btnDown.removeClass('btn-red');
});

btnDown.click(function() {
  $(this).toggleClass('btn-red');
  btnUp.removeClass('btn-green');
});
.btn {
  background-color: transparent;
}

.btn-green {
  background-color: green;
}

.btn-red {
  background-color: red;
}
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<button id="btn-up" class="btn">Up Vote</button>
<button id="btn-down" class="btn">Down Vote</button>

Answer №3

Upon reviewing your code, I have made some modifications to your JavaScript function to meet your desired outcome:

function updateStyle(str) {
         var element = document.getElementById("btn1");
         var element2 = document.getElementById("btn2");
            
           if(str === 1){
               element.classList.toggle("mystyle");
               element2.className = '';
            } else{
               element2.classList.toggle("mystyle1");
               element.className = '';  
            }
        }

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

Please note: With React 18, the use of ReactDOM.render is no longer supported. Instead, we recommend using create

I encountered an issue while attempting to link my React application with a MongoDB database. Here is the code snippet where the problem occurred: //index.js ReactDOM.render( <React.StrictMode> <BrowserRouter> <App /> &l ...

Show a notification when utilizing AJAX requests

I consist of two separate files: one written in PHP and the other one in JavaScript and HTML. PHP file : <?php session_start(); //start session $_SESSION['data'] = "The content should be displayed as alert in the JS file"; JS/HTML File: & ...

Ways to send users to a different page with parameters without relying on cookies

Is there a way to redirect users from URLs containing parameters like /?v=xxx to the index page without those parameters showing in the address bar? I still need to retain and use these parameters internally. One approach I considered was using custom hea ...

Customizing animations for birds

I'm currently in the process of developing a new website. The link to access the site is: One thing I am eager to achieve is having birds from this specific link incorporated into my background: I have attempted various methods without success. If a ...

The <a> tag is failing to cover the appropriate section of the <div> element

I am facing the following issue: HTML: <div id="about" class="menu1"> <a href="#">About</a></div> <div id="aboutsub"> <div id="team" class="menu2"> <a href="">Team</a></div> &l ...

An error occurred while the server was processing the request during an Ajax POST operation

My jQuery Mobile app communicates with a WCF REST service, and most of the calls to the service are GETs. However, one particular function uses a POST request with JSON data. While the POST request works perfectly on our development servers, it fails to w ...

"Attempting to dynamically include Components for SSR bundle in React can result in the error message 'Functions are invalid as a React child'. Be cautious of this

When working with my express route, I encountered an issue trying to pass a component for use in a render function that handles Server-Side Rendering (SSR). Express Route: import SettingsConnected from '../../../client/components/settings/settings-c ...

What's preventing me from tapping on hyperlinks on my mobile device?

I'm currently working on a website (saulesinterjerai.lt) and everything seems to be functioning properly, except for the fact that on mobile devices, the links aren't clickable and instead navigates to other layers. How can I disable this behavio ...

Sending both an array and an image via Ajax in a single request

I need to send both JSON and file data to my PHP backend using an ajax call. Here is my current ajax call: $.ajax({ type: 'POST', dataType: 'json', data: jsonData, url: 'xxx.php', cache: false, suc ...

Ways to display pictures by invoking an API within the antd item list container

Upon page load, I am fetching images from a database using an API. Now, my goal is to display these images within a Modal in Antd. How can I accomplish this with the code snippet below? const MyVehiclePage = (props) => { useEffect(() => { co ...

"Proper Installation of Angular Project Dependencies: A Step-by-Step

Whenever I clone an Angular project with older versions that are missing the node_modules folder, and then run npm install to install all necessary dependencies, I end up receiving numerous warnings and errors related to version mismatches. Here are some ...

Node.js module loader compared to client-side AMD loader such as RequireJS

Today, let's talk about loading Javascript modules on the client-side. There are two popular ways to do this: Using RequireJS Utilizing NPM (Node Package Manager) for exporting and requiring files I've always found the first option to work wel ...

When first accessing the page, the map may not load properly. However, a simple refresh of the page in VueJS should resolve this issue and allow the

After initially loading the page, the map may not work properly in Vue.js. However, refreshing the page fixes this issue. Can anyone provide assistance with this problem? Here is the relevant code: mounted() { this.geolocate(); }, methods: { ...

Tips for incorporating dynamic parameters/variables into templates displayed using ng-bind-html or a custom directive (within ng-repeat)

EDIT: I have created a solution sample based on the initial answer. However, I am open to further suggestions and would appreciate any help in filling the gaps in my knowledge (please refer to the comments). plnkr.co/edit/mqGCaBHptlbafR0Ue17j?p=preview OR ...

Assign a value to a HubSpot hidden form field by utilizing Javascript

I have a snippet of JavaScript code placed in the head section of my website: <!-- Form ID Setter --> <script> document.querySelector('input[name=form_submission_id]').value = new Date(); </script> My objective is to automat ...

Does the server transmit HTML page content rather than the information you need?

My React application is connected to a backend built with Node.js. However, when I try to fetch data in my React component, the server sends back an HTML page instead of the expected data, displaying raw HTML on the screen. Backend (server.js): app.route ...

Automatically fill in input fields in a form by selecting options from a dropdown menu and extracting data

After executing a MySQL query, a select dropdown menu is populated with data like this: <form method="post" action="action.php"> <select name="elements" id="elements"> <option type="text" value="">Select an element to be modifie ...

Create a specialized angular controller

Is there a way to create a custom controller programmatically while preserving scope inheritance? I am looking to achieve something similar to this: var controller = 'myCtrl'; var html = '<p>{{value}}</p>'; var validScope= ...

Is Intellisense within HTML not available in SvelteKit when using TypeScript?

Having trouble with intellisense inside HTML for a simple page component. Also, renaming properties breaks the code instead of updating references. Typescript version: 4.8.4 Below is the code snippet: <script lang="ts"> import type { Bl ...

Having trouble capturing screenshots with PuppeteerJS?

I've encountered an issue while working with Puppeteer to capture screenshots from a provided URL. The code I have below doesn't seem to be functioning properly. It keeps showing the error message: [0] Error: Protocol error (Emulation.setDeviceM ...