Deactivate the button upon click using alternative methods besides the disable attribute

I am trying to implement functionality with 3 buttons: 'click me', 'disable', and 'enable'. When the 'click me' button is clicked, it triggers an alert. However, when the 'disable' button is clicked, it should disable the 'click me' button and change its background color. Similarly, clicking the 'enable' button should enable the 'click me' button and revert the background color back to its original state. I want to achieve this without using the 'disabled' attribute.

To get a better understanding of what I am aiming for, please refer to this GIF:

Although I attempted to use pointercancel, it did not produce the desired results.

function disableButton() {
  var a = document.getElementById('clickme');
  a.addEventListener("pointercancel", function() {})
}

function enableButton() {
  var b = document.getElementById('clickme');
  b.addEventListener("pointerover", function() {
    b.style.backgroundColor = '#E2343F';
  })
}
<div class="container">
  <button id="clickme">Click Me</button>
  <div class="">
    <button onclick="disableButton()" class="disable">Disable Button</button>
    <button onclick="enableButton()" class="enable">Enable Button</button>
  </div>
</div>

In addition, I am looking for a way to toggle the ID in order to change the CSS values accordingly.

If someone could assist me in resolving this issue, it would be greatly appreciated.

Answer №1

Here is a simple solution that should do the trick:

.no-click {
    pointer-events: none;
}

To implement this, just apply the "no-click" class to your desired element in your user interface:

<button class="no-click">

UPDATE: If you prefer to toggle the functionality rather than simply disabling it:

function disableButton() {
  var button = document.getElementById('clickme');
  button.style.pointerEvents = 'none';
}

function enableButton() {
  var button = document.getElementById('clickme');
  button.style.pointerEvents = '';
  button.addEventListener("pointerover", function() {
    button.style.backgroundColor = '#E2343F';
  })
}

Answer №2

There is a method to control button functionality by utilizing event listeners.

const showAlert = () => alert('Hi');

const addListener = () => {
  const btn = document.querySelector('#clickme');
  clickListener = btn.addEventListener('click', showAlert);
  btn.classList.remove('disabled');
};

document.addEventListener('DOMContentLoaded', () => {
  addListener();
  
});

function disableButton() {
  const btn = document.querySelector('#clickme'); 
  document.querySelector('#clickme').removeEventListener('click', showAlert);
  btn.classList.add('disabled');
}

function enableButton() {
  addListener();
}
button {
  cursor: pointer;
}

#clickme {
  background-color: #E2343F;
}

#clickme.disabled {
  cursor: auto;
  background-color: grey;
}
<div class="container">
  <button id="clickme">Click Me</button>
  <div class="">
    <button onclick="disableButton()" class="disable">Disable Button</button>
    <button onclick="enableButton()" class="enable">Enable Button</button>
  </div>
</div>

Answer №3

Give this a shot...

function deactivateButton() {
  document.getElementById('pressme').disabled = true;
}

function activateButton() {
  document.getElementById('pressme').disabled = false;
}
<div class="wrapper">
  <button id="pressme">Press Me</button>
  <div class="">
    <button onclick="deactivateButton()" class="inactive">Deactivate Button</button>
    <button onclick="activateButton()" class="active">Activate Button</button>
  </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

Responsive Fullscreen Bootstrap Panel with Highcharts

One issue I'm facing is with my (bootstrap) panels that contain Highcharts charts and I want them to show fullscreen without losing their aspect ratio. The problem is that the size of the Highcharts does not adjust when going into full-screen mode. Is ...

Conditionally render a div in React with Next.js depending on the value of a prop

Struggling with an issue in my app and seeking some guidance. The problem arises when dealing with data from contentful that has been passed as props to a component. Specifically, I only want to render a particular piece of data if it actually contains a v ...

Looping through and printing JSON strings

