Why don't these OnClick and OnKeyDown Events work? - javascript

var clicks;
var time1;
var keys_pressed;
var keys_typed;
function startTrack() {
time1 = Date.now();
clicks = 0;
keys_pressed = 0;
keys_typed = 0;
}
document.onclick = function() {
clicks++;
};
document.onkeydown = function() {
keys_pressed++;
};
function analytics() {
var time2 = Date.now();
var time = time2 - time1;
var min = Math.floor(time / 60000);
var sec = (time % 60000) / 1000;
document.body.insertAdjacentHTML( 'afterbegin', '<div hidden><p>Number of mouse clicks: '+ clicks + '</p><p>Total time spent: ' + min + ' mins, ' + sec + ' secs' + '</p><p>Total key presses: ' + keys_pressed + '</p><p>Total number of characters: ' + keys_typed + '</p></div>' );
}
<body onload="startTrack()">
...
</body>
I'm a complete JS beginner trying to get 2 simple events to work without using Ajax or JQuery or anything like that. All my other scripts seem to work, except the two events above where I'm just trying to store the number of keys pressed and mouse clicks anywhere on the page. However, the counters for both these metrics remain at zero no matter what. Any help would be greatly appreciated.

Doing a clicks++; when it is not initialized produces NaN since you cannot ++ on undefined.
var clicks;
var time1;
var keys_pressed;
var keys_typed;
function startTrack() {
time1 = Date.now();
clicks = 0;
keys_pressed = 0;
keys_typed = 0;
}
document.onclick = function() {
clicks++;
// without the initialization this logs NaN
console.log("Clicks:",clicks);
};
document.onkeydown = function() {
keys_pressed++;
console.log("Pressed:", keys_pressed);
};
console.log(clicks);// logs "undefined"
// you need to initialize your variables so call it!
//startTrack();
<body onload="startTrack()">
...<div>Hi there I am here! But the fish ate my bait.</div>
</body>

Using addEventListener() is better as it allows you to add multiple listeners instead of replacing a listener that might have already been there:
let events = 0
const foo = document.getElementById('foo')
document.addEventListener('click', oneMore)
document.addEventListener('keydown', oneMore)
function oneMore(ev) {
foo.textContent = ++events
}
#foo {
width: 50px;
height: 50px;
background: lime;
}
<div id=foo>Click me</div>

addEventListener('click', (e) => { clicks++ })
addEventListener('keydown', (e) => { keys_pressed++ })
Should work.

Related

timer starts automatically instead of on a button press in javascript

