Add Easing to Following Image on mouseMove - javascript

I have created an Array of images that load randomly when the page is refreshed and follows the cursor with an onmouseMove function. And fades out after a certain amount of time. You can find a working example here — JSFiddle
I came across another Question which supplied a JSFiddle that allowed the image to follow the cursor as well as adding some easing to it. The overall flow and experience is much more appealing, which is what I'm trying to achieve.
What I would like to know is if it were to possible to implement easing to the design I have created? I've read that there are some easing plug-ins but I feel that my situation might be a little different, but I could be wrong, I am very inexperienced when it comes to JS and jQuery.
Any feedback on how I can achieve this would be appreciated.
JS
(function() {
var pictures = ['http://www.iconsdb.com/icons/preview/white/x-mark-4-xxl.png', 'http://www.iconsdb.com/icons/preview/white/x-mark-xxl.png'];
var selectedPicture = Math.floor(Math.random() * pictures.length);
var randImg = pictures[selectedPicture];
document.onmousemove = handleMouseMove;
function handleMouseMove(event) {
var imgFollow, eventDoc, doc, body, pageX, pageY;
event = event || window.event; // IE-ism
// If pageX/Y aren't available and clientX/Y
// are, calculate pageX/Y - logic taken from jQuery
// Calculate pageX/Y if missing and clientX/Y available
if (event.pageX == null && event.clientX != null) {
eventDoc = (event.target && event.target.ownerDocument) || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = event.clientX +
(doc && doc.scrollLeft || body && body.scrollLeft || 0) -
(doc && doc.clientLeft || body && body.clientLeft || 0);
event.pageY = event.clientY +
(doc && doc.scrollTop || body && body.scrollTop || 0) -
(doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add an image to follow the cursor
var pictures = new Array ('http://www.etamcru.com/pub/img/toolbar_x_icon.png', 'http://www.schultzlawoffice.com/img/icons/blue/arrow-up-50-white.png', 'http://www.fullscope.com/SiteCollectionImages/Icons/White/Right-Arrow-Icon.png');
var selectedPicture = Math.floor(Math.random() * pictures.length);
imgFollow = document.createElement('div');
imgFollow.className = "imgFollow";
imgFollow.style.left = event.pageX + "px";
imgFollow.style.top = event.pageY + "px";
imgFollow.style.backgroundImage = 'url('+ randImg +')';
console.log(randImg);
document.body.appendChild(imgFollow);
setTimeout(function () {
imgFollow.className = "imgFollow fade-out"
}, 200);
}
})();

Related

Creating a keyboard shortcut to change the colour of a soccer/football tracker?

I'm very new to Javascript/HTML and I'm trying to create a manual tracking device for soccer/football games. (By using others examples) I've gotten as far as been able to create a program to track/dot my mouse movements across my screen and record the positional coordinates in the console, yet I'm struggling on 2 issues.
Is there a way to change the colour on my tracker by using keyboard shortcuts to indicate a possession change?
If so, is it also possible to correspond the colour of my tracker/dot the the coordinates in the console for later analysis?
Here's my code so far. Please feel free to rip it apart and edit it however you see fit.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example</title>
<style>
body {
height: 1000px;
}
.dot {
width: 2px;
height: 2px;
background-color: black;
position: absolute;
}
</style>
</head>
<body>
<script>
(function() {
"use strict";
var mousePos;
document.onmousemove = handleMouseMove;
setInterval(getMousePosition, 100); // setInterval repeats every X ms
function handleMouseMove(event) {
var eventDoc, doc, body;
event = event || window.event; // IE-ism
// If pageX/Y aren't available and clientX/Y are,
// calculate pageX/Y - logic taken from jQuery.
// (This is to support old IE)
if (event.pageX == null && event.clientX != null) {
eventDoc = (event.target && event.target.ownerDocument) ||
document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = event.clientX +
(doc && doc.scrollLeft || body && body.scrollLeft || 0) -
(doc && doc.clientLeft || body && body.clientLeft || 0);
event.pageY = event.clientY +
(doc && doc.scrollTop || body && body.scrollTop || 0) -
(doc && doc.clientTop || body && body.clientTop || 0 );
}
mousePos = {
x: event.pageX,
y: event.pageY
};
}
function getMousePosition() {
var pos = mousePos;
console.log("mouse location:", pos);
if (!pos) {
// We haven't seen any movement yet, so don't add a duplicate dot
}
else {
// Use pos.x and pos.y
// Add a dot to follow the cursor
var dot;
dot = document.createElement('div');
dot.className = "dot";
dot.style.left = pos.x + "px";
dot.style.top = pos.y + "px";
document.body.appendChild(dot);
}
}
})();
</script>
</body>
<img src="Soccer_Template.png"></img>
</html>
I'm not sure i understand you're question but i'm going to try an answer.
1 - you can change the color of you're tracker using element.style.background
var dot = document.createElement('div');
dot.style.background = "red"; // Or any color, rgb, HEX you want
2 - It's possible to change the color of you're tracker dynamically to correspond of the coordinates. Just add something like
if(pos.x > 1 && pos.y > 1){
dot.style.background = "red";
}
else{
dot.style.background = "blue";
}
Hope it's helps

How often does a browser poll for mouse location?

var mouseTrack = (function() {
document.onmousemove = handleMouseMove;
function handleMouseMove(event) {
var dot, eventDoc, doc, body, pageX, pageY;
event = event || window.event; // IE-ism
// If pageX/Y aren't available and clientX/Y are,
// calculate pageX/Y - logic taken from jQuery.
// (This is to support old IE)
if (event.pageX == null && event.clientX != null) {
eventDoc = (event.target && event.target.ownerDocument) || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = event.clientX +
(doc && doc.scrollLeft || body && body.scrollLeft || 0) -
(doc && doc.clientLeft || body && body.clientLeft || 0);
event.pageY = event.clientY +
(doc && doc.scrollTop || body && body.scrollTop || 0) -
(doc && doc.clientTop || body && body.clientTop || 0 );
}
console.log(event.pageX + ', ' + event.pageY);
// document.body.innerHTML += '<div style="position:absolute;width:3px;height:3px;background:red;right:'+(window.innerWidth-event.pageX)+'px;top:'+event.pageY+'px;"></div>'
}
});
mouseTrack();
(try this in your browser :) )
If you race the mouse on high sensitivity across the page, you'll only get a coordinate set of like 10-20. If you do it slowly, you'll accumulate hundreds or thousands of points.
How often does a browser (let's say, Chrome) poll for mouse location to fire the mousemove event and even better, where is the source I can look at for this?
It is not the browser that is causing this effect. The browser does not poll the mouse position at all, actually.
It is the scripting engines implementation that takes a certain execution time for each command, thus is only able to compare positions every so many microseconds. If a change is detected an event is raised.
It is impossible to name a specific time here in my eyes, since obviously the execution time of single commands depends on the specific hardware and load of the system you test on.

Check if element is visible for certain percentage on screen (viewport)?

How can i detect if some element is visible? For better understading look at the image below.
I want to fire event when the image is half-visible. It would be great if it would work for all browsers and devices (tablets and smartphones).
Jquery.fracs plugin seems to do exactly what you need.
function callback(fracs: Fractions, previousFracs: Fractions) {
if(fracs > 0.5)
doSomething();
};
var fracs = $("img").fracs(callback);
Your Window is between
$(document).scrollTop()
and
$(document).scrollTop() + $(window).height()
If the
$(element).offset().top
falls between those, it should be visible.
EDIT: I am assuming your element (whose visibility is to be determined) is absolutely positioned. If not, it would be a bit more complicated.
EDIT2: This is only to determine visibility in case of vertical offset. For the horizontal version, replace "scrollTop" with "scrollLeft", "height" with "width" and "top" with "left".
There's a neat plugin, jQuery fracs written specifically for this purpose.
You want to check whether the item is viewable from the bottom of the screen or the top. so the logic would be this:
on window scroll event
if item.y is less than scroll.y, calculate amount off screen
if item.y + item.height is greater than scroll.y + scroll.height, calculate amount off screen
deduct both values off the item.height to find the total off screen
create a percentage of this
So in javascript this would work something like this:
var el = document.getElementById('item1'),
rect = el.getBoundingClientRect(),
item = {
el: el,
x: rect.left,
y: rect.top,
w: el.offsetWidth,
h: el.offsetHeight
};
window.addEventListener('scroll', function (e) {
var deduct = 0,
percentage = 0,
x = window.pageXOffset,
y = window.pageYOffset,
w = window.innerWidth,
h = window.innerHeight;
if (item.y < y) {
deduct += (y - item.y);
}
if ((item.y + item.h) > (y + h)) {
deduct += (item.y + item.h) - (y + h);
}
if (deduct > item.h) {
deduct = item.h;
}
percentage = Math.round(((item.h - deduct) / item.h) * 100);
});
I've excluded the support for older browsers, but if you need it it would be:
x = (window.pageXOffset !== undefined) ? window.pageXOffset : (document.documentElement || document.body.parentNode || document.body).scrollLeft,
y = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop,
w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,
h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
var $w = $(window), wh = $w.height(),
top = $w.scrollTop(), bottom = top + wh,
$img = $("#image"),
imgCenter = $img.offset().top + $img.height()/2;
if (imgCenter >= top && imgCenter < bottom) {
// the image is half-visible
}

How to find out the exact position of the mouse cursor when the user clicks a button in Javascript?

I need to set the top and left px numbers for a div based on this data. How might one go about doing this?
So basically when a user clicks on this element. I have a showcontent function which shows/hides content. But I need to set the top by finding the position of cursor
function ShowContent(d) {
document.getElementById(d).style.display = "block";
}
This example is based on the jQuery javascript library.
$("#button").click(function(e){
alert("X is: "+e.pageX+" \n Y is:"+e.pageY);
});
Online demo here: http://jsfiddle.net/pGdbD/1/
Try clicking in different parts of the button
If you don't use jquery or another lib, you need to look at this page http://www.quirksmode.org/js/events_properties.html to handle it cross browser. It involves the following properties: Event.clientX or Event.pageX
Otherwise jquery's event has a pageX and pageY properties.
Most libraries have something to do this for you.
Ext-Core: Event.getPageX() http://dev.sencha.com/deploy/dev/docs/source/EventManager.html#method-Ext.EventObject-getPageX
jquery: http://api.jquery.com/event.pageX/
You can use the event.pageX and event.pageY properties of the Event object to find out where the mouse was when the event took place. For example:
document.getElementById('yourDiv').addEventListener('click', function(event) {
console.log('X: ' + event.pageX + ' Y: ' + event.pageY);
});
Obviously your actual code would be more complex, using attachEvent for IE, for instance, but this should show you how it's done.
Edit As Juan quite rightly reminds me, pageX/Y are not set in Internet Explorer. The following is adapted from the jQuery source code, and works round this problem:
function(event) {
var x, y;
if ( event.pageX == null && event.clientX != null ) {
var doc = document.documentElement,
body = document.body;
x = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
y = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
} else {
x = event.pageX;
y = event.pageY;
}
console.log('X: ' + x + ' Y: ' + y);
}

Getting javascript mouse position relative to website prefferably without jQuery

I've found this snippet on Ajaxian, but I can't seem to use the cursor.y (or cursor.x) as a variable and when the function is called as such it does not seem to work. Is there a syntax problem or something else?
function getPosition(e) {
e = e || window.event;
var cursor = {x:0, y:0};
if (e.pageX || e.pageY) {
cursor.x = e.pageX;
cursor.y = e.pageY;
}
else {
cursor.x = e.clientX +
(document.documentElement.scrollLeft ||
document.body.scrollLeft) -
document.documentElement.clientLeft;
cursor.y = e.clientY +
(document.documentElement.scrollTop ||
document.body.scrollTop) -
document.documentElement.clientTop;
}
return cursor;
}
I'd preffer not to use jQuery UI if possible, since I've always thaught of jQuery and librarys as a bit of an overkill for most JS programing.
This has always been difficult to achieve cross-browser, but this is about as good as you can get...
<!DOCTYPE html>
<html>
<head>
<title>Javascript Test</title>
<script type="text/javascript">
window.onload = function() {
document.onmousemove = function(e) {
if(!e) e = window.event;
if(e.pageX == null && e.clientX != null) {
var doc = document.documentElement, body = document.body;
e.pageX = e.clientX
+ (doc && doc.scrollLeft || body && body.scrollLeft || 0)
- (doc.clientLeft || 0);
e.pageY = e.clientY
+ (doc && doc.scrollTop || body && body.scrollTop || 0)
- (doc.clientTop || 0);
}
document.getElementById("pos").innerHTML = e.pageX + ", " + e.pageY;
}
}
</script>
</head>
<body>
<h1>Position: <span id="pos">0, 0</span></h1>
</body>
</html>
This snippet must be called inside a mouse event handler, with the event object from the handler.
//edit//Just in case I misunderstood you can not set the mouse's physical position in javascript.
So I found an answer kind of on here so I shall Simply Link to it for study purposes. Show mouse x and y position with javascript
Edited----Wanted to share what worked for me.
This is a form of the code I found at above link I changed slightly. It seems as though I must put certain things to window.onload.
window.onload = function () {
IE = (navigator.appName == "Microsoft Internet Explorer") ? true : false;
if (!IE) {
document.captureEvents(Event.MOUSEMOVE);
document.captureEvents(Event.MOUSEDOWN);
}
document.onmousemove = function (e) {mousePos(e);};
document.onmousedown = function (e) {mouseClicked();};
};
var mouseClick;
var keyClicked;
var mouseX = 0;
var mouseY = 0;
function mousePos (e) {
if (!IE) {
mouseX = e.pageX;
mouseY = e.pageY;
}else{
mouseX = event.clientX + document.body.scrollLeft;
mouseY = event.clientY + document.body.scrollTop;
}
return true;
}

Categories