Currently, I am dealing with a JSON string of this specific format: {"prey":["{\"distance\": 8.686924173343307, \"signal\": \"-59\", \"frequency\": 2447, \"mac\": \"00:00:00:00:00:00\", \"ip ...

How to Customize the Size and Color of secureTextEntry Inputs in React Native

When it comes to styling a password input like the one below: <TextInput name="Password" type="password" mode="outline" secureTextEntry={true} style={styles.inputStyle} autoCapitalize="none" autoFocus={true} /> I also ap ...

Emphasize the selected page number

My React application contains page numbers, but currently when a page number is clicked, it does not get highlighted or displayed in a different color. The className "text-success" can be added to make the text green. How can I dynamically add this class t ...

Issue with req.user being Undefined in Node, Express, Passport, and Mongoose

I've encountered an issue where req.user is defined when logging in, but undefined on other paths. I'm starting to feel stuck and out of ideas at this point. Another thing is that deserialization is never being called. server.js: var LocalStra ...

Creating an adaptable grid system in Vue Material

I am working on a project where I am using Vue-Material to display user-inputted cards in a grid layout. While the cards are rendering correctly, I want to optimize the grid to make it flexible, justify the cards, and stagger them in a way that eliminates ...

The combination of $.post and $J = jQuery.noConflict() does not seem to be functioning correctly

I'm struggling with sending data from JavaScript to PHP using the $.post method, while also having conflicts with WordPress and using $J = jQuery.noConflict(). Here's what I have in my JavaScript: $J = jQuery.noConflict() x=1 $J.post('/the ...

Having trouble with d3 / svg layering when introducing new nodes overtime

Struggling with a frustrating issue on my d3 force directed map project. Initially, I render the necessary nodes and links, then periodically check for updates through AJAX. The problem arises when adding new nodes and links – they appear over existing c ...

5 Creative Techniques for Manipulating Boolean Variables in If Statements

I am receiving a unique custom header value and the values I am getting are accurate. The expected values include: true, false, undefined. However, the response associated with the value: false is incorrect. Code Snippet let deviceStatus = req.headers[ ...

Switching back and forth between classes prevents the animation from playing continuously, causing it to jump straight to the end

Currently, I am in the process of animating a hamburger menu with a unique twist. The idea is to have the top and bottom lines smoothly translate to the middle and then elegantly rotate into an X shape when clicked. My approach involves toggling between tw ...

What is the best way to implement function chaining in TypeScript?

I'm interested in implementing function chaining in typescript. Let's consider a sample class: export class NumberOperator { private num; constructor(initialNum) { this.num = initialNum; } public add(inc = 1) { this.num += inc ...

Unable to click a button on HTML file

In my current project, there is a piece of code responsible for checking if the user is logged in or not. If the user hasn't logged in yet, they are redirected to the login page. Once the user logs in successfully, they should be able to upload conten ...

The Express server is set up with CORS enabled, however, it continues to encounter issues when attempting to make asynchronous HTTP requests from

We're currently experiencing an unusual issue and are seeking assistance to resolve it. Initially, our Express server is functioning well as an API when accessed from the same domain. However, we also need to utilize this API on our computers for tes ...

Is JavaScript Gallery Acting Up? Possible Layer Glitch!

Seeking assistance with a website issue. I have an index.php file set up with a sideshow script in the head that appears on all pages. Additionally, within the index.php file, there is a portfolio.html page that displays a gallery script when loaded. The p ...

Unable to cancel $interval within factory

I created a factory for long-polling, complete with start and stop methods. However, I am struggling to cancel the timer. Any suggestions or ideas? app.controller("AuthCtrl", function($scope, $http, $window, User, Poller) { Poller.start(1, $scope.sess ...

JQuery table sorter is unable to effectively sort tables with date range strings

I am facing an issue with sorting a column in my table that contains text with varying dates. The text format is as follows: Requested Statement 7/1/2014 - 9/16/2014 When using tablesorter, the sorting does not work properly for this column. You can see ...

Troubleshooting Intel Edison application update issues

After setting up the IoT XDK, I decided to try out the blink example. Excitedly, I saw that the LED on pin 13 was blinking just as expected! But when I attempted to change the interval from 1000ms to 100ms and 3000ms, there was no difference in the blinkin ...

Is there a way to asynchronously load multiple textures in three.js using a callback function?

Bringing in a single texture with a callback is a simple task, for instance: var loader = new THREE.TextureLoader(); var texture1 = loader.load("https://i.imgur.com/UiTMJzv.png", process); //executed only once texture1 is loaded function process(){ } B ...

Having trouble with the preview feature when resizing images

Before trying to implement the JSFiddle was working correctly: http://jsfiddle.net/qa9m7t33/ However, after attempting to implement it, I encountered some issues: http://jsfiddle.net/z1k538sm/ While trying to resize an image, I realized that this example ...