skip to Main Content

how to background button color change onclick and unclick

i tried to change the button color on onclick and unclick but not work

i tried to change the button color on onclick and unclick but not work

anyone help on this how to change button color onclick and unclick

2

Answers


  1. To change the background color of a button on click and unclick, you can add event listeners to the button using JavaScript and change its background color using the style.backgroundColor property. Here is an example that changes the background color of a button to red on click and back to its default color on unclick:

    const button = document.querySelector('#myButton');
    const defaultColor = button.style.backgroundColor;
    
    button.addEventListener('click', () => {
      button.style.backgroundColor = 'red';
    });
    
    button.addEventListener('mouseup', () => {
      button.style.backgroundColor = defaultColor;
    });
    

    In this example, you first select the button using querySelector(). Then you define a variable defaultColor to store its initial background color. Next, you add an event listener for the click event which changes its background color to red. Finally, you add an event listener for the mouseup event which changes its background color back to the default color. You can change the colors and event types in this example to suit your needs.

    Login or Signup to reply.
    1. Set up local state to be either true or false.
    2. Set up a handler to toggle the state between true and false.
    3. Using state determine what the background colour should be. Here I’ve used a conditional/ternary operator in the className attribute to switch between a blue and red class.

    The implementation details of this may differ from your use-case because you may be using CSS modules or styled components, for example, but it will generally follow this pattern.

    const { useState } = React;
    
    function Button() {
    
      // Initialise local state
      const [ clicked, setClicked ] = useState(false);
    
      // Toggle the state between true/false
      function handleClick() {
        setClicked(prev => !prev);
      }
    
      // Use a conditional operator to choose what
      // colour to render based on the state
      return (
        <button
          className={clicked ? 'red' : 'blue'}
          onClick={handleClick}
        >Click me
        </button>
      );
    
    }
    
    ReactDOM.render(
      <Button />,
      document.getElementById('react')
    );
    .red { background-color: red; }
    .blue { background-color: blue; }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
    <div id="react"></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search