stop function that run with setTimeout - javascript

I want stop my function that run with setTimeout and do not show image followed mouse. I want do that with button click, how do that?
my code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<script type="text/javascript">
var trailimage = ["test.gif", 100, 99];
var offsetfrommouse = [-25, -25];
var displayduration = 0;
function truebody() {
return (!window.opera && document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body;
}
function hidetrail() {
var x = document.getElementById("trailimageid").style;
x.visibility = "hidden";
document.onmousemove = "";
}
function followmouse(e) {
var xcoord = offsetfrommouse[0];
var ycoord = offsetfrommouse[1];
if (typeof e != "undefined") {
xcoord += e.pageX;
ycoord += e.pageY;
}
else if (typeof window.event != "undefined") {
xcoord += truebody().scrollLeft + event.clientX;
ycoord += truebody().scrollTop + event.clientY;
}
var x = document.getElementById("trailimageid").style;
x.left = xcoord + "px";
x.top = ycoord + "px";
}
alert("obj_selected = true");
document.onmousemove = followmouse;
if (displayduration > 0)
setTimeout("hidetrail()", displayduration * 1000);
</script>
</head>
<body>
<form id="form1" runat="server">
<img alt="" id="trailimageid" src="Pictures/sides/sides-not-clicked.gif" border="0" style="position: absolute; visibility: visible; left: 0px;
top: 0px; width: 50px; height: 50px"/>
</form>
</body>
</html>

var foobarTimeout = setTimeout(foobar, 1000);
...
clearTimeout(foobarTimeout);
See:
https://developer.mozilla.org/en/DOM/window.setTimeout
https://developer.mozilla.org/en/DOM/window.clearTimeout

Save the return value of setTimeout, which is a "handle" for the timer, and when you want to cancel it, call clearTimeout with that value.
So in your code, you'd declare a timerHandle variable somewhere appropriate, then set it here:
if (displayduration > 0)
timerHandle = setTimeout("hidetrail()", displayduration * 1000);
...and then create a button click handler:
function cancelTimeoutOnClick() {
if (timerHandle) {
clearTimeout(timerHandle);
timerHandle = 0;
}
}
Off-topic: It's almost never best practice to pass strings into setTimeout, that's an implicit eval. In your case, just pass the function reference:
if (displayduration > 0)
timerHandle = setTimeout(hidetrail, displayduration * 1000);
// ^--- Difference here (no quotes, no parentheses)

you use timeout like >
var myTimeout = setTimeout(yourfunction);
and then you can cancel it >
clearTimeout(myTimeout);

Related

Top attribute won't update. Function only works when I set if function value = to initial top value in javascript

I was working on collision detection and thought I would start out simple by testing when the object reaches a certain x-position. It works when I set it to 100, the initial top value for 'character, which leads me to believe the problem is with top updating; however, I don't see why the circles would be moving if that were the case.If you could tell me how to keep 'top' updated or better yet, help me with collision detection that would be great!
(ps. I know it's not good to put css, javascript, and html in one page. I have this as part of a website but moved it to one file so I could test it separately without looking through the code of the entire website and I will add it in the appropriate files once I get this figured out.)
<html>
<head>
<style>
#character {
position: absolute;
width: 42px;
height: 42px;
background: black;
border-radius: 50%;
}
#character2 {
position: absolute;
width: 42px;
height: 42px;
background: pink;
border-radius: 50%;
} </style>
</head>
<body>
<div id = 'character'></div>
<div id = 'character2'></div>
<script>
var keys = {};
keys.UP = 38;
keys.LEFT = 37;
keys.RIGHT = 39;
keys.DOWN = 40;
keys.W = 87;
keys.A = 65;
keys.D = 68;
keys.S = 83;
/// store reference to character's position and element
var character = {
x: 1000,
y: 100,
speedMultiplier: 1,
element: document.getElementById("character")
};
var character2 = {
x: 100,
y: 100,
speedMultiplier: 3,
element: document.getElementById("character2")
};
/// key detection (better to use addEventListener, but this will do)
document.body.onkeyup =
document.body.onkeydown = function(e){
/// prevent default browser handling of keypresses
if (e.preventDefault) {
e.preventDefault();
}
else {
e.returnValue = false;
}
var kc = e.keyCode || e.which;
keys[kc] = e.type == 'keydown';
};
/// character movement update
var moveCharacter = function(dx, dy){
character.x += (dx||0) * character.speedMultiplier;
character.y += (dy||0) * character.speedMultiplier;
character.element.style.left = character.x + 'px';
character.element.style.top = character.y + 'px';
};
var moveCharacter2 = function(dx, dy){
character2.x += (dx||0) * character2.speedMultiplier;
character2.y += (dy||0) * character2.speedMultiplier;
character2.element.style.left = character2.x + 'px';
character2.element.style.top = character2.y + 'px';
};
/// character control
var detectCharacterMovement = function(){
if ( keys[keys.LEFT] ) {
moveCharacter(-1, 0);
}
if ( keys[keys.RIGHT] ) {
moveCharacter(1, 0);
}
if ( keys[keys.UP] ) {
moveCharacter(0, -1);
}
if ( keys[keys.DOWN] ) {
moveCharacter(0, 1);
}
if ( keys[keys.A] ) {
moveCharacter2(-1, 0);
}
if ( keys[keys.D] ) {
moveCharacter2(1, 0);
}
if ( keys[keys.W] ) {
moveCharacter2(0, -1);
}
if ( keys[keys.S] ) {
moveCharacter2(0, 1);
}
};
/// update current position on screen
moveCharacter();
moveCharacter2();
/// game loop
setInterval(function(){
detectCharacterMovement();
}, 1000/24);
function getPosition() {
var elem = document.getElementById("character");
var top = getComputedStyle(elem).getPropertyValue("top");
if (top == '200px') {
alert ("hi");
}
getPosition()
}
getPosition()
// var pos1 = document.getElementById('character').style.top
</script>
</body>
</html>
I figured it out! I just added Jquery's .position() to get the coordinates! For the collision detection I added this:
function collision1() {
$(document).ready(function(){
var x = $("#character").position();
var y = $("#character2").position();
var zid = '#' + id
var z = $(zid).position();
var topX = parseInt(x.top);
var topZ = parseInt(z.top);
var leftX = parseInt(x.left);
var leftZ = parseInt(z.left);
var topY = parseInt(y.top);
var leftY = parseInt(y.left);
if (topX > topZ && topX < (topZ + 50) && leftX > leftZ && leftX < (leftZ + 100)) {
alert('Player 1 Won! Click restart to play again.')
document.getElementById("button2").style.display = "block";
document.getElementById("def").style.display = "none";
document.getElementById("def2").style.display = "none";
document.getElementById("def3").style.display = "none";
document.getElementById("def4").style.display = "none";
document.getElementById("term").style.display = "none";
}
else {
collision1()}
});}
I know it is probably not the most effective way to program this but it works!

Have to move variable from left to right in Javascript. Professor has up and down as sample

new to javascript and taking a college course for game programming. Only using notepad. Now I have to move an object, in this case just the letter "o" from left to right. My professor provides code for the object going up and down the screen so I tried just to switch the "top" with "left" but it still wont move.
Prof sample:
<!-- Microsoft Edge, IE10/11, FireFox, Chrome -->
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var bH = document.documentElement.clientHeight; // return the browser’s height
function init() {
var m1 = document.getElementById("m1"); // m1 represent m1
var y = parseInt(m1.style.top); // y-coordinate of m1
if (y >= bH) {
y = 0;
} else {
y++;
}
m1.style.top = y + "px";
s1 = setTimeout("init()", 10); // wait 10 milliseconds and then call init
}
window.onload = function () {
init(); // onload event occurs right after a page is loaded
}
</script>
</head>
<body>
<span id="m1" style="position: absolute; top: 0px">o</span>
</body>
</html>
My attempt:
<!-- Chrome -->
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var bW = document.documentElement.clientWidth;
function init() {
var o = document.getElementById("o");
var x = parseInt(o.style.left);
if (x >= bW) {
x = 0;
} else {
x++;
}
o.style.left = x + "px";
s1 = setTimeout("init()", 10);
}
window.onload = function () {
init();
}
</script>
</head>
<body>
<span id="o" style="position: absolute; left: 0px">o</span>
</body>
</html>
Two three mistakes
using ; after window.onload = function(); is wrong
Don't add the function inside " " like s1=setTimeout("init()", 10); (it will work otherwise also, but i can't correctly figure out why not working in your case)
Solution: (js part only)
var bW = document.documentElement.clientWidth;
function init() {
var o = document.getElementById("o");
var x = parseInt(o.style.left);
if (x >= bW){
x = 0;
}
else{
x++;
}
o.style.left = x + "px";
s1=setTimeout(init(), 10);
}
window.onload = function(){
init();
}

Javascript - setInterval() still running after clearInterval() called

I'm making a game with Javascript. I have functions for moving left, right, gravity and down. The gravity function makes the player's location go to the bottom of the screen once it goes off the platform (div). When the gravity() function is called when you are moving right (OnButtonDownr()) it stops the move up from working. What I mean is that when I go right and off the platform and then try to go up it doesn't work but I can go up before I go off the platform. When I try to go up (and it doesn't work) it has a weird effect which looks like its position is being set to 0 but moving up at the same time. My code:
HTML (index.htm):
<html>
<head><link rel='stylesheet' href='style.css'></head>
<body>
<div id='level' class='level'>
<div class='start_platform' id='plat1'></div>
<div class='platform' style='
'></div>
</div>
<img id='player' src='img/player.png' style='height:64px;'></img>
<div class='buttons'>
<button id='moveleft' onmousedown="OnButtonDownl (this)" onmouseup="OnButtonUpl (this)"><--</button>
<button id='moveup' onmousedown="OnButtonDownu (this)" onmouseup="OnButtonUpu (this)">^</button>
<button id='moveright' onmousedown="OnButtonDownr (this)" onmouseup="OnButtonUpr (this)">--></button>
</div>
</body>
<script type='text/javascript' src='scripts/move.js'></script>
<script type='text/javascript' src='scripts/gravity.js'></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</html>
JS (move.js):
//move left
var elem = document.getElementById("player");
function OnButtonDownl (button) {
var posl = parseInt(document.getElementById("player").style.left, 10) || 0;
window.idl = setInterval(framel, 5);
function framel() {
posl--;
elem.style.left = posl + 'px';
gravityCheck();
}}
function OnButtonUpl (button) {
clearInterval(idl);
}
//move right
var elem = document.getElementById("player");
function OnButtonDownr (button) {
var posr = parseInt(document.getElementById("player").style.left, 10) || 0;
window.idr = setInterval(framer, 5);
function framer() {
posr++;
elem.style.left = posr + 'px';
gravityCheck();
}}
function OnButtonUpr (button) {
clearInterval(idr);
}
//move up
var elem = document.getElementById("player");
function OnButtonDownu () {
var posu = parseInt(document.getElementById("player").style.bottom, 10) || 0;
window.idu = setInterval(frameu, 5);
elem.style.bottom = 0;
function frameu() {
gravity = false;
posu++;
elem.style.bottom = posu + 'px';
}}
function OnButtonUpu (button) {
clearInterval(idu);
}
JS (gravity.js):
var gravity = true;
function gravityCheck() {
var player = parseInt(document.getElementById("player").style.left, 10) || 0;
var plat1 = parseInt(document.getElementById("plat1").style.left, 10) || 0;
var width = player - plat1;
var elem = document.getElementById("player");
var pos = parseInt(document.getElementById("player").style.bottom, 10) || 0;
window.id = setInterval(frame, 5);
function frame() {
if(width > 100 && width < 164) {
if(gravity = true) {
pos--;
elem.style.bottom = pos + 'px';
if(elem.style.bottom = 0) {
clear();
}
}
}
}
function clear() {
clearInterval(id);
}}
How do I fix this. Thanks in advance.
You may not be clearing properly. Before setting interval clear any previously set one.
if(window.idl) clearInterval(window.idl);
window.idl = setInterval(framel, 5);

Overlay an iframe on another iframe

I have a javascript code, using which an iframe moves with mouse pointer.
and when I slide mouse over another iframe (e.x youtube embed video), the iframe doesn't move with mouse while mouse pointer is on youtube video.
what can be done? thanks
<script type="text/javascript">
var opacity = 1;
var time = 3500000;
if (document.cookie.indexOf('visited=true') == -1) {
(function openColorBox() {
if ((document.getElementById) && window.addEventListener || window.attachEvent) {
var hairCol = "#ff0000";
var d = document;
var my = -10;
var mx = -10;
var r;
var vert = "";
var idx = document.getElementsByTagName('div').length;
var thehairs = "<iframe id='theiframe' scrolling='no' frameBorder='0' allowTransparency='true' src='b.html' style='margin: px 0px 0px px; position:fixed;width:200px;height:200px;overflow:hidden;border:0;opacity:" + opacity + ";filter:alpha(opacity=" + opacity * 100 + ");'></iframe>";
document.write(thehairs);
var like = document.getElementById("theiframe");
document.getElementsByTagName('body')[0].appendChild(like);
var pix = "px";
var domWw = (typeof window.innerWidth == "number");
var domSy = (typeof window.pageYOffset == "number");
if (domWw) r = window;
else {
if (d.documentElement && typeof d.documentElement.clientWidth == "number" && d.documentElement.clientWidth != 0) r = d.documentElement;
else {
if (d.body && typeof d.body.clientWidth == "number") r = d.body
}
}
if (time != 0) {
setTimeout(function() {
document.getElementsByTagName('body')[0].removeChild(like);
if (window.addEventListener) {
document.removeEventListener("mousemove", mouse, false)
} else if (window.attachEvent) {
document.detachEvent("onmousemove", mouse)
}
}, time)
}
function scrl(yx) {
var y, x;
if (domSy) {
y = r.pageYOffset;
x = r.pageXOffset
} else {
y = r.scrollTop;
x = r.scrollLeft
}
return (yx == 0) ? y : x
}
function mouse(e) {
var msy = (domSy) ? window.pageYOffset : 0;
if (!e) e = window.event;
if (typeof e.pageY == 'number') {
my = e.pageY - 0 - msy;
mx = e.pageX - 0
} else {
my = e.clientY - 6 - msy;
mx = e.clientX - 6
}
vert.top = my + scrl(0) + pix;
vert.left = mx + pix
}
function ani() {
vert.top = my + scrl(0) + pix;
setTimeout(ani, 300)
}
function init() {
vert = document.getElementById("theiframe").style;
ani()
}
if (window.addEventListener) {
window.addEventListener("load", init, false);
document.addEventListener("mousemove", mouse, false)
} else if (window.attachEvent) {
window.attachEvent("onload", init);
document.attachEvent("onmousemove", mouse)
}
}
})();
var oneDay = 1000 * 60 * 30;
var expires = new Date((new Date()).valueOf() + oneDay);
document.cookie = "visited=true;expires=" + expires.toUTCString()
}
</script>
<iframe width="420" height="315" src="https://www.youtube.com/embed/sTesehdHbqs" style="display:block; position:static;"frameborder="0" allowfullscreen></iframe>
Without seeing your HTML, the best guess is: you're not going to be able to do this. The issue is that, once you move your mouse into an iframe that has an origin different from your page, mouse events will not fire out to your script, and therefore you won't be able to update the position of your iframe. DEMO: Note how the mouse coordinates stop updating once you move your mouse pointer inside the iframe.
function mouseMoveListener() {
var outputX = document.querySelector('#mouseX');
var outputY = document.querySelector('#mouseY');
return function(ev) {
outputX.innerText = ev.clientX;
outputY.innerText = ev.clientY;
};
}
function test(ev) {console.log('ev::', ev.clientX);}
document.addEventListener('mousemove', mouseMoveListener());
<div>Mouse position:
<span id="mouseX"></span>
,
<span id="mouseY"></span>
</div>
<iframe src="http://www.example.com" width="200" height="200"></iframe>
If you don't need to let your users interact with the content of the iframe, you can cheat this by overlaying a transparent div on top of the iframe. That prevents mouse events from "falling through" to the iframe beneath them, while still showing the content of the iframe. DEMO: But note that the iframe doesn't allow you to scroll, since mouse events (like clicks on the scroll bar or wheel events) are captured by the overlay div.
function mouseMoveListener() {
var outputX = document.querySelector('#mouseX');
var outputY = document.querySelector('#mouseY');
return function(ev) {
outputX.innerText = ev.clientX;
outputY.innerText = ev.clientY;
};
}
function test(ev) {console.log('ev::', ev.clientX);}
document.addEventListener('mousemove', mouseMoveListener());
#iframe-wrapper {
position: relative;
}
#iframe-wrapper iframe {
position: relative;
z-index: 0;
}
#iframe-wrapper .overlay {
position: absolute;
background: transparent;
top: 0;
left: 0;
bottom: 0;
right: 0;
z-index: 2;
}
<div>Mouse position:
<span id="mouseX"></span>
,
<span id="mouseY"></span>
</div>
<div id="iframe-wrapper">
<iframe src="http://www.example.com" width="200" height="200"></iframe>
<div class="overlay"></div>
</div>
However, if you're displaying a YouTube video, it's unlikely this will satisfy your requirements, since user interaction is a key part of the viewing experience.

javascript on mouse pointer coords

I would like to appear the coordinates x,y from a site on my cursor as it is moving ..
I use the bellow script but it generates a alert box.
<script type=text/javascript>
var isIE = document.all?true:false;
if (!isIE) document.captureEvents(Event.CLICK);
document.onclick = getMousePosition;
function getMousePosition(e) {
var _x;
var _y;
if (!isIE) {
_x = e.pageX;
_y = e.pageY;
}
if (isIE) {
_x = event.clientX + document.body.scrollLeft;
_y = event.clientY + document.body.scrollTop;
}
posX = _x;
posY = _y;
return true;
}
</script>
<body onclick=alert("X-position: "+posX+"; Y-position: "+posY+".")>
I think this is a simpler option..
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
$(document).mousemove(function(e){
$('#status').html(e.pageX +', '+ e.pageY);
});
})
</script>
<body>
<h2 id="status">
0, 0
</h2>
</body>
</html>
http://docs.jquery.com/Tutorials:Mouse_Position#Tracking_mouse_position
This should work:
// Cursor coordinate functions
var myX, myY, xyOn, myMouseX, myMouseY;
xyOn = true;
function getXYPosition(e) {
myMouseX = (e || event).clientX;
myMouseY = (e || event).clientY;
if (document.documentElement.scrollTop > 0) {
myMouseY = myMouseY + document.documentElement.scrollTop;
}
if (xyOn) {
alert("X is " + myMouseX + "\nY is " + myMouseY);
}
}
function toggleXY() {
xyOn = !xyOn;
document.getElementById('xyLink').blur();
return false;
}
document.onmouseup = getXYPosition;
You also need this hidden hyperlink:
Here's the article: http://www.brenz.net/snippets/xy.asp

Categories

Resources