Reputation: 2166
I just write some JS code for click listener, if a button is clicked more than 5 times in 3 seconds then alert will say you wan otherwise you lost. But I am getting every time YOU LOST!!
<head>
</head>
<body>
<button>Click!!</button>
<script>
let counter =0;
document.querySelector('button').addEventListener('Click', () => {
counter++;
});
setTimeout(() => {
if(counter > 5) {
alert('You Won!!' + counter);
} else {
alert('You Lost!!' + counter);
}
},3000)
</script>
</body>
Upvotes: 0
Views: 151
Reputation: 10627
You should use external JavaScript and CSS, for caching reasons, but I think you want to see this:
function lameGame(clickElement){
let c = 0;
setTimeout(() => {
if(c > 5) {
alert('You Won!!' + c); // never use alert in real world
}
else{
alert('You Lost!!' + c); // never use alert in real world
}
lameGame(clickElement);
}, 3000);
clickElement.onclick = function(){
c++;
}
}
lameGame(document.querySelector('button'));
Upvotes: 0
Reputation: 8166
This works fine, Working Demo
I changed "Click" to "click", small case only.
addEventListener('click', () => {})
Might want to check out : JavaScript event listeners are case sensitive.
<button>Click!!</button>
<script>
let counter =0;
document.querySelector('button').addEventListener('click', () => {
counter++;
});
setTimeout(() => {
if(counter > 5) {
alert('You Won!!' + counter);
} else {
alert('You Lost!!' + counter);
}
},3000)
</script>
Result :
LOST :
WON :
Upvotes: 0
Reputation: 564
Minor change on your source code. Now working fine.
let counter =0;
document.querySelector('button').addEventListener('click', () =>counter++);
setTimeout(() => {
if(counter > 5) {
alert('You Won!!' + counter);
} else {
alert('You Lost!!' + counter);
}
},3000)
.col {
float: left;
width: 20%;
}
.row {
width: 100%;
clear:both;
display:block;
}
<button>Click!!</button>
Upvotes: 1
Reputation: 31
you may use lowercase 'click' not 'Click', you didn't call your click event anytime in your sample code.
https://developer.mozilla.org/en-US/docs/Web/Events/click
Upvotes: 1
Reputation: 6737
I updated your code, two things I noticed were you used an uppercase for your click event:
addEventListener('Click'
and I also changed the if to alert 'you won' if counter was greater than or equal to 5
if(counter >= 5)
Here's a working fiddle
http://jsfiddle.net/fkvvc1f0/1/
Upvotes: 0