+ 1
Hey there, can anyone give me an idea of how to let a function start when a button is clicked and to let it stop when it is released? Thank you!
13 Answers
+ 5
HTML
<button onclick="btnCliker()">Check Click</button>
JS
function btnClicker(){
alert("hello")
}
btnClicker function gets called every time the button is clicked. onclick is the event attribute to register it. If this is what you mean ?
+ 5
Try onmousedown and onmouseup events.
+ 5
<input type = "button" value = "↑" id = "uarr" onmousedown = "Up()" onmouseup = "stopMoving()">
<div id= "playsupport">
<div id= "player"></div>
</div>
<div id = "pos"></div>
<script>
var a;
var y = 0;
var t;
var player = document.getElementById("player");
function Pos(){
a = setInterval(BGPos, 1);
}
function BGPos(){
document.getElementById("pos").innetHTML= "x: " + player.top+ "\ny" + player.bottom;
}
Pos();
function Up(){
t = setInterval("BGUp()", 20);
}
function stopMoving(){
clearInterval(t);
}
function BGUp(){
y += 10;
player.style.bottom = y + "px";
player.style.background = "blue";
}
</script>
Try this code. Up and stopMoving functions are working now.
setTimeout should be replaced with setInterval.
y should be initialized for the player to move.
+ 4
What do you mean by let the function work
+ 4
onmousedown and onmouseup events work. I just tried. Please provide a link to code playground if not working for you.
0
Not really š
. I'm searching for a solution to let a function work WHILE a button is pressed, and to stop it when it's released.
0
It shall do something as long as a certain button is pressed
0
I tried:
<button ontouchstart = "Func()" ontouchend = "StopFunc()">
But it doesn't even call the function
0
I also tried, it doesn't work.
0
http://www.sololearn.com/app/javascript/playground/WCNo2JgLcl92/
It also may not work because the JS is not responding. The "Up()" function is not the only one which doesn't get executed even known it's called. Don't pay attention on the onmouseup events in the HTML code
0
Thank you!
0
Could you please send me the link of your code it doesn't do anything for me