Javascript increment value faster with mouse hold [duplicate] - javascript

This question already has answers here:
Incrementing value continuously on mouse hold
(5 answers)
Closed 5 years ago.
I have this script that adds 1 to a value every time I click on a button:
<script>
function incrementValue(id) {
var value = parseInt(document.getElementById(id).innerHTML);
value = value + 1;
document.getElementById(id).innerHTML = value;
}
</script>
<button onclick="incrementValue('skill_1')"> add </button><br>
<span id=skill_1>0</span>
However I want to adjust it so that if I hold down the mouse button, it'll repeat so I don't have to keep pressing it over and over.
Any way to do that using javascript? Or would jquery suit?

To achieve this you need to use the mousedown event to start a timeout (which is the delay before the incremental count starts) and an interval (which does the repeated counting). You'll also need a mouseup and mouseleave handler to remove both of those timers. Try this:
var timeout, interval;
[].forEach.call(document.querySelectorAll('.add'), function(button) {
button.addEventListener('mousedown', function() {
var id = button.dataset.target;
incrementValue(id);
timeout = setTimeout(function() {
interval = setInterval(function() {
incrementValue(id);
}, 50);
}, 300);
});
button.addEventListener('mouseup', clearTimers);
button.addEventListener('mouseleave', clearTimers);
function clearTimers() {
clearTimeout(timeout);
clearInterval(interval);
}
});
function incrementValue(id) {
var el = document.getElementById(id);
var value = parseInt(el.textContent, 10);
document.getElementById(id).textContent = ++value;
}
<button class="add" data-target="skill_1">add</button><br />
<span id="skill_1">0</span>

You'll need 3 event handler:
mousedown that will call a function, that will call itself with a timeout (continuosIncerment) while the mouse button is pressed.
mouseup that will clear the timeout when the button is released.
mouseleave that clears the timeout when the mouse leaves the button area.
const btn = document.querySelector('#btn');
const skill_1 = document.querySelector('#skill_1');
let value = 0;
let timer;
function continuosIncerment() {
skill_1.innerHTML = ++value;
timer = setTimeout(continuosIncerment, 200);
}
function timeoutClear() {
clearTimeout(timer);
}
btn.addEventListener('mousedown', continuosIncerment);
btn.addEventListener('mouseup', timeoutClear);
btn.addEventListener('mouseleave', timeoutClear);
<button id="btn"> add </button><br>
<span id="skill_1">0</span>

Instead of reading the value from the HTML, then writing it back, it's easier to hold the value in a variable, increment it, then write it out.
Did you know you can do this with a simple HTML spinner?
<input type="number" min="0" max="50" step="1">

I'd go with a solution like this: on mouse down event starts a repeating timer that triggers your function and it stops when the mouse up event occurs.
var inter = null;
function setInter(){
inter=setInterval(incrementValue, 500);
}
function unsetInter(){
clearInterval(inter);
}
function incrementValue() {
var value = parseInt(document.getElementById('skill_1').innerHTML);
value = value + 1;
document.getElementById('skill_1').innerHTML = value;
}
<button
onmousedown="setInter()"
onmouseup="unsetInter()"> add </button>
<br>
<span id=skill_1>0</span>

Related

read div and check for a click condition

