Button Click Event not working - javascript

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>

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

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>

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/

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 :

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'));

Related

Why is the mousedown event being fired after click instead of during?

I have a div class "guessed" and have a timer to detect whether a short press and long press. When testing, the console logs "MOUSEDOWN" after the press instead of on the press.
The console also logs "SHORT PRESS" even if it's held for longer than 2 seconds.
I've tested the code on JSFiddle and it's working fine. However within my website, the code doesn't work. Can anyone spot the error? Many thanks
var timer = 0;
var timerInterval;
$(document).on('mousedown', '.guessed', function() {
console.log("MOUSEDOWN");
timerInterval = setInterval(function() {
timer += 1;
}, 300);
});
$(document).on('mouseup', '.guessed', function() {
if (timer < 1) {
console.log("SHORT PRESS");
clearInterval(timerInterval);
timer = 0;
return;
}
console.log("LONG PRESS");
clearInterval(timerInterval);
timer = 0;
});
.guessed { border:1px solid red; width:100px; height:100px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='guessed'>mouse me</div>
You can simply use html attributes for mouseup and mousedown events and call custom defined JavaScript functions just like in the following example :
var timer = 0,timerInterval;
function mousedownfunction() {
console.log("MOUSE DOWN");
timerInterval = setInterval(function() {
timer += 1;
}, 300);
}
function mouseupfunction() {
console.log("MOUSE UP");
if (timer < 1) {
console.log("SHORT PRESS");
clearInterval(timerInterval);
timer = 0;
return;
} else {
console.log("LONG PRESS");
clearInterval(timerInterval);
timer = 0;
return;
}
}
<div class="guessed" onmousedown="mousedownfunction()" onmouseup="mouseupfunction()">
<p>Mouse</p>
</div>

Why doesn't my if statement respond to the changes I made to the variables?

var count = 0;
if(count % 2 == 0) {
for (let i = 0; i < squareStorage.length; i++) {
squareStorage[i].addEventListener("click", function() {
console.log("This is: " + i)
console.log(count%2)
count++;
console.log(count);
});
}
}
else if(count % 2 == 1) {
console.log(count%2)
for (let i = 0; i < squareStorage.length; i++) {
squareStorage[i].addEventListener("click", function() {
console.log("This is (no.2): " + i)
count++;
console.log(count);
}, false);
}
}
Those are part of my code. I wanted the variable count to change as I click on a bunch of divs which I threw into the squareStorage variable. I tried by increasing variable count whenever I click. However, my if statement somehow keeps on running, even when count % 2 is not 0.
Its a common mistake, you need to add your events seperately and then in the event call the code.
Here is example.
let count = 0;
// This method will deal with the logic on each click.
// NOTE: we are not re-doing our events.
const processClick = () => {
if(count%2 == 0) {
console.log(`This is one: count ${count}`);
} else {
console.log(`This is two: count ${count}`);
}
count++;
};
// When document loads we will find all divs and add a click event.
document.addEventListener('DOMContentLoaded', () => {
// Find all our DIV elements and add a click event to them.
document.querySelectorAll('div')
.forEach(div => div.addEventListener('click', processClick));
});
<div>Click</div>
<div>Click</div>
<div>Click</div>
<div>Click</div>
<div>Click</div>
I think you've forgotten to remove the old event listeners which you can do with removeEventListener.
eg:
function myClickFunction {
// ... do stuff for first click function
}
// when loading the 2nd click function you run this
squareStorage[i].removeEventListener('click', myClickFunction)

If Statement not registering in JavaScript

I can't figure out why these if statements aren't working. I have tried setting the second one to else if as well and it's still not working.
Basically I want to the code to add 1 to the count variable whenever a button is pressed. The problem is that even though the count++ is working, the if statements aren't registering and I can just keep playing around in the if (count== 0) section.
var player = "X";
var comp = "O";
var count = 0;
console.log(count);
//Code for turn 1
if (count == 0) {
//Code for Div 1
$("#1").one("click", function(){
console.log("hit")
count++;
console.log(count)
if ( $('#1').children().length == 0 ){
$("#1").append("<p>" + player + "</p>");
$("#5").append("<p>" + comp + "</p>");
}
else {
console.log("full");
}
});
//Code for Div 2
$("#2").one("click", function(){
console.log("hit")
count++;
console.log(count);
if ( $('#2').children().length == 0 ){
$("#2").append("<p>" + player + "</p>");
$("#5").append("<p>" + comp + "</p>");
}
else {
console.log("full");
}
});
if (count == 1){
$("#2").one("click", function(){
count++;
if ( $('#2').children().length == 0 ){
$("#2").append("<p>" + player + "</p>");
$("#3").append("<p>" + comp + "</p>");
}
else {
console.log("full");
}
})
console.log(count);};
Any logic that needs to be executed on each click must be triggered by that click. Right now, the ifs at the top level are only run once, not in response to clicks.
You're using $("#1").one, which by definition only works once:
Description: Attach a handler to an event for the elements. The
handler is executed at most once per element per event type. (source)
Change all .one's to .on.

JavaScript Alert Box Popup Issue

I am having an issue with an Alert Box not appearing on the screen after I click a submit button. I have searched this forum and online for answers and I don't see what is wrong with my code. As with most of my issues, the solution is probably a simple fix but I can't seem to find the issue after going through my code. Any help is appreciated.
javascript code
<script type="text/javascript">
function stopClock() {
clearInterval (clockId);
correctAns = gradeQuiz();
alert('You have' + correctAns + 'correct of 5 in' + timer + 'seconds');
}
</script>
<script type="text/javascript">
function runClock() {
seconds++;
document.getElementById('quizclock').value=seconds;
}
</script>
<script type="text/javascript">
function startClock() {
showQuiz();
clockId=setInterval ("runClock()", 1000);
}
</script>
function resetQuiz() {
document.quiz.quizclock.value = 0;
for (i=0; i<document.quiz.elements.length; i++)document.quiz.elements[i].disabled=false;
document.quiz.stop.disabled = true;
}
function showQuiz() {
document.getElementById("quiztable").style.visibility="visible";
document.quiz.start.disabled = true;
document.quiz.stop.disabled = false;
}
function hideQuiz() {
document.getElementById("quiztable").style.visibility="hidden";
}
function gradeQuiz() {
correct=0;
if (document.quiz.q1[1].checked) correct++;
if (document.quiz.q2[3].checked) correct++;
if (document.quiz.q3[0].checked) correct++;
if (document.quiz.q4[3].checked) correct++;
if (document.quiz.q5[2].checked) correct++;
document.getElementById("cor1").style.backgroundColor="yellow";
document.getElementById("cor2").style.backgroundColor="yellow";
document.getElementById("cor3").style.backgroundColor="yellow";
document.getElementById("cor4").style.backgroundColor="yellow";
document.getElementById("cor5").style.backgroundColor="yellow";
for (i=0; i<document.quiz.elements.length; i++)document.quiz.elements[i].disabled=true;
return correct;
}
html for button that pops up the alert
<input id="stop" type="button" value="Submit Answers" onclick="stopClock()"/>
Probably you have a variable undefined, check this working demo
function gradeQuiz() {
return 'something';
}
var clockId, i = timer = 0;
clockId = setInterval(function() {
i++;
$('h2').text(i);
}, 200);
function stopClock() {
clearInterval (clockId);
correctAns = gradeQuiz();
alert('You have ' + correctAns + ' correct of 5 in ' + timer + ' seconds');
}
$('button').on('click', stopClock);
http://jsbin.com/toyibekivu/edit?html,js,output
You need to define your variables and use seconds in alert.
Change your functions to:
var clockId;
var seconds = 0;
function stopClock() {
clearInterval (clockId);
correctAns = gradeQuiz();
alert('You have' + correctAns + 'correct of 5 in' + seconds + 'seconds');
}
function startClock() {
showQuiz();
seconds = 0;
clockId=setInterval (runClock, 1000);
}
If you remove
alert('You have' + correctAns + 'correct of 5 in' + timer + 'seconds');
from your stopClock() function no alert will appear on the screen.

Check when element is double-clicked with middle mouse button

<div style="width: 250px;
height: 100px;
background-color: Green;
border-style: solid;
border-color: Black;"></div>
With the code above, I create a green box with a black outline. Fiddle.
Below, I have a Javascript function myFunction().
function myFunction() {
window.alert("Hello world!");
}
How do I get this function to run when the user uses his middle mouse button twice in a row with his mouse in the green box (as quickly as how someone double-clicks with his left mouse button)?
Plain JavaScript 1:
Cross browser support
var div = document.getElementsByTagName("div")[0];
var count = 0;
var timeout;
div.onmouseup = function(e){ // thanks RobG, it should be `mouseup`
if(e.which == 2){
count++;
if(!timeout){
timeout = setTimeout(function(){
timeout = undefined;
check();
}, 250);
}
}else{
count = 0;
}
};
function check(){
if(count >= 2){
alert('y');
}
count = 0;
}
DEMO
With jQuery:
Not working in Firefox 27.0 - use "Plain JS 1"
$("div").dblclick(function(e){
if(e.which == 2)
alert('y');
})
DEMO
Plain JavaScript 2:
Doesn't work in Safari 7/FireFox 27.0 - use "Plain JS 1"
var div = document.getElementsByTagName("div")[0];
div.ondblclick = function (e) {
if(e.button == 1) alert('y');
};
DEMO
Start simple. Add a click handler to you div like this:
<div style="width: 250px;
height: 100px;
background-color: Green;
border-style: solid;
border-color: Black;" onclick="myFunction();"></div>
Get that working, then search for how to modify the click event to use other buttons
Here is a function version of Gaurang's answer, however I can't get it to work reliably on Mac OS (nor is Gaurang's answer reliable). Anyway, it might be useful.
// Listener to add
function foo(e) {
console.log(this.id + ':' + e.button);
}
// Main function
var addNonPrimaryDblclick = (function() {
var timeout = null,
count = 0,
delay = 250;
// If timeout expires, reset everything
function checkTimeout() {
if (timeout) {
clearTimeout(timeout);
timeout = null;
count = 0;
}
}
return function(element, listener, newDelay) {
if (typeof newDelay != 'undefined') delay = newDelay;
// Add isDoubleClick as listener
element.addEventListener('mouseup', isDoubleClick, false);
function isDoubleClick(e) {
// A bit of debug
console.log('button: ' + e.button + ' which: ' + e.which);
e.preventDefault();
// 2 is the secondary button, equivalent to 3 in "which" scheme
if (e.button == 2) {
count++;
if (timeout) {
// If this is second click within delay, reset everything
// and call listener
if (count == 2) {
clearTimeout(timeout);
timeout = null;
count = 0;
// Set element to "this" in the listener and pass event
listener.call(element, e);
return;
}
// If no timeout setup, doso
} else {
timeout = setTimeout(checkTimeout, delay);
}
}
}
}
}());
// Example use - set long delay for testing
addNonPrimaryDblclick(document.getElementById('d0'), foo, 1000);

Categories

Resources