var mdflag;
var count = 0;
document.addEventListener("mousedown",mdown,false);
document.addEventListener("mouseup",mup,false);
}
function mdown()
{
mdflag=true;
while(mdflag)
document.getElementById("testdiv").innerHTML = count++;
}
function mup()
{
mdflag = false;
}
I'm wanting to run code while the mouse is down, i cant find anything to suggest i can do while(mousedown) so i've tryed making a flag for mousedown which is reset on mouse up however i beleive the while loop is whats causing me to go get stuck in an infinite loop.
Any advice to help with what i'm trying to acheive?
You have to invoke the mousedown activity in some reasonable interval. I'd do this:
var mousedownID = -1; //Global ID of mouse down interval
function mousedown(event) {
if(mousedownID==-1) //Prevent multimple loops!
mousedownID = setInterval(whilemousedown, 100 /*execute every 100ms*/);
}
function mouseup(event) {
if(mousedownID!=-1) { //Only stop if exists
clearInterval(mousedownID);
mousedownID=-1;
}
}
function whilemousedown() {
/*here put your code*/
}
//Assign events
document.addEventListener("mousedown", mousedown);
document.addEventListener("mouseup", mouseup);
//Also clear the interval when user leaves the window with mouse
document.addEventListener("mouseout", mouseup);
You can't do that, as your function must end before another event is processed, but you could repetitively call a function until the mouse is up :
var timer;
document.addEventListener("mousedown", function(){
timer=setInterval(function(){
document.getElementById("testdiv").innerHTML = count++;
}, 100); // the above code is executed every 100 ms
});
document.addEventListener("mouseup", function(){
if (timer) clearInterval(timer)
});
You need to use setInterval to execute your function and clearInternal to stop
let interval = setInterval(function(){
console.log("executing...");
}, 0);
document.addEventListener("mouseup", function(){
clearInterval(interval);
console.log('End');
});
Related
I was able to get the space bar to activate the simple button I made, but I am having problems with having it be looped with setInterval(). Is it because of the eventFire mechanism I utilized? Any help or constructive criticism is welcomed as I am trying to learn. Thanks for your time.
Edit: I was able to find a solution as I apparently was using the setInterval function incorrectly. However I still have an issue with stopping the setInterval loop with clearInterval(timer) E hotkey. Here is the updated code.
"use strict";
// used for Tracking Mouse Position which I will implement later
let mousex;
let mousey;
// Simple Button that logs the amount of times pressed and triggers an animation
function button() {
const button = document.querySelector(".button");
function buttonClassRemove() {
button.classList.remove("active");
}
function delay(time, inputFunction) {
let milliseconds = time;
setTimeout(function () {
inputFunction();
}, milliseconds);
}
let i = 0;
button.addEventListener("click", function () {
i = i + 1;
console.log(`Button pressed ${i} times`);
button.classList.add("active");
delay(100, buttonClassRemove);
});
}
// Simulates event
function eventFire(el, etype) {
if (el.fireEvent) {
el.fireEvent("on" + etype);
} else {
var evObj = document.createEvent("Events");
evObj.initEvent(etype, true, false);
el.dispatchEvent(evObj);
}
}
function autoClicker() {
document.addEventListener("mousemove", () => {
// Tracking Mouse Position
mousex = event.clientX; // Gets Mouse X
mousey = event.clientY; // Gets Mouse Y
// console.log([mousex, mousey]); // Prints data
});
document.body.onkeydown = function (e) {
// Simulates click mouse event
// and then loop that functionality with the setInterval function
let timer = setInterval(function () {
eventFire(document.getElementById("button1"), "click");
}, 100);
if (e.keyCode == 32) {
timer;
console.log("Space pressed");
} else if (e.keyCode == 69) {
// Cancels autoclicker setInterval function
clearInterval(timer);
console.log("E pressed");
}
};
}
autoClicker();
button();
Your issue is that timer is a local variable. You should define it with var at the start of your program alongside mousex and mousey. As it currently stands, every time you run onkeydown it creates a new instance of the interval, checks whether to cancel it, and then throws away the reference. If you make it a global variable, then you can keep the reference so that you can cancel it at any time.
With this, you should also consider when you are running the interval. If you keep it as-is, your old interval will be overwritten with the new one before you can check to cancel. What you should do instead is something like this:
var timer = null;
document.body.onkeydown = function(e) {
if (/* start timer */ && timer == null) {
timer = setInterval(/* ... */);
} else if (/* end timer */) {
clearInterval(timer);
timer = null;
}
}
Basically what I am trying to do is, I am trying to call a function and repeat the same function after every "n" seconds till the mouse button is pressed (MouseDown) on a button/picture and stop calling the function when the mouse button is released (MouseUp). I am trying to do this using JavaScript!
SOME REFERENCES
https://api.jquery.com/mousedown/
How can I detect a rightmouse button event on mousedown?
JavaScript: Check if mouse button down?
Not tested, but to give an idea.
var state = false;
function repeatingFunction(){
if (!state){
return;
}
console.log("Do something");
setTimeout(repeatingFunction, 2000);
}
function mymousedown(ev){
state = true;
repeatingFunction();
}
function mymouseup(ev){
state = false;
}
var obj = document.getElementById("foo");
obj.addEventListener("mousedown", mymousedown);
obj.addEventListener("mouseup", mymouseup);
This should work for you:
var timerId = 0;
function onmousedown(ev) {
console.log("Do something"); //first call right after mouse down
timerId = setInterval(function () {
console.log("Do something");
}, 2000);
}
function onmouseup(ev) {
clearInterval(timerId);
}
var obj = document.getElementById("foo");
obj.addEventListener("mousedown", onmousedown);
obj.addEventListener("mouseup", onmouseup);
fiddle: https://jsfiddle.net/kLnjh9zd/
I want to be able to run the below function continuously while the mouse is down. At the moment the function excecutes once per click. I want to be able to continue running the function while mousedown and stop when the mouse is released.
$('#md').mousedown(function(e){
var pCords = e.pageY +e.pageY;
var max = $(document).height()+$(document).width();
var dg = 2*( pCords / max );
$('#div').css({ 'transform':'rotate('+dg+'deg) '});
});
This issue has been addressed in: jQuery continuous mousedown
It will involve setting up a flag that you can set to true when the first mousedown event occurs, and calling a function that only finishes once the flag is set back to false when the mouseup event occurs.
Easy way to do with time delay between execution of event handler:
var timerId = 0;
$('#md').mousedown(function(e){
timerId = setInterval(function() {
var pCords = e.pageY +e.pageY;
var max = $(document).height()+$(document).width();
var dg = 2*( pCords / max );
$('#div').css({ 'transform':'rotate('+dg+'deg) '});
}, 20); // specify the required time delay here
});
$('#md').mouseup(function(e){
clearInterval(timerId);
});
You can do it using a simple semaphore. Here's an example:
var lock = true;
$('#md').mousedown(function() {
lock = false;
setTimeout(function() {
while(!lock) {
// Do your stuff here
}
}, 0);
});
$(document).mouseup(function() {
lock = true;
});
I hope this does the trick.
The setTimeout function detaches the execution of the function and creates an asynchronous process - this makes your code non-blocking.
I'm sure there are more sophisticated ways to solve this problem. It's just that I haven't had my coffee yet. :)
like this? making a global boolean variable to track if mouse is up, then looping your function while mouse is down on that element.
var ismouseup = false;
$(document).ready(function(){
$('#md').mousedown(function(e){
ismouseup = false;
while(!ismouseup)
{
//do your thing
}
});
$('#md').mouseup(function(e){
ismouseup = true;
}
});
--edit: set ismouseup to true when mouseup. sorry.
You can use setTimeout. This will run every 1 sec when mousedown
$('#md').on({
mousedown: function () {
$(this).data('clicked', true);
var process = function() {
if ($(this).data('clicked')) {
// Do your stuff
setTimeout(process, 100);
}
};
process();
},
mouseup: function () {
$(this).data('clicked', false);
}
});
As an option you can set the handler for mousemove in mousedown and remove in mouseup as in code
function movehandler(e) {
var pCords = e.pageY + e.pageY;
var max = $('#md').height();
var dg = 20 * (pCords / max);
$('#md').css({
'transform': 'rotate(' + dg + 'deg) '
});
}
$('#md').mousedown(function (e) {
$('body').on('mousemove', movehandler);
});
$('#md').mouseup(function (e) {
$('body').off('mousemove');
});
$('body').mouseleave(function (e) {
$('body').off('mousemove');
});
Jsfiffle Example is not ideally written but you can get the idea
EDIT: Note that $('body').on('mousemove', might not be sufficient dependent on your markup.
The game is quite simple you click on the start button to begin then move your mouse along the track until you reach the end then the timer stops and shows you the score. If you go out of the track you get a score of zero.
Why don't my mouseOver functions work?
Link to my full code: http://www.codecademy.com/TictacTactic/codebits/AQBK4L/edit
Thank you in advance!
var score = 1000;
var timer = setInterval(countDown(), 1000);
$(document).ready(function() {
$('#start').click(function() {
$('#game').mouseover(function() {
stopTimer();
score = 0
$('#points').html(score)
});
$('#end').mouseover(function() {
stopTimer()
$('#points').html(score)
});
});
});
function countDown() {
score = score - 1;
}
function stopTimer() {
clearInterval(timer);
}
Most events are in lowercase, like mouseover, mouseout etc. There are also others that have capitals, like DOMContentLoaded. Most (if not all) programming languages are case-sensitive, watch out for these.
Try this
var clicked = false;
$('#start').click(function() {
if(!clicked){
clicked = true;
}
});
$("#game").hover(function(){
if(clicked){
stopTimer();
score = 0;
$("#points").html(score);
}
});
$("#end").hover(function(){
if(clicked){
stopTimer();
$("#points").html(score);
}
});
Then later if you don't want the hover event to work just set clicked to false I.E : clicked = false;
I am trying to consecutively add +1 to the value of a text input field when the user clicks a button.
Simplified, my JQuery code is something like this:
$('#button').on({
mousedown : function () {
var value = $(this).val();
$(this).val(value + 1);
},
mouseup : function () {
//Some other stuff here
}
});
This works every time the user clicks the button.
What I want is if the user keeps the button pressed, the mousedown event to fire every 0.2s until he stops pressing (and than the mouseup event fires).
I figure this should somehow be done with setTimeout() but I would be glad if someone showed me how. Thanks.
Use setInterval and clearInterval:
var interval;
$('#button').on({
mousedown : function () {
var el = $(this);
el.val(parseInt(el.val(), 10) + 1);
interval = window.setInterval(function(){
el.val(parseInt(el.val(), 10) + 1);
}, 200);
},
mouseup : function () {
window.clearInterval(interval);
}
});
However, it's not possible to run as often as every 0.2 ms, I suppose that you mean every 0.2 seconds...
You can use setInterval to repeat the event after the mousedown code
var int = null;
$("#button").mousedown(function() {
// Start the timer on mousedown
int = setInterval(function() {
$("#button").val($("#button").val() + 1);
}, 2);
}).mouseup(function() {
// Stop the timer after mouse up
clearInterval(int);
int = null;
// Other code
});
You can achieve this like that:
$('#button').on({
mousedown: function () {
$(this).data('clicked', true);
var self = this;
var process = function() {
if ($(self).data('clicked')) {
console.log("process...");
setTimeout(process, 200);
}
};
process();
},
mouseup: function () {
$(this).data('clicked', false);
}
});