Preparing for main Click and Touch Events - javascript

Trying to get the following code to work, a working example presented in jsfiddle will help. The codes for a game that should work on both click hardware and touchscreen hardware.
If there's a way to avoid using an init function that seems to help. Unless you feel like adding an example of how to get a draw function call into the mix somehow.
<p id="Xpos"></p>
<p id="Ypos"></p>
<script>
//############################### Mouse and Touch Events : Start
<!-- Source Code Web Site:
http://blog.patricktresp.de/2012/02/
internet-explorer-8-
and-all-the-fun-stuff-e-stoppropagation-e-preventdefault-mousedown/ -->
var el;
el = document.getElementById('bgLayerMain');
if( el.addEventListener )
{
el.addEventListener('mousedown', onMouseDown, false);
}else if( el.attachEvent ) {
el.attachEvent('onmousedown', onMouseDown);
}
if( is_touch_device() ) {addListeners(); alert("here");}
function stopEvent(e) {
if(!e) var e = window.event;
//e.cancelBubble is supported by IE -
// this will kill the bubbling process.
e.cancelBubble = true;
e.returnValue = false;
//e.stopPropagation works only in Firefox.
if ( e.stopPropagation ) e.stopPropagation();
if ( e.preventDefault ) e.preventDefault();
return false;
}
function addListeners( el )
{// Allow function call without passing parameters
var e = el;
if( !e ) e = document.getElementById('bgLayerMain');
var el = e;
if( el )
{
if( el.addEventListener )
{
el.addEventListener('mouseup', onMouseUp, true);
el.addEventListener('mousemove', onMouseMove, true);
el.addEventListener('touchstart', onTouchStart, true);
el.addEventListener('touchmove', onTouchMove, true);
el.addEventListener('touchend', onTouchEnd, true);
}else if( el.attachEvent ) {
// make sure mouse events have the prefix <strong>on</strong>
el.attachEvent('onmouseup', onMouseUp);
el.attachEvent('onmousemove', onMouseMove);
el.attachEvent('touchstart', onTouchStart);
el.attachEvent('touchmove', onTouchMove);
el.attachEvent('touchend', onTouchEnd);
}
}
}
// also remove the Listeners correctly:
function removeListeners( el ) {
var e = el;
if( !e ) e = document.getElementById('bgLayerMain');
var el = e;
if( el )
{
if( el.removeEventListener )
{
el.removeEventListener('mouseup', onMouseUp);
el.removeEventListener('mousemove', onMouseMove);
el.removeEventListener('touchstart', onTouchStart);
el.removeEventListener('touchmove', onTouchMove);
el.removeEventListener('touchend', onTouchEnd);
}else if( el.detachEvent ) {
el.detachEvent('onmouseup', onMouseUp);
el.detachEvent('onmousemove', onMouseMove);
el.detachEvent('touchstart', onTouchStart);
el.detachEvent('touchmove', onTouchMove);
el.detachEvent('touchend', onTouchEnd);
}
}
}
function onMouseDown(e) {
log('-> mouse down');
addListeners();
e.touches = [{clientX: e.clientX, clientY: e.clientY}];
onTouchStart(e);
stopEvent(e);
}
function onTouchStart(e) {
log('-> touch start');
//do something with e.touches[0].clientX or e.touches[0].clientY
updateMousePos(e.touches[0].clientX,e.touches[0].clientY);
stopEvent(e);
}
function onMouseMove(e) {
log('-> mouse move');
e.touches = [{clientX: e.clientX, clientY: e.clientY}];
onTouchMove(e);
stopEvent(e);
}
function onTouchMove(e) {
log('-> touch move');
//do something with e.touches[0].clientX or e.touches[0].clientY
updateMousePos(e.touches[0].clientX,e.touches[0].clientY);
stopEvent(e);
}
function onMouseUp(e) {
log('-> mouse up');
e.touches = [{clientX: e.clientX, clientY: e.clientY}];
removeListeners();
stopEvent(e);
}
function onTouchEnd(e) {
log('-> touch end');
if( !is_touch_device() ) removeListeners();
}
function log(str) {
var c;
c = document.getElementById('console');
c.innerHTML = str + '
' + c.innerHTML;
}
function is_touch_device() {
return !!('ontouchstart' in window) ? 1 : 0;
}
function updateMousePos(){
//update posX and posY
}
//############################### Mouse and Touch Events : End

