Steps to eliminate the active state of a button after clicking on an input

I am currently working on a component that consists of 4 preset buttons and a customized range input. The issue I am facing is that while I can toggle the active state on the buttons when they are clicked, I want to remove the active state from all the buttons when I click into the input field. Additionally, I would like the input field to clear out when I click outside of it.

Here is the code snippet:

let btnContainer = document.getElementById("rc-button-bar");
let btns = btnContainer.getElementsByClassName("ce-button");
let input = document.getElementById("customPercent");

for (var i = 0; i < btns.length; i++) {
  btns[i].addEventListener("click", function() {
    (document.querySelector('.is-active')) ? document.querySelector('.is-active').classList.remove('is-active'): '';
    this.classList.add('is-active');
  });
}
.btn-primary.ce-button {
  width: 100%;
  height: 48px;
  padding: auto;
  border: 4px solid #0079c1;
  border-radius: 5px;
  background: transparent;
  color: #0079c1;
  font-weight: bold;
  cursor: pointer;
}

.btn-primary.ce-button:hover,
.btn-primary.ce-button:active {
  background: #0079c1;
  border-radius: 5px;
  color: #ffffff;
  font-weight: bold;
  cursor: pointer !important;
}

.is-active {
  background: #0079c1 !important;
  border-radius: 5px !important;
  color: #ffffff !important;
  font-weight: bold !important;
}
<div class="row selectors d-flex justify-content-center" id="rc-button-bar">
  <div class="col-xs-6 col-sm-6 col-md-2 mb-2">
    <button id="btn-25" class="btn-primary ce-button" data-value="25">25%</button>
  </div>
  <div class="col-xs-6 col-sm-6 col-md-2 mb-2">
    <button id="btn-50" class="btn-primary ce-button" data-value="50">50%</button>
  </div>
  <div class="col-xs-6 col-sm-6 col-md-2 mb-2">
    <button id="btn-85" class="btn-primary ce-button is-active" data-value="85">85%</button>
  </div>
  <div class="col-xs-6 col-sm-6 col-md-2 mb-2">
    <button id="btn-100" class="btn-primary ce-button" data-value="100">100%</button>
  </div>
  <div class="col-sm-12 col-md-2 mb-2 d-flex align-items-center">
    <input id="customPercent" class="numbers" type="text" placeholder="ex: 80"></input>&nbsp;<span>%</span>
  </div>
</div>

Answer №1

It seems that you are not actually toggling the active state of a button, but rather just changing its appearance. However, assuming that was a miscommunication error and you simply want to adjust the style after the button is clicked.

The solution is quite straightforward. You just need to attach a click event listener to the input and have it remove the 'is-active' class from the buttons (if they have it):

input.addEventListener('click', function() { // Handle click event
 for (let a = 0; a < btns.length; a++) { // Loop through buttons
   if (btns[a].classList.contains('is-active')) { // Check for class
     btns[a].classList.remove('is-active'); // Remove the class
    }
  }
})

To clear the input when clicking away from it, simply add a blur event listener that resets its value to an empty string:

input.addEventListener('blur', function() {  // Handle blur event
   input.value = ''; // Clear the input
});

Feel free to run the complete code provided below to confirm that it functions as expected:

// JavaScript implementation
let btnContainer = document.getElementById("rc-button-bar");
let btns = btnContainer.querySelectorAll(".ce-button");
let input = document.getElementById("customPercent");

for (var i = 0; i < btns.length; i++) {
  btns[i].addEventListener("click", function() {
    (document.querySelector('.is-active')) ? document.querySelector('.is-active').classList.remove('is-active'): '';
    this.classList.add('is-active');
  });
}

input.addEventListener('click', function() {
  for (let a = 0; a < btns.length; a++) {
    if (btns[a].classList.contains('is-active')) {
      btns[a].classList.remove('is-active');
    }
  }
})

input.addEventListener('blur', function() {
  input.value = '';
});
// CSS styling
.btn-primary.ce-button {
  width: 100%;
  height: 48px;
  padding: auto;
  border: 4px solid #0079c1;
  border-radius: 5px;
  background: transparent;
  color: #0079c1;
  font-weight: bold;
  cursor: pointer;
}

.btn-primary.ce-button:hover,

.btn-primary.ce-button:active {
  background: #0079c1;
  border-radius: 5px;
  color: #ffffff;
  font-weight: bold;
  cursor: pointer !important;
}

.is-active {
  background: #0079c1 !important;
  border-radius: 5px !important;
  color: #ffffff !important;
  font-weight: bold !important;
}
// HTML structure
<div class="row selectors d-flex justify-content-center" id="rc-button-bar">
  <div class="col-xs-6 col-sm-6 col-md-2 mb-2">
    <button id="btn-25" class="btn-primary ce-button" data-value="25">25%</button>
  </div>
  <div class="col-xs-6 col-sm-6 col-md-2 mb-2">
    <button id="btn-50" class="btn-primary ce-button" data-value="50">50%</button>
  </div>
  <div class="col-xs-6 col-sm-6 col-md-2 mb-2">
    <button id="btn-85" class="btn-primary ce-button is-active" data-value="85">85%</button>
  </div>
  <div class="col-xs-6 col-sm-6 col-md-2 mb-2">
    <button id="btn-100" class="btn-primary ce-button" data-value="100">100%</button>
  </div>
  <div class="col-sm-12 col-md-2 mb-2 d-flex align-items-center">
    <input id="customPercent" class="numbers" type="text" placeholder="ex: 80"></input>&nbsp;<span>%</span>
  </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

