'Notifying/Alerting a user the element is already in use?
I have a bright/white background, and dark/black background. I made a button to switch between them when you click on it. I tried to make an alert or notification when the user click the same button or use the same background. But it seems like the alert is showing up even when the user just clicked on the button. I'll appreciate any replies.
Here is my code:
var x = 2;
function chngBg1() {
document.body.style.backgroundColor = 'white';
var x = 1;
if (x == 1) {
alert('This bg is already in use.');
}
}
function chngBg2() {
document.body.style.backgroundColor = 'black';
var x = 0;
if (x == 0) {
alert('This bg is already in use.');
}
}
body {
background-color: #fff;
}
<body>
<div class="bgbuttons">
<button type="button" onclick="chngBg1()">
White background
</button>
<button type="button" onclick="chngBg2()">
black background
</button>
</div>
</body>
[Note: I used true/false method to do it]
Solution 1:[1]
var x needs to be initialized only once. I have added conditions in both functions that helps solve your problem.
var x = 1;
function chngBg1() {
if (x === 1) {
alert("This bg is already in use.");
} else {
document.body.style.backgroundColor = "white";
x = 1;
}
}
function chngBg2() {
if (x === 0) {
alert("This bg is already in use.");
} else {
document.body.style.backgroundColor = "black";
x = 0;
}
}
body {
background-color: #fff;
}
<body>
<div class="bgbuttons">
<button type="button" onclick="chngBg1()">White background</button>
<button type="button" onclick="chngBg2()">black background</button>
</div>
</body>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mohammad Abdul Alim |
