I need a button which can change the background color if you click it 2x. How can I do this?, I only know how to do it with 1 click. My code is actually this:
<button onClick="document.body.style.backgroundColor ='#000';"> color </button>
CodePudding user response:
Use onDblClick
instead:
<button onDblClick="document.body.style.backgroundColor ='#000';"> color </button>
CodePudding user response:
You can store the number of clicks in a variable and add a click
event listener to the button that increments the counter and checks whether it is 2
, and if so, sets the background color of the body.
var clicks = 0;
btn.addEventListener('click', function(){
if( clicks == 2){
document.body.style.backgroundColor ='#000';
}
})
<button id="btn"> color </button>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Similar to the response of @Spectric, store the number of clicks in a variable and add a click event listener to the button.
I don't know logic is what is desired.
You could add another button with an idea equal to the one placed, but in reverse: subtracting.
const btnEle = document.querySelector(".btn");
const resEle = document.querySelector(".result");
const legendEle = document.querySelector("#legend");
let clickCount = 0;
btnEle.addEventListener("click", () => {
clickCount ;
resEle.innerHTML = "The button has been clicked " clickCount " times ";
if (clickCount > 1) {
document.body.style.backgroundColor ='#000';
legendEle.style.color = '#1E5128';
}
});
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result {
font-size: 18px;
font-weight: 500;
color: blueviolet;
}
<div class="result"></div>
<br />
<button class="btn">CLICK HERE</button>
<h3 id="legend">Click on the above button to check if the button is clicked</h3>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
in HTML
<input type="button" id="btn" onclick="eventB()">
in JS
function eventB() {
var click = 0;
btn.addEventListner('click', function() {
if( click == 2){
window.document.body.style.background = '##836fff';
}
})