Script to change button color

 Sure, here is an example JavaScript program to change the color of a button on a webpage:

javascript
// Get a reference to the button element const button = document.querySelector('button'); // Add an event listener to the button that changes its color button.addEventListener('click', () => { button.style.backgroundColor = 'red'; });

In this example, we first use the querySelector method to get a reference to the button element on the page. We then add an event listener to the button using the addEventListener method, which listens for a "click" event on the button.

When the button is clicked, the code inside the event listener function is executed. In this case, we simply set the background color of the button to "red" using the style property.

Of course, you can change "red" to any other valid color value to change the color of the button to your desired color




Certainly! Here is another example of a JavaScript program that changes the color of a button, but this time using a function that takes a color as an argument:

javascript
// Get a reference to the button element const button = document.querySelector('button'); // Define a function to change the color of the button function changeButtonColor(color) { button.style.backgroundColor = color; } // Add an event listener to the button that calls the function with a color argument button.addEventListener('click', () => { changeButtonColor('green'); });

In this example, we define a function called changeButtonColor that takes a color argument. Inside the function, we set the background color of the button to the value of the color argument using the style property.

We then add an event listener to the button that calls the changeButtonColor function with the argument "green" when the button is clicked.

This approach allows you to easily change the color of the button by passing in different color values as arguments to the changeButtonColor function. You could even add additional logic to the function to make the color change more dynamic or based on user input

Comments

Popular posts from this blog

Change Text Dynamically