Simplified it to the following, perhaps a better way, yet for now works for me.
var clickOrTouchActive = 0;
addEventListener("mousedown", onClickOrTouchStart, false);
addEventListener("touchstart", onClickOrTouchStart, false);
addEventListener("mousemove", onClickOrTouchMove, false);
addEventListener("touchmove", onClickOrTouchMove, false);
addEventListener("mouseup", onClickOrTouchEnd, false);
addEventListener("touchend", onClickOrTouchEnd, false);
function onClickOrTouchStart(e) {
updateMousePos(e.pageX,e.pageY);
tileMouseClicked(e.pageX,e.pageY);
fAngleOfMotion(e.pageX,e.pageY);
clickOrTouchActive = 1;
e.preventDefault();
return false;
}// end function onClickOrTouchStart
function onClickOrTouchMove(e) {
if (clickOrTouchActive == 1){
updateMousePos(e.pageX,e.pageY);
tileMouseClicked(e.pageX,e.pageY);
fAngleOfMotion(e.pageX,e.pageY);
}
e.preventDefault();
return false;
}//end function onClickOrTouchMove
function onClickOrTouchEnd(e) {
updateMousePos(e.pageX,e.pageY);
tileMouseClicked(e.pageX,e.pageY);
fAngleOfMotion(e.pageX,e.pageY);
clickOrTouchActive = 0;
e.preventDefault();
return false;
}// end function onClickOrTouchEnd

Related

How to prevent the user from interrupting window.scrollTo()?

I have a piece of code which uses window.scrollTo(), and I want to stop the user from interrupting the scrolling until it is finished.
let isMoving = false;
const scroll_keys = { 37: 1, 38: 1, 39: 1, 40: 1 };
preventDefault = e => {
console.log(isMoving);
if (!isMoving) return;
e = e || window.event;
if (e.preventDefault) e.preventDefault();
e.returnValue = false;
};
preventDefaultForScrollKeys = e => {
if (!isMoving) return;
if (keys[e.keyCode]) {
preventDefault(e);
return false;
}
};
document.addEventListener('wheel', preventDefault, { passive: false });
document.addEventListener('DOMMouseScroll', preventDefault, { passive: false });
document.addEventListener('scroll', preventDefault, { passive: false });
window.ontouchmove = preventDefault;
document.onkeydown = preventDefaultForScrollKeys;
function scrollTo(offset, callback) {
const onScroll = () => {
const scrollTop = window.scrollTop || window.pageYOffset;
if (scrollTop === offset) {
window.removeEventListener('scroll', onScroll);
callback();
}
};
window.addEventListener('scroll', onScroll);
onScroll();
window.scrollTo({
top: offset,
behavior: 'smooth',
});
}
I set isMoving = true before the call to window.scrollTo, and set it back to false in the callback, like this:
isMoving = true; scrollTo(0, () => { isMoving = false; });
I expect this to completely prevent the user from interrupting the scrolling but it doesn't work properly. It seems to work, but not every time, and it seems quite buggy.

javascript shortcut key / stop Interval function