What is the correct way to integrate HTML input elements into JavaScript code without encountering a type error?

I'm having some trouble with this code snippet. It's my first time coding and I can't figure out what's causing the issue. The error message I'm receiving is: "TypeError: Cannot read properties of null (reading 'value&ap ...

There seems to be an issue with byRole as it is failing to return

Currently in the process of migrating my unit test cases from Jest and Enzyme to React Testing Library. I am working with Material UI's Select component and need to trigger the mouseDown event on the corresponding div to open the dropdown. In my previ ...

JavaScript Nested Array Looping Script

I am currently working on a loop script for my application that checks for the full capacity of a user array and adds a user ID if there is space available. The data in my JSON file is structured around MongoDB and contains 24 entries (hours). Each entry ...

What is the best way to create a global variable using jQuery?

Is it possible to pass the value of a_href = $(this).attr('href'); function globally and set a_href as "home"? var a_href; $('click a').on('hover', function(e){ a_href = $(this).attr('href'); ...

The effectiveness of the javascript widget is hindered by the absence of the meta viewport tag,

As I work on creating a widget to appear at the bottom of webpages, I've encountered a styling issue. The widget's display varies based on whether the webpage includes a specified meta viewport tag or not. <meta name="viewport" content="width ...

What is the best way to change a date-containing string into a Json object?

I need to convert a string into a JSON Object using JavaScript. However, when I do so, the date in the original string gets completely changed. Here is the string I am working with: var JsonData=[[2013-02-27,787],[2013-02-26,131],[2013-02-02,0],[2013-01- ...

Updating the background image without having to validate the cache

I have implemented a basic image slideshow on my website using a simple Javascript function. The function runs every 5 seconds to update the CSS "background-image" property of a div element. While it is functional, I've noticed that each time the func ...

The functionality of the handleTextShow function in components>DrinkList.js is not working as expected after integrating an API

While working on my react program, I created a DrinkList.js file to display images of drinks. However, when I attempted to make the images clickable by adding an Onclick function to display their names in the console, errors started flooding in. import Rea ...

The value returned when using $.css('transform') is incorrect and displays as "rotate"

Possible Duplicate: Retrieve -moz-transform:rotate value using jQuery Firefox 15 - Chrome: $('#img2').css('transform'); return => "rotate(90deg)" Firefox 16 $('#img2').css('transform'); return => mat ...

Issue with spacing dropdown choices within primary navigation bar

Struggling with my final project for a class as the semester comes to a close. I've received minimal help from my Professor and hit a roadblock. The main navigation on the side is working correctly, but the dropdown options are stacking on top of each ...

Issue with clicking a button in Selenium using JavaScript for automation

I'm encountering an issue where Selenium is detecting an element as disabled, despite it being enabled. To work around this, I am attempting to click on the element using JavaScript with the following code snippet: IWebElement button = driver.FindEl ...

Having trouble using the search feature on ngx-mat-select-search for typing?

I am experiencing an issue with searching while using ngx-mat-select-search. I am able to display the options, but when I try to type in a search query, nothing appears on the screen. Can anyone provide assistance? Below is the code snippet: <div *ng ...

Is there a way to specify the dimensions of the canvas in my image editing software based on the user-input

Here is the code and link for my unique image editor. I would like to allow users to enter the desired width and height of the selection area. For example, if a user enters a width of 300 and height of 200, the selection size will adjust accordingly. Addit ...

JavaScript doesn't automatically redirect after receiving a response

Hey there, I'm attempting to implement a redirect upon receiving a response from an ajax request. However, it seems that the windows.href.location doesn't execute the redirect until the PHP background process finishes processing. Check out my cod ...

Incorporating the power of ES6 into a pre-existing website using React

I currently have an established website with a page accessible through the URL www.example.com/apps/myApp. The myApp functionality is embedded within an existing HTML page and serves as a utility app. I am interested in learning React, so I see this as a g ...

Determine the worth of various object attributes and delete them from the list

Currently, my dataset is structured like this: { roof: 'black', door: 'white', windows: 8 }, { roof: 'red', door: 'green', windows: 2 }, { roof: 'black', door: 'green', windows: ...

Optimal approach for managing numerous modals containing map data in Next.js

Hey there, I'm facing an issue while trying to utilize map data in conjunction with modals. Although I have set the state for all modals, when I use an array object within the map data, the modals end up showing duplicated. To provide clarity, let me ...

What is the method for opening the image gallery in a Progressive Web App (PWA)?

I am struggling to figure out how to access the image gallery from a Progressive Web App (PWA). The PWA allows me to take pictures and upload them on a desktop, but when it comes to a mobile device, I can only access the camera to take photos. I have tried ...

What is the best way to retrieve an <a> tag element using Selenium in Python?

I am fairly new to using Selenium and could use some guidance with the following issue. I am attempting to create a birthday bot for Facebook, but navigating through the platform's latest UI has been challenging with JavaScript disabled. I've bee ...

React hooks causing the for loop to only work on the second iteration

I am working on a project where I need to implement tags, similar to what you see on this website. Before adding a tag, I want to ensure that it hasn't already been selected by the user. I have set up a for loop to compare the new tag with the existin ...