I'm quite new to javascript so the answer is probably quite easy but anyways
I'm trying to make a simple click speed test but i cant get the timer to start when the user presses the click me button, so i resorted to just starting it automatically. if anyone can help me to start it on the button press it will be much appreciated
HTML code:
<button id="click2" onclick="click2()">Click Me!</button><br>
<span id="clicksamount">0 Clicks</span><br><br>
<span id="10stimer">10s</span>
JS code:
var click = document.getElementById("click2");
var amount = 0;
var seconds = 10;
var endOfTimer = setInterval(click2, 1000);
function click2() {
seconds--;
document.getElementById("10stimer").innerHTML = seconds + "s";
if (seconds <= 0) {
var cps = Number(amount) / 10;
document.getElementById("clicksamount").innerHTML = "You got " + cps + " CPS!";
document.getElementById("click2").disabled = true;
document.getElementById("10stimer").innerHTML = "Ended";
clearInterval(seconds);
}
}
document.getElementById("click2").onclick = function() {
amount++;
document.getElementById("clicksamount").innerHTML = amount + " Clicks";
}
It looks like you're overwriting your onclick function on the button with id click2 with the lowest 4 lines.
Also, you call clearInterval() with the seconds variable instead of the actual interval, which is referenced by endOfTimer.
I'd suggest to have a separated timer management in a function which you call only on the first click of your button.
See JSFiddle
<button id="clickbutton" onclick="buttonClick()">Click Me!</button><br>
<span id="clicksamount">0 Clicks</span><br><br>
<span id="secondcount">10s</span>
// We will have timerStarted to see if the timer was started once,
// regardless if it's still running or has already ended. Otherwise
// we would directly restart the timer with another click after the
// previous timer has ended.
// timerRunning only indicates wether the timer is currently running or not.
var timerStarted = false;
var timerRunning = false;
var seconds = 10;
var clickAmount = 0;
var timer;
function buttonClick() {
if (!timerStarted) {
startTimer();
}
// Only count up while the timer is running.
// The button is being disabled at the end, therefore this logic is only nice-to-have.
if (timerRunning) {
clickAmount++;
document.getElementById("clicksamount").innerHTML = clickAmount + " Clicks";
}
}
function startTimer() {
timerStarted = true;
timerRunning = true;
timer = setInterval(timerTick,1000);
}
function timerTick() {
seconds--;
document.getElementById("secondcount").innerHTML = seconds + "s";
if (seconds <= 0) {
timerRunning = false;
clearInterval(timer);
var cps = Number(clickAmount) / 10;
document.getElementById("clickbutton").disabled = true;
document.getElementById("clicksamount").innerHTML = "You got " + cps + " CPS (" + clickAmount + "clicks in total)!";
}
}
I made some changes to your code. Effectively, when the user clicks the first time, you start the timer then. The timer variables is null until the first the user clicks.
var click = document.getElementById("click2");
var noOfClicks = 0;
var seconds = 10;
var timer = null;
function doTick(){
seconds--;
if(seconds<=0){
seconds = 10;
clearInterval(timer);
document.getElementById("10stimer").innerHTML= "Ended"
timer=null;
document.getElementById("click2").disabled = true;
}
updateDisplay()
}
function updateClicks(){
if(!timer){
timer=setInterval(doTick, 1000);
clicks= 0;
seconds = 10;
}
noOfClicks++;
updateDisplay();
}
function updateDisplay(){
var cps = Number(noOfClicks) / 10;
document.getElementById("clicksamount").innerHTML = "You got " + cps + " CPS!";
document.getElementById("10stimer").innerHTML =seconds;
}
click.addEventListener('click', updateClicks)
https://jsbin.com/bibuzadasu/1/edit?html,js,console,output
function timer(startEvent, stopEvent) {
let time = 0;
startEvent.target.addEventListener(startEvent.type, () => {
this.interval = setInterval(()=>{
time++;
}, 10); // every 10 ms... aka 0.01s
removeEventListener(startEvent.type, startEvent.target); // remove the listener once we're done with it.
stopEvent.target.addEventListener(startEvent.type, () => {
clearInterval(this.interval); // stop the timer
// your output function here, example:
alert(time);
removeEventListener(stopEvent.type, stopEvent.target); // remove the listener once we're done with it.
});
});
}
Use event listeners rather than onclicks
usage example:
HTML
<button id="mybutton">Click me!</button>
JS
/* ABOVE CODE ... */
let mybutton = document.getElementById("mybutton");
timer(
{target: mybutton, type: "click"},
{target: mybutton, type: "click"}
);
function timer(startEvent, stopEvent) {
let time = 0;
startEvent.target.addEventListener(startEvent.type, () => {
this.interval = setInterval(()=>{
time++;
}, 10); // every 10 ms... aka 0.01s
removeEventListener(startEvent.type, startEvent.target); // remove the listener once we're done with it.
stopEvent.target.addEventListener(startEvent.type, () => {
clearInterval(this.interval); // stop the timer
// your output function here, example:
alert(time);
removeEventListener(stopEvent.type, stopEvent.target); // remove the listener once we're done with it.
});
});
}
let mybutton = document.getElementById("mybutton");
timer(
{target: mybutton, type: "click"},
{target: mybutton, type: "click"}
);
<button id="mybutton">Click me!</button>
//state initialization
var amount = 0;
var seconds = 10;
var timedOut=false;
var timerId=-1;
//counters display
var clicksDisplay= document.getElementById("clicksamount");
var timerDisplay= document.getElementById("10stimer");
function click2(e){
//first click
if(timerId===-1){
//start timer
timed();
}
//still in time to count clicks
if(!timedOut){
amount++;
clicksDisplay.innerText=amount +" Clicks";
}
}
function timed(){
//refresh timer dispaly
timerDisplay.innerText=seconds+"s";
seconds--;
if(seconds<0){
//stop click count
timedOut=true;
}else{
//new timerId
timerId=setTimeout(timed,1000);
}
}

trying to count the seconds while my users is with the mouse over an element

I am new in Javascript and I am trying to count the seconds while my users is with the mouse over an element.But I can`t get the interval to stop. Here is my code until now. Thanks
var seconds = 0;
var el = document.getElementById('ceva');
function incrementSeconds() {
seconds += 1;
el.innerText = "You have been here for " + seconds + " seconds.";
}
var x;
document.getElementById("ceva").onmouseenter = function() {var x =
setInterval(incrementSeconds, 1000)};
function mouseLeave() {
clearInterval(x`);
}
document.getElementById("ceva").onmouseleave = function() {mouseLeave()};
Just remove the "var" in the mouseenter function. Change it as below
document.getElementById("ceva").onmouseenter = function(){
x = setInterval(incrementSeconds, 1000)
};