i make a shortcut key for javascript function . i set the S key for start this and i so set the Z key for clear Interval function but im tired about this and when press Z key the Interval doesnt stop :(
var isCtrl = false;
document.onkeydown=function(e){
if(e.which == 83) {
var elem = document.elementFromPoint( cursorX,cursorY );
elem.addEventListener('click', function() {
console.log('clicked')
}, false);
var support = true;
try {
if (new MouseEvent('click', {bubbles: false}).bubbles !== false) {
support = false;
} else if (new MouseEvent('click', {bubbles: true}).bubbles !== true) {
support = false;
}
} catch (e) {
support = false;
}
var refreshIntervalId = setInterval(function() {
if (support) {
var event = new MouseEvent('click');
}else{
var event = document.createEvent('Event');
event.initEvent('click', true, true);
}
elem.dispatchEvent(event);
},10);
var cursorX;
var cursorY;
cursorX = 0; cursorY = 0;
document.onmousemove = function(e){
cursorX = e.clientX;
cursorY = e.clientY;
elem = document.elementFromPoint(e.clientX, e.clientY);
}
if(e.which == 90) {
clearInterval(refreshIntervalId);
}
}
}
help me i want to press Z key and Interval stop but i can`t ...
UPDATE : this code work correctly . use S key for start and Z key for stop the function .
var elem = document.elementFromPoint( cursorX,cursorY );
elem.addEventListener('click', function() {
console.log('clicked')
}, false);
var support = true;
try {
if (new MouseEvent('click', {bubbles: false}).bubbles !== false) {
support = false;
} else if (new MouseEvent('click', {bubbles: true}).bubbles !== true) {
support = false;
}
} catch (e) {
support = false;
}
var cursorX;
var cursorY;
cursorX = 0; cursorY = 0;
document.onmousemove = function(e){
cursorX = e.clientX;
cursorY = e.clientY;
elem = document.elementFromPoint(e.clientX, e.clientY);
}
var refreshIntervalId;
window.addEventListener("onkeydown", keyDown,true);
window.addEventListener("keydown", keyDown);
function keyDown() {
var e = window.event;
switch (e.keyCode) {
case 83:
start();
break;
case 90:
stop();
break;
}
}
function start() {
stop();
refreshIntervalId = setInterval(function() {
if (support) {
var event = new MouseEvent('click');
}else{
var event = document.createEvent('Event');
event.initEvent('click', true, true);
}
elem.dispatchEvent(event);
},1000);
}
function stop() {
if (refreshIntervalId != null) {
clearInterval(refreshIntervalId);
refreshIntervalId = null;
}
}
You also have to code it in a way to avoid starting the timer more than once. You should construct it more like this (move the var for the timer outside the function):
var refreshIntervalId;
window.addEventListener("onkeydown", keyDown,true);
window.addEventListener("keydown", keyDown);
function keyDown() {
var e = window.event;
switch (e.keyCode) {
case 83:
start();
break;
case 90:
stop();
break;
}
}
function start() {
stop();
refreshIntervalId = setInterval(function() {
// code...
},10);
}
function stop() {
if (refreshIntervalId != null) {
clearInterval(refreshIntervalId);
refreshIntervalId = null;
}
}
You doesn't seem to make an event to listen to keypress.
jQuery:
$(window).keypress(function(e) {
if (e.which == 90) {
clearInterval(refreshIntervalId);
}
});
Vanilla JS:
var keyEvent = function (e) {
if (e.which == 90) {
clearInterval(refreshIntervalId);
}
};
window.addEventListener('keypress', keyEvent);

Showing popup when user leave the window

Here's the code. I need to show pop up window, when user leave the window without using jquery.
Anybody can help?
<script type="text/javascript">
function addEvent(obj, evt, fn) {
if (obj.addEventListener) {
obj.addEventListener(evt, fn, false);
}
else if (obj.attachEvent) {
obj.attachEvent("on" + evt, fn);
}
}
addEvent(window,"load",function(e) {
addEvent(document, "mouseout", function(e) {
e = e ? e : window.event;
var from = e.relatedTarget || e.toElement;
if (!from || from.nodeName == "HTML") {
// stop your drag event here
console.log("leave window");
}
});
});
</script>

Fullcalendar mousewheel event prev next

i'm trying to do a simple think in Fullcalendar ( 1.6.2 ) and is to simulate the prev and next button throught the mouse wheel up and down, similar to google calendar.
Here is the code i'm using, this code is from another question in here i think, but i can´t remember wich one :S
calendar.bind('mousewheel', function(event, delta) {
var view = calendar.fullCalendar('getView');
//alert(view.name); //Can retrieve the view name successfully
//alert(delta); // Undefined
//alert(event); // [Object object]
if (view.name == "month") {
if (delta > 0) {
alert(delta);
calendar.fullCalendar('prev');
}
if (delta < 0) {
alert(delta);
calendar.fullCalendar('next');
}
return false;
}
});
The problem is delta is Undefined
Anyone have a clue what i'm doing wrong? I'm very new to Jquery or Javascript
EDIT
var mousewheelevt=(/Firefox/i.test(navigator.userAgent))? "DOMMouseScroll" : "mousewheel";
// left: 37, up: 38, right: 39, down: 40,
// spacebar: 32, pageup: 33, pagedown: 34, end: 35, home: 36
var keys = [37, 38, 39, 40];
function preventDefault(e) {
e = e || window.event;
if (e.preventDefault)
e.preventDefault();
e.returnValue = false;
}
function keydown(e)
{
for (var i = keys.length; i--;) {
if (e.keyCode === keys[i]) {
preventDefault(e);
return;
}
}
}
function wheel(e) {
preventDefault(e);
}
function disable_scroll()
{
if (window.addEventListener) {
window.addEventListener('DOMMouseScroll', wheel, false);
}
window.onmousewheel = document.onmousewheel = wheel;
document.onkeydown = keydown;
}
function enable_scroll()
{
if (window.removeEventListener) {
window.removeEventListener('DOMMouseScroll', wheel, false);
}
window.onmousewheel = document.onmousewheel = document.onkeydown = null;
}
calendar.bind(mousewheelevt, function(e)
{
var evt=window.event || e;
var delta=evt.detail ? evt.detail*(-120) : evt.wheelDelta;
if(delta > 0){
calendar.fullCalendar('next');
}
if(delta < 0){
calendar.fullCalendar('prev');
}
});
calendar.bind("mouseleave", function()
{
enable_scroll();
});
calendar.bind("mouseenter", function()
{
disable_scroll();
});
Most of this code was copied from the net i have just adapt it to my problem.
This works in Chrome ( latest version ) and I.E ( lastest version )
Doesn´t work in Firefox ( lastest version )
Didn´t check in old versions of any of them.
Can anyone see the problem of not working in FF?
I think i got it, its a bit hacky but it does the trick!!! Any constructive critics are welcome. This is now working in IE, Firefox, Chrome recent versions.
//This checks the browser in use and populates da var accordingly with the browser
var mousewheelevt=(/Firefox/i.test(navigator.userAgent))? "DOMMouseScroll" : "mousewheel";
//Prevents the scroll event for the windows so you cant scroll the window
function preventDefault(e) {
e = e || window.event;
if (e.preventDefault)
e.preventDefault();
e.returnValue = false;
}
//I think this could be eliminated but in the examples i found used it
function wheel(e) {
preventDefault(e);
}
//adds the scroll event to the window
function disable_scroll(){
if (document.attachEvent) //if IE (and Opera depending on user setting)
document.attachEvent("on"+mousewheelevt, wheel);
else if (document.addEventListener) //WC3 browsers
document.addEventListener(mousewheelevt, wheel, false);
}
//removes the scroll event to the window
function enable_scroll()
{
if (document.removeEvent) //if IE (and Opera depending on user setting)
document.removeEvent("on"+mousewheelevt, wheel);
else if (document.removeEventListener) //WC3 browsers
document.removeEventListener(mousewheelevt, wheel, false);
}
//binds the scroll event to the calendar's DIV you have made
calendar.bind(mousewheelevt, function(e){
var evt = window.event || e; //window.event para Chrome e IE || 'e' para FF
var delta;
delta = evt.detail ? evt.detail*(-120) : evt.wheelDelta;
if(mousewheelevt === "DOMMouseScroll"){
delta = evt.originalEvent.detail ? evt.originalEvent.detail*(-120) : evt.wheelDelta;
}
if(delta > 0){
calendar.fullCalendar('next');
}
if(delta < 0){
calendar.fullCalendar('prev');
}
});
//hover event to disable or enable the window scroll
calendar.hover(
function(){
enable_scroll();
console.log("mouseEnter");
},
function(){
disable_scroll();
console.log("mouseLeave");
}
);
//binds to the calendar's div the mouseleave event
calendar.bind("mouseleave", function()
{
enable_scroll();
});
//binds to the calendar's div the mouseenter event
calendar.bind("mouseenter", function()
{
disable_scroll();
});

Scriptaculous draggable on iOS

How would you setup touch events to the draggable class, so that it works on iOS (iPad's, iPhone's, etc)? I have read How can I make a jQuery UI 'draggable()' div draggable for touchscreen?, which has lots of options for jQuery, but not sure how to apply that to Scriptaculous. Any help would be appreciated. Thanks.
You can do it by editing dragdrop.js as mention here:
In Draggables:
register: function(draggable) {
if(this.drags.length == 0) {
this.eventMouseUp = this.endDrag.bindAsEventListener(this);
this.eventMouseMove = this.updateDrag.bindAsEventListener(this);
this.eventKeypress = this.keyPress.bindAsEventListener(this);
Event.observe(document, "mouseup", this.eventMouseUp);
Event.observe(document, "mousemove", this.eventMouseMove);
Event.observe(document, "keypress", this.eventKeypress);
Event.observe(document, "touchstart", this.eventKeypress);
Event.observe(document, "touchmove", this.eventMouseMove);
Event.observe(document, "touchend", this.eventMouseUp);
}
this.drags.push(draggable);
},
unregister: function(draggable) {
this.drags = this.drags.reject(function(d) { return d==draggable });
if(this.drags.length == 0) {
Event.stopObserving(document, "touchstart", this.eventKeypress);
Event.stopObserving(document, "touchmove", this.eventMouseMove);
Event.stopObserving(document, "touchend", this.eventMouseUp);
Event.stopObserving(document, "mouseup", this.eventMouseUp);
Event.stopObserving(document, "mousemove", this.eventMouseMove);
Event.stopObserving(document, "keypress", this.eventKeypress);
}
},
In Draggable:
initialize:
...
this.eventMouseDown = this.initDrag.bindAsEventListener(this);
Event.observe(this.handle, "mousedown", this.eventMouseDown);
Event.observe(this.handle, "touchstart", this.eventMouseDown);
Draggables.register(this);
},
destroy: function() {
Event.stopObserving(this.handle, "mousedown", this.eventMouseDown);
Event.stopObserving(this.handle, "touchstart", this.eventMouseDown);
Draggables.unregister(this);
},
...
initDrag: function(event) {
if(!Object.isUndefined(Draggable._dragging[this.element]) &&
Draggable._dragging[this.element]) return;
if(Event.isLeftClick(event) || event.type == "touchstart") {
Along with editing prototype.js:
function pointerX(event) {
var docElement = document.documentElement,
body = document.body || { scrollLeft: 0 };
if (event.changedTouches) return (event.changedTouches[0].clientX +
(docElement.scrollLeft || body.scrollLeft) -
(docElement.clientLeft || 0));
return event.pageX || (event.clientX +
(docElement.scrollLeft || body.scrollLeft) -
(docElement.clientLeft || 0));
}
function pointerY(event) {
var docElement = document.documentElement,
body = document.body || { scrollTop: 0 };
if (event.changedTouches) return (event.changedTouches[0].clientY +
(docElement.scrollTop || body.scrollTop) -
(docElement.clientTop || 0));
return event.pageY || (event.clientY +
(docElement.scrollTop || body.scrollTop) -
(docElement.clientTop || 0));
}
I think, you have to use parseInt function for X,Y coordinates, because I have some problem with Chrome browser on Android-it put something like 23.45435435345345345345345 to coordinates.
//Add parseInt ----------------[start]
if (event.changedTouches) return (parseInt(event.changedTouches[0].clientY +
(docElement.scrollTop || body.scrollTop) -
(docElement.clientTop || 0),10));
//Add parseInt ----------------[end]

Categories

Resources