let timer = document.querySelector("#timer");
var counter = 3;
function myFn() {
counter--
if (counter === -1) {
counter = 3
}
timer.innerText = counter
}
btn.onclick = function() {
text.innerHTML += 'clicked' + '<br>'
}
var myTimer = setInterval(myFn, 1000);
<div id="timer"></div>
<button id="btn">Button</button>
<div id="text"></div>
I'm trying with this small code to read the div#timer every second and check for a click condition in console.log() F12. It gives me different error in every way I try to do it.
let timer = document.querySelector("#timer");
let btn = document.querySelector("#btn");
setInterval(() => {
console.log(timer.textContent)
if (timer.textContent === '0') {
btn.click()
}
}, 1000);
Consider the following jQuery example.
$(function() {
var timer = 0;
var counter = 3;
var timeObj = $("#timer");
var btnObj = $("#btn");
var txtObj = $("#text");
var interval;
function myFn() {
if (--counter >= 0) {
txtObj.append("Clicked<br />");
} else {
clearInterval(interval);
}
}
interval = setInterval(function() {
timeObj.html(++timer);
}, 1000);
btnObj.click(myFn);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="timer">0</div>
<button id="btn">Button</button>
<div id="text"></div>
You will want to use setInterval() and not setTimeout().
The setInterval() method, offered on the Window and Worker interfaces, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call.
This method returns an interval ID which uniquely identifies the interval, so you can remove it later by calling clearInterval().
See more: https://developer.mozilla.org/en-US/docs/Web/API/setInterval
Using the -- and ++ before the variable will also apply the change before it is used.
The decrement operator (--) decrements (subtracts one from) its operand and returns the value before or after the decrement, depending on where the operator is placed.
Adjusting the logic here can also ensure that the button click does allow the user to keep performing actions.

set Interval function giving output for previous parameter [duplicate]

So, I got an infinite loop to work in this function using setInterval attached to an onClick. Problem is, I can't stop it using clearInterval in an onClick. I think this is because when I attach a clearInterval to an onClick, it kills a specific interval and not the function altogether. Is there anything I can do to kill all intervals through an onClick?
Here's my .js file and the calls I'm making are
input type="button" value="generate" onClick="generation();
input type="button" value="Infinite Loop!" onclick="setInterval('generation()',1000);"
input type="button" value="Reset" onclick="clearInterval(generation(),80;" // This one here is giving me trouble.
setInterval returns a handle, you need that handle so you can clear it
easiest, create a var for the handle in your html head, then in your onclick use the var
// in the head
var intervalHandle = null;
// in the onclick to set
intervalHandle = setInterval(....
// in the onclick to clear
clearInterval(intervalHandle);
http://www.w3schools.com/jsref/met_win_clearinterval.asp
clearInterval is applied on the return value of setInterval, like this:
var interval = null;
theSecondButton.onclick = function() {
if (interval === null) {
interval = setInterval(generation, 1000);
}
}
theThirdButton.onclick = function () {
if (interval !== null) {
clearInterval(interval);
interval = null;
}
}
Have generation(); call setTimeout to itself instead of setInterval. That was you can use a bit if logic in the function to prevent it from running setTimeout quite easily.
var genTimer
var stopGen = 0
function generation() {
clearTimeout(genTimer) ///stop additional clicks from initiating more timers
. . .
if(!stopGen) {
genTimer = setTimeout(function(){generation()},1000)
}
}
}
Live demo
This is all you need!
<script type="text/javascript">
var foo = setInterval(timer, 1000);
function timer() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("demo").innerHTML = t;
}
$(document).on("click", "#stop_clock", function() {
clearInterval(foo);
$("#stop_clock").empty().append("Done!");
});
</script>

onmouseover() to invoke onclick after 1 second?

I have an element:
<b onclick="alert('');" onmouseover="this.style.color='red'; setTimeout('........', 1000);" onmouseout="this.style.color='';">123</b>
I need that when element is mouseovered and after 1 second the mouse cursor continue staying above this element, then onclick() event of this element should start.
In other words, what should be instead of '..............' in onmouseover() event?
window.countdown = setTimeout(function(){this.click();}, 1000);
Additionally, you need to clear the interval in the mouseout handler:
clearTimeout(countdown);
Ideally you would give your element an ID and use the new event registration model:
var e = document.getElementById('myelement');
e.addEventListener('click',function(){
alert('');
});
e.addEventListener('mouseenter',function(){
var self = this;
this.style.color='red';
window.countdown = setTimeout(function(){self.click();}, 1000);
});
e.addEventListener('mouseleave',function(){
this.style.color='';
clearTimeout(countdown);
});
You should start the interval on mouse over event as a global variable to refer on mouse out event to clear it like #Asad said.
<b onclick = "alert()"
onmouseover = "window.countdown = setTimeout(function(){this.click();}, 1000);"
onmouseout = "clearTimeout(countdown)">
123
</b>
You'll have to do some extra work, and this won't work out very well for you inside of inline Javascript. This is all pseudocode so I don't recommend copy/pasting!
// We'll need to create an interval and store it
var timerInterval = {}
// And keep track of how many seconds have elapsed
var timeElapsedInSeconds = 0;
function tick (){
timeElapsedInSeconds++;
if (timeElapsedInSeconds > 0){
// YOUR GREAT CODE HERE
}
// Either way, let's be sure to reset everything.
resetTimer();
}
function hoverOverHandler (){
// Start our timer on hover
timerInterval = window.setInterval(tick, 1000);
}
function resetTimer () {
timeElapsedInSeconds = 0;
window.clearInterval(timerInterval);
}
function hoverOutHandler () {
// Kill timer on hoverout
resetTimer();
}
Ok, I did some trick with dynamic id and this is what came out:
<b style="color:red;" onclick="if(this.style.color!='green'){return false;}else{this.style.color='red';} alert(this.parentNode);" onmouseover="if(this.style.color!='green'){var newID='tmpID_'+Math.floor(Math.random() * (10000000)); if(this.id==''){this.id=newID;} setTimeout('top.document.getElementById(\''+this.id+'\').onclick();',1000); this.style.color='green';}" onmouseout="this.style.color='red';">click</b>
crossbrowsered =)

Is there any way to kill a setInterval loop through an Onclick button