Converting a manual slideshow to automatic

I followed a tutorial and created a simple manual loop slideshow. I'm trying to make it so it changes the slide automatically even if the prev/next buttons aren't clicked. I tried a crude approach by setting a delay between automatic click events on the "next" button but for some reason it clicks it only once and stops. My js knowledge is very limited and can't figure it out, any input is appreciated. This is the script so far:
$(function() {
var ul = $(".slider ul");
var slide_count = ul.children().length;
var slide_width_pc = 100.0 / slide_count;
var slide_index = 0;
var first_slide = ul.find("li:first-child");
var last_slide = ul.find("li:last-child");
last_slide.clone().prependTo(ul);
first_slide.clone().appendTo(ul);
ul.find("li").each(function(indx) {
var left_percent = (slide_width_pc * indx) + "%";
$(this).css({"left":left_percent});
$(this).css({width:(100 / slide_count) + "%"});
});
ul.css("margin-left", "-100%");
$(".slider .prev").click(function() {
console.log("prev button clicked");
slide(slide_index - 1);
});
$(".slider .next").click(function() {
console.log("next button clicked");
slide(slide_index + 1);
});
function slide(new_slide_index) {
var margin_left_pc = (new_slide_index * (-100) - 100) + "%";
ul.animate({"margin-left": margin_left_pc}, 400, function() {
if(new_slide_index < 0) {
ul.css("margin-left", ((slide_count) * (-100)) + "%");
new_slide_index = slide_count - 1;
}
else if(new_slide_index >= slide_count) {
ul.css("margin-left", "-100%");
new_slide_index = 0;
}
slide_index = new_slide_index
});
}
});
Here is an approach to make it sliding automatically...
But if user clicks on prev/next, it holds the automatic feature for a defined "idle" time.
It need two lines added to your click handlers:
var autoEnabled = true; // ADDED
$(".slider .prev").click(function() {
console.log("prev button clicked");
slide(slide_index - 1);
autoEnabled = false; // ADDED
disabledCount = 0; // ADDED
});
$(".slider .next").click(function() {
console.log("next button clicked");
slide(slide_index + 1);
autoEnabled = false; // ADDED
disabledCount = 0; // ADDED
});
And this to cyclically slide or check if it can re-enable itself.
// ----------------- Automatic sliding interval with "idle time" to re-enable on user click
var idleTime = 5000; // Time without manual click to re-enable automatic sliding.
var autoSlideDelay = 1000; // Time between each slide when automatic.
var disabledCount = 0;
var autoSlide = setInterval(function(){
if(autoEnabled || disabledCount >= idleTime/autoSlideDelay ){
disabledCount = 0;
autoEnabled = true;
slide(slide_index + 1);
}else{
disabledCount++;
}
},autoSlideDelay);
var break_auto_slide = false;
function auto_silde()
{
if(break_auto_slide)
{
break_auto_slide = false;
return;
}
slide(slide_index + 1);
setTimeout(auto_silde,1000 /* time in ms*/);
}
setTimeout will call the function in a specified timeout in milliseconds.
Variable break_auto_slide - set it to true to stop the automatic slide. Next time the function is called it will return without setting a new timer and will reset this variable so auto mode can be turned on again.

Reset javascript function

I am having trouble getting a javascript function to reset itself after an onclick event. When I click the "Start" button the counter begins to count up. But when I click the "Reset" button nothing happens. I need the timer to reset to "0:00" and wait for me to click "Start" again. Here is my code:
<script type="text/javascript">
var seconds = 0;
var minutes = 0;
function zeroPad(time) {
var numZeropad = time + '';
while(numZeropad.length < 2) {
numZeropad = "0" + numZeropad;
}
return numZeropad;
}
function countSecs() {
seconds++;
if (seconds > 59) {
minutes++;
seconds = 0;
}
document.getElementById("timeBox").innerHTML = "Time " + zeroPad(minutes) + ":" + zeroPad(seconds);
}
function startTimer() {
action = window.setInterval(countSecs,1000);
}
function resetTimer() {
var seconds = 0;
var minutes = 0;
}
</script>
<body>
<button onclick = "startTimer()">Start</button>
<div id="timeBox">Time 00:00</div>
<button onclick = "resetTimer">Reset</button>
</body>
Call the clearInterval() method.
function resetTimer() {
window.clearInterval(action);
}
This is a scoping issue, using var inside a function, makes seconds and minutes local to that function. Removing the leading var will start you off in the right direction.
function resetTimer() {
seconds = 0;
minutes = 0;
}
Onclick events must call functions like: onclick="resetTimer();" with the parenthesis at the end. Some browsers may try to submit on button clicks if you don't define type="button". I didn't assume you wanted reset timer to stop the timer so I added a stop button.
http://jsfiddle.net/iambriansreed/WRdSK/
<button type="button" onclick="startTimer();">Start</button>
<div id="timeBox">Time 00:00</div>
<button type="button" onclick="resetTimer();">Reset</button>
<button type="button" onclick="stopTimer();">Stop</button>
<script>
window.seconds = 0;
window.minutes = 0;
function startTimer() {
window.action = setInterval(countSecs,1000);
}
function resetTimer() {
seconds = 0;
minutes = 0;
}
function stopTimer() {
clearInterval(action);
seconds = -1;
minutes = 0;
countSecs();
}
function zeroPad(time) {
var numZeropad = time + '';
while(numZeropad.length < 2) {
numZeropad = "0" + numZeropad;
}
return numZeropad;
}
function countSecs() {
seconds++;
if (seconds > 59) {
minutes++;
seconds = 0;
}
document.getElementById("timeBox").innerHTML = "Time " + zeroPad(minutes) + ":" + zeroPad(seconds);
}
</script>
​
You have two errors in your code:
First, in the button you missed the () after the function's name in order to make an actual call:
<button onclick = "resetTimer()">Reset</button>
Second, you did not stop the interval using window.clearInterval() (MDN docu), so the timer went on and on.
// just to make it an explicit global variable. already was an implicit one.
var action;
// rest of your code
function resetTimer() {
// clear the timer
window.clearInterval( action );
// reset variables
var seconds = 0;
var minutes = 0;
// update output
document.getElementById("timeBox").innerHTML = "Time " + zeroPad(minutes) + ":" + zeroPad(seconds);
}
I set up a working fiddle here.

jquery: stopwatch

I'm using the stopwatch code I found here:
http://www.kellishaver.com/projects/stopwatch/
(function($) {
$.fn.stopwatch = function() {
var clock = this;
var timer = 0;
clock.addClass('stopwatch');
//console.log(clock);
// This is bit messy, but IE is a crybaby and must be coddled.
clock.html('<div class="display"><span class="hr">00</span>:<span class="min">00</span>:<span class="sec">00</span></div>');
clock.append('<input type="button" class="start" value="Start" />');
clock.append('<input type="button" class="stop" value="Stop" />');
clock.append('<input type="button" class="reset" value="Reset" />');
//console.log(clock.html());
// We have to do some searching, so we'll do it here, so we only have to do it once.
var h = clock.find('.hr');
var m = clock.find('.min');
var s = clock.find('.sec');
var start = clock.find('.start');
var stop = clock.find('.stop');
var reset = clock.find('.reset');
stop.hide();
start.bind('click', function() {
timer = setInterval(do_time, 1000);
stop.show();
start.hide();
});
stop.bind('click', function() {
clearInterval(timer);
timer = 0;
start.show();
stop.hide();
});
reset.bind('click', function() {
clearInterval(timer);
timer = 0;
h.html("00");
m.html("00");
s.html("00");
stop.hide();
start.show();
});
function do_time() {
// parseInt() doesn't work here...
hour = parseFloat(h.text());
minute = parseFloat(m.text());
second = parseFloat(s.text());
second++;
if(second > 59) {
second = 0;
minute = minute + 1;
}
if(minute > 59) {
minute = 0;
hour = hour + 1;
}
h.html("0".substring(hour >= 10) + hour);
m.html("0".substring(minute >= 10) + minute);
s.html("0".substring(second >= 10) + second);
}
};
})(jQuery);
And I use it like this:
<script type="text/javascript">
$('#clock1').stopwatch();
</script>
It works fine and I can stop it using the stop button. However I would like to be able to stop it programatically using javascript. Something like this:
<script type="text/javascript">
$('#clock1').stop();
</script>
I created the stop function but I cannot access the timer var defined in stopwatch(). How can I do it?
How about:
$('#clock1').find('.stop').trigger('click');
You can add a small API to the code and attach it using $.data:
var api = {
stop: function() {
stop.click(); // this should probably be improved, but you get the idea
}
};
$(clock).data('stopwatch', api);
Then use:
$('#clock1').data('stopwatch').stop();
You can also add the reset and start functions to the API using the same logic. A good thing here is that you can improve the execution code on a coffee break later without changing the way external programs uses the API.

Categories