How to change the background color after clicking the button in JavaScript
In this article, our task is to change the background color of an element whenever a button is clicked.
function changeColor() { document.body.style.background = 'red'; }
There are lot of ways to change the background color of the body element. Among them we can simply use the background property of the style object.
For this, we have the following button element.
<button onclick="changeColor()"> Click Me </button>
Now, we will create the function changeColor() .
<script> function changeColor() { document.body.style.background = 'red'; } </script>
Instead of the above method, we can create a class with some styles. Then, we can add the created class name to the body element.
For this, we have created the following class name.
<style> .add-style{ background-color:red; } </style>
Now, we will use the add() method of the classList property to dynamically add the class name add-style to the body element.
<script> function changeColor() { document.body.classList.add('add-style'); } </script>
To remove an existing class, use the remove() method instead of the add() method.
Change background colour using JQuery. #
In this example, we will use JQuery to change the background colour of the body element.
<script> $('button').on('click', function() { $('body').css('background', '#ff0'); }); </script>
- The on() method is used as event handlers for the selected elements.
- The css() method is used to change/set the CSS property of the element.
save
listen
AI Answer
How to change the background color after clicking the button in JavaScript
0
In this article, our task is to change the background color of an element whenever a butt…
asked
Apu
0 answers
2915
In this article, our task is to change the background color of an element whenever a butt…
Answer Link
answered
Apu