So, I got an infinite loop to work in this function using setInterval attached to an onClick. Problem is, I can't stop it using clearInterval in an onClick. I think this is because when I attach a clearInterval to an onClick, it kills a specific interval and not the function altogether. Is there anything I can do to kill all intervals through an onClick?
Here's my .js file and the calls I'm making are
input type="button" value="generate" onClick="generation();
input type="button" value="Infinite Loop!" onclick="setInterval('generation()',1000);"
input type="button" value="Reset" onclick="clearInterval(generation(),80;" // This one here is giving me trouble.
setInterval returns a handle, you need that handle so you can clear it
easiest, create a var for the handle in your html head, then in your onclick use the var
// in the head
var intervalHandle = null;
// in the onclick to set
intervalHandle = setInterval(....
// in the onclick to clear
clearInterval(intervalHandle);
http://www.w3schools.com/jsref/met_win_clearinterval.asp
clearInterval is applied on the return value of setInterval, like this:
var interval = null;
theSecondButton.onclick = function() {
if (interval === null) {
interval = setInterval(generation, 1000);
}
}
theThirdButton.onclick = function () {
if (interval !== null) {
clearInterval(interval);
interval = null;
}
}
Have generation(); call setTimeout to itself instead of setInterval. That was you can use a bit if logic in the function to prevent it from running setTimeout quite easily.
var genTimer
var stopGen = 0
function generation() {
clearTimeout(genTimer) ///stop additional clicks from initiating more timers
. . .
if(!stopGen) {
genTimer = setTimeout(function(){generation()},1000)
}
}
}
Live demo
This is all you need!
<script type="text/javascript">
var foo = setInterval(timer, 1000);
function timer() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("demo").innerHTML = t;
}
$(document).on("click", "#stop_clock", function() {
clearInterval(foo);
$("#stop_clock").empty().append("Done!");
});
</script>

Detecting when the mouse is not moving

I am able to find the cursor position. But I need to find out if the mouse is stable. If the mouse wasn't moved for more than 1 minute, then we have to alert the user.
How its possible, are there any special events for this? (Only for IE in javascript)
Set a timeout when the mouse is moved one minute into the future, and if the mouse is moved, clear the timeout:
var timeout;
document.onmousemove = function(){
clearTimeout(timeout);
timeout = setTimeout(function(){alert("move your mouse");}, 60000);
}
Here's a one-and-done function that can check any element for movement:
function mouse (element, delay, callback) {
// Counter Object
element.ms = {};
// Counter Value
element.ms.x = 0;
// Counter Function
element.ms.y = function () {
// Callback Trigger
if ((++element.ms.x) == delay) element.ms.callback(element, element.ms);
};
// Counter Callback
element.ms.callback = callback;
// Function Toggle
element.ms.toggle = function (state) {
// Stop Loop
if ([0, "off"][state]) clearInterval(element.ms.z);
// Create Loop
if ([1, "on"][state]) element.ms.z = setInterval(element.ms.y, 1);
};
// Function Disable
element.ms.remove = function () {
// Delete Counter Object
element.ms = null; return delete element.ms;
};
// Function Trigger
element.onmousemove = function () {
// Reset Counter Value
element.ms.x = -1;
};
// Return
return element.ms;
};
Usage:
mouse(element, delay, callback)
Examples:
Make a video player hide the mouse after 5 seconds when idle and fullscreen
let x = mouse(video, 5000, function (a) {
if (document.webkitIsFullScreen) video.style.cursor = "none";
});
x.toggle(1); addEventListener("mousemove", function () {
video.style.cursor = "auto";
});
Chat Room AFK (45 Seconds) (assuming you have a chat box and a send message function):
let x = mouse(chatBox, (45e3), function (a) {
chatBox.send({ text: chatBox.username + " is AFK.", italic: true });
});
x.toggle(1); x.addEventListener("mousemove", function () {
chatBox.send({ text: chatBox.username + " is no longer AFK", italic: true });
});
Is there not a way to set a timer to start incrementing after every mouse movement event?
If it gets to a minute then pop up the message box, but every time the mouse moves the timer gets reset.
Use a timer that resets its value on mousemove event.
If timer reaches 1 minute --> Do something.
More info on timer here http://www.w3schools.com/js/js_timing.asp
And more info on catchin mouse events here http://www.quirksmode.org/js/events_mouse.html
Yes, you have a onmousemove event in Javascript, so to achieve what you need you just have to do code something like this:
startTimer();
element.onmousemove = stopTimer(); //this stops and resets the timer
You can use it on the document body tag for instance.
UPDATE: #Marius has achieved a better example than this one.
You can use the onmousemove event. Inside it, clearTimeout(), and setTimeout(your_warning, 1 minute).
You could use this script/snippet to detect the mouse pointer position and "remember" it. Then use a timer "setTimeout(...)" to check the position let's say every second and remember that time.
If more than one minute passed and the position hasn't changed, you could alert the user.

Categories