javascript on mouse pointer coords - javascript

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

Related

Collision check and moving image with mouse isn't combining properly

I have a code where there is an image following my cursor, with a collision check on divs with a certain class. I also have another code where the mouse follows my cursor, and if my cursor ever gets a little distance away, the image stops following it. Note that I am using jQuery. If I try combining the two codes, the codes both stop properly working. Separately, they work fine. I want to find a way to make it so both codes can be combined and work properly.
From code 1:
function collisionCheck(ax,ay) {
var collide = false;
var aminY = ay;
var aminX = ax;
var amaxX = aminX + $('#image').width();
var amaxY = aminY + $('#image').height();
$('.maze').each(function(){
collide = false;
var bminY = $(this).offset().top - $(window).scrollTop();
var bminX = $(this).offset().left - $(window).scrollLeft();
var bmaxX = bminX + $(this).width();
var bmaxY = bminY + $(this).height();
if (amaxX < bminX) collide = true; // a is left of b
if (aminX > bmaxX) collide = true; // a is right of b
if (amaxY < bminY) collide = true; // a is above b
if (aminY > bmaxY) collide = true; // a is below b
if (!collide) {
return collide;
}
});
return collide;
}
$(document).ready(function(){
$(document).mousemove(function(e) {
startMove = true;
var cursorY = e.pageY;
var cursorX = e.pageX;
if (collisionCheck(cursorX, cursorY)) {
$('html').removeClass('showCursor');
$("#image").css({
left: e.pageX,
top: e.pageY
});
} else {
$('html').addClass('showCursor');
}
});
$("#drop").mouseenter(function(){
alert("Success");
});
});
https://jsfiddle.net/8pc3u7t9/1
From code 2:
var startMove;
$(document).mousemove(function(e) {
var DIFF_SNAP = 10;
var DIFF_UNSNAP = 100;
var difLeft = $('#image').offset().left - e.pageX;
var difTop = $('#image').offset().top - e.pageY;
if (!startMove && Math.abs(difLeft) < DIFF_SNAP && Math.abs(difTop) < DIFF_SNAP) {
startMove = true;
$('html').removeClass('showCursor');
} else if (startMove && !(Math.abs(difLeft) < DIFF_UNSNAP && Math.abs(difTop) < DIFF_UNSNAP)) {
startMove = false;
}
if (startMove) {
$("#image").css({
left: e.pageX,
top: e.pageY
});
} else {
$('html').addClass('showCursor');
}
});
$(document).mouseleave(function() {
startMove = false;
})
https://jsfiddle.net/3x7cgLdr/25/

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.

how to drag and drop a <div> across the page

I am developing an web application where I am trying simulate a popup window using tags , for style purpose. I done this with this javascript code:
<script>
function handleClick(url){
document.getElementById("results").style.display = 'block';
document.getElementById("about").innerHTML='<object type="text/html" data="'+url+'" ></object>';
}
function cleanDiv() {
document.getElementById("results").style.display = 'none';
document.getElementById("about").innerHTML=' ';
}
</script>
associated to this html code:
<section class="about" id="results">
<div align="right">Fechar</div>
<div id="about" algin="center"></div>
</section>
and the style is on my css file.
I have almost all what I want, but I wish this "popup window" don't stay fixed in a unique position on the page, and the user could move it around with the mouse.
Someone knows how to make this with javascript/html/css only?
You are looking for the HTML5 draggable attribute and events. Make the element draggable by setting draggable="true" and ondragstart="dragElem(event)". Then write your code in function dragElem(ev) { }. See W3Schools
After more search, I ended with this code, from site http://waseemblog.com/42/movable-div-using-javascript.html
html:
<section class="about" id="results" style="left: 183px; top: 111px;" onMouseDown="dragStart(event, 'results');">
<div align="right">X</div>
<div id="content" align="center"></div>
</section>
javascript:
function getID(id)
{
return document.getElementById(id);
}
// Global object to hold drag information.
var dragObj = new Object();
function dragStart(event, id) {
var x, y;
dragObj.elNode = getID(id);
// Get cursor position with respect to the page.
try {
x = window.event.clientX + document.documentElement.scrollLeft
+ document.body.scrollLeft;
y = window.event.clientY + document.documentElement.scrollTop
+ document.body.scrollTop;
}
catch (e) {
x = event.clientX + window.scrollX;
y = event.clientY + window.scrollY;
}
// Save starting positions of cursor and element.
dragObj.cursorStartX = x;
dragObj.cursorStartY = y;
dragObj.elStartLeft = parseInt(dragObj.elNode.style.left, 10);
dragObj.elStartTop = parseInt(dragObj.elNode.style.top, 10);
if (isNaN(dragObj.elStartLeft)) dragObj.elStartLeft = 0;
if (isNaN(dragObj.elStartTop)) dragObj.elStartTop = 0;
// Capture mousemove and mouseup events on the page.
try {
document.attachEvent("onmousemove", dragGo);
document.attachEvent("onmouseup", dragStop);
window.event.cancelBubble = true;
window.event.returnValue = false;
}
catch (e) {
document.addEventListener("mousemove", dragGo, true);
document.addEventListener("mouseup", dragStop, true);
event.preventDefault();
}
}
function dragGo(event) {
var x, y;
// Get cursor position with respect to the page.
try {
x = window.event.clientX + document.documentElement.scrollLeft
+ document.body.scrollLeft;
y = window.event.clientY + document.documentElement.scrollTop
+ document.body.scrollTop;
}
catch (e) {
x = event.clientX + window.scrollX;
y = event.clientY + window.scrollY;
}
// Move drag element by the same amount the cursor has moved.
var drLeft = (dragObj.elStartLeft + x - dragObj.cursorStartX);
var drTop = (dragObj.elStartTop + y - dragObj.cursorStartY);
if (drLeft > 0)
{
dragObj.elNode.style.left = drLeft + "px";
}
else
{
dragObj.elNode.style.left = "1px";
}
if (drTop > 0)
{
dragObj.elNode.style.top = drTop + "px";
}
else
{
dragObj.elNode.style.top = "1px";
}
try {
window.event.cancelBubble = true;
window.event.returnValue = false;
}
catch(e){
event.preventDefault();
}
}
function dragStop(event) {
// Stop capturing mousemove and mouseup events.
try {
document.detachEvent("onmousemove", dragGo);
document.detachEvent("onmouseup", dragStop);
}
catch (e) {
document.removeEventListener("mousemove", dragGo, true);
document.removeEventListener("mouseup", dragStop, true);
}
}
It can be bigger than your counterpart using jquery, but I guess it works fine in most browsers available today.

HTML5 edit text on the canvas

I'm trying to create something similar to http://www.listhings.com where you can edit the text within the canvas.
I've read the other post HTML5 Canvas Text Edit . But I don't want to edit the text outside of the canvas. I want to edit the text within the canvas.
I'd appreciate if anyone can point me in the right direction.
Thanks
First, Mohsen correctly points out that when you do context.fillText you are actually "painting a picture of letters" on the canvas. It's not like a word processor!
You can capture the key events on the window and then write the keystrokes out to your canvas.
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/7tXd4/
This example ONLY types lowercase a-z (no capitals, spaces, backspaces, etc)
You will probably want to make more enhancements like these:
Adding more keys (A-Z, 0-9, etc).
Respond to command keys like backspace to remove letters from the keyHistory.
Put a cursor so users know where they are on the line as they type (hint: http://www.html5canvastutorials.com/tutorials/html5-canvas-text-metrics/)
If you allow multi-line text, handle the [enterkey] and move to the new line.
Etc
Here's code just to get you started:
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; padding:20px; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
ctx.font="18px Arial";
var keyHistory="";
window.addEventListener("keyup", keyUpHandler, true);
function addletter(letter){
keyHistory+=letter;
ctx.clearRect(0,0,300,300);
ctx.fillText(keyHistory,20,20);
}
function keyUpHandler(event){
var letters="abcdefghijklmnopqrstuvwxyz";
var key=event.keyCode;
if(key>64 && key<91){
var letter=letters.substring(key-64,key-65);
addletter(letter);
}
}
}); // end $(function(){});
</script>
</head>
<body>
<p>First click in the red canvas below</p><br/>
<p>Then type any lowercase letters from a-z</p><br/>
<canvas id="canvas" width=300 height=100></canvas>
</body>
</html>
fillText() do not create an object or text node that you can edit afterwards. It will fill text on canvas, that means it will leave pixels on canvas.
You can use Canvas libraries like http://kineticjs.com/ to have a single layer for that text so you can erase the layer and retype the text in. Kinect allows you to bind values to layers so you can save the text you have in the layer in a value binded to the layer.
Try this solution https://jsfiddle.net/tabvn/zjyoexf1/
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Canvas Input Element</title>
</head>
<body>
<canvas id="draw" width="500" height="500"></canvas>
<script type="text/javascript">
var canvas = document.getElementById("draw");
var ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
ctx.beginPath();
function Input(text = "", options = {}){
this.text = text;
this.options = Object.assign({width: 250, height: 40, font: "17px Arial", borderWidth: 1, borderColor: "#ccc", padding: 5}, options);
this.position = {x: 10, y: 10};
this.isFocus = false;
this.focusIndex = text.length;
this.isCommandKey = false;
this.selected = false;
this.render = function(){
ctx.clearRect(this.position.x, this.position.y, this.options.width, this.options.height);
ctx.font = this.options.font;
ctx.lineWidth = this.options.borderWidth;
ctx.strokeStyle = this.options.borderColor;
if(this.isFocus){
ctx.strokeStyle = "#000";
}
ctx.rect(this.position.x, this.position.y, this.options.width, this.options.height);
ctx.stroke();
// write text
var str = "";
for(var i = 0; i < this.text.length; i++){
if(!this.selected && this.isFocus && this.focusIndex === i){
str += "|";
}
str += this.text[i];
}
if(!this.selected && this.isFocus && this.focusIndex === this.text.length){
str += "|";
}
if(this.selected){
var _width = ctx.measureText(this.text).width;
ctx.fillStyle = 'rgba(0,0,0,0.5)';
ctx.fillRect(this.position.x + this.options.padding, this.position.y + this.options.padding, _width, parseInt(this.options.font, 17));
}
ctx.fillStyle = "#000";
ctx.fillText(str, this.position.x + this.options.padding, this.position.y + (this.options.height / 2) + this.options.padding);
}
this.handleOnClick = function(e){
let clientX = e.clientX;
let clientY = e.clientY;
if(clientX <= this.position.x + this.options.width && clientX >= this.position.x && clientY <= this.position.y + this.options.height && clientY >= this.position.y){
if(!this.isFocus){
this.isFocus = true;
this.focusIndex = this.text.length;
this.render();
}
}else{
if(this.isFocus){
this.selected = false;
this.isFocus = false;
this.render();
}
}
}
this.handleOnKeyUp = function(e){
this.isCommandKey = false;
this.render();
}
this.handleOnKeyDown = function(e){
if(e.key === "Meta" || e.key === "Control"){
this.isCommandKey = true;
}
if(this.isFocus){
e.preventDefault();
}
if(this.isCommandKey && e.key === "a"){
this.selected = true;
this.render();
return
}
if(this.isFocus && e.key === "Backspace"){
if(this.selected){
this.focusIndex = 0;
this.text = "";
this.selected = false;
this.render();
}
var str = "";
for(var i =0; i < this.text.length; i++){
if(i !== this.focusIndex - 1){
str += this.text[i];
}
}
this.text = str;
this.focusIndex --;
if(this.focusIndex <0){
this.focusIndex = 0;
}
this.render();
}
if(this.isFocus && e.key === "ArrowLeft"){
this.focusIndex --;
if(this.focusIndex < 0){
this.focusIndex = 0;
}
this.render();
}
if(this.isFocus && e.key === "ArrowRight"){
this.focusIndex ++;
if(this.focusIndex > this.text.length){
this.focusIndex = this.text.length;
}
this.render();
}
if(!this.isCommandKey && this.isFocus && (e.keyCode == 32 || (e.keyCode >= 65))){
this.text += e.key;
this.focusIndex = this.text.length;
this.render();
}
}
}
var input = new Input("I 'm an input");
input.render();
window.addEventListener("click", function(event){
input.handleOnClick(event);
});
window.addEventListener("keydown", function(event){
input.handleOnKeyDown(event);
});
window.addEventListener("keyup", function(event){
input.handleOnKeyUp(event);
});
</script>
</body>
</html>

stop function that run with setTimeout

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);

Categories

Resources