Detect the mousemove inside the broswer - javascript

Question:
i would like to detect the mousemove inside the browser. When the mouse stop for 60seconds, the user will log out.
However, i would like to have a iframe (inside the login system) , but it cannot click or mousemove inside the iframe. I don't know what is the problems of iframe. Can any tell me any way to find out the mousemove action? Thank you very much.
<iframe id=iframe src=""></iframe>

http://jsfiddle.net/keshann/oqjgzsm0/518/
Check this fiddle
You can have mouse stop delay detection function as below
(function(mouseStopDelay) {
var timeout;
document.addEventListener('mousemove', function(e) {
clearTimeout(timeout);
timeout = setTimeout(function() {
var event = new CustomEvent("mousestop", {
detail: {
clientX: e.clientX,
clientY: e.clientY
},
bubbles: true,
cancelable: true
});
e.target.dispatchEvent(event);
}, mouseStopDelay);
});
}(1000));
Iframes capture mouse events, but you can transfer the events to the parent scope if the cross-domain policy is satisfied. Here's how:
// This example assumes execution from the parent of the the iframe
function bubbleIframeMouseMove(iframe) {
// Save any previous onmousemove handler
var existingOnMouseMove = iframe.contentWindow.onmousemove;
// Attach a new onmousemove listener
iframe.contentWindow.onmousemove = function(e) {
// Fire any existing onmousemove listener
if (existingOnMouseMove) existingOnMouseMove(e);
// Create a new event for the this window
var evt = document.createEvent("MouseEvents");
// We'll need this to offset the mouse move appropriately
var boundingClientRect = iframe.getBoundingClientRect();
// Initialize the event, copying exiting event values
// for the most part
evt.initMouseEvent(
"mousemove",
true, // bubbles
false, // not cancelable
window,
e.detail,
e.screenX,
e.screenY,
e.clientX + boundingClientRect.left,
e.clientY + boundingClientRect.top,
e.ctrlKey,
e.altKey,
e.shiftKey,
e.metaKey,
e.button,
null // no related element
);
// Dispatch the mousemove event on the iframe element
iframe.dispatchEvent(evt);
};
}
// Get the iframe element we want to track mouse movements on
var myIframe = document.getElementById("iframe");
// Run it through the function to setup bubbling
bubbleIframeMouseMove(myIframe);
At last have a listener
// Example use
document.getElementById('iframe').addEventListener('mousestop', function(e) {
console.log('Mouse coordinates are: ', e.detail.clientX, e.detail.clientY);
document.getElementById("message").innerHTML = 'Mouse coordinates are: ' + e.detail.clientX + ' ' + e.detail.clientY;
// The event will bubble up to parent elements.
});
and your html will be
<iframe id="iframe"></iframe>
<div id="message"></div>

function over() {
console.log("over");
}
<iframe width="300" height="300" src="http://google.com" onMouseOver="over()" />

Well here's some piece of code that does just that,
var logOut = function() {
(timeOut !== undefined)? window.clearTimeout(timeOut): null;
isLoggedIn = false;
document.removeEventListener("mousemove", setTime);
alert("Oops Logged you out");
};
var setTime = function() {
window.clearTimeout(timeOut);
timeOut = window.setTimeout(logOut, maxOut);
};
var timeOut,
isLoggedIn = true,
maxOut = 10000;
if (isLoggedIn === true) {
setTime();
document.addEventListener("mousemove", setTime);
}
Edit:
If you add this then, even if the user moves on Iframe it doesn't matter any more.
document.getElementById("myFrame").addEventListener("mousemove", function(evt) {
evt.preventDefault();
});
and here's the codepen link http://codepen.io/ram333/pen/ygLNQG
Cheers,
Rj

Related

Why couldn't I remove the Listeners?

Hi I write a Whiteboard where you can draw on in vue. I use svg to paint paths. It does work with my EventHandlers, but i want to remove the Handlers, when i make my mouse up. The app should work like, when you click, the Whiteboard gets all Eventhandlers and you can paint a line. When you dont click you dont paint. At the moment i make a undendless line, when i clicked once.
I hope this is understandable :/
Thanks
main() {
// hole whiteboard
let whiteboard = document.getElementById("whiteboard");
const color = "black";
let test2 = event => {
//console.log(event);
this.createSvgElement(whiteboard, color);
this.setup(event);
//alert("Ich bin reich!");
}
whiteboard.addEventListener("mousedown", test2);
},
createSvgElement(w, c){
this.whiteboard.removeEventListener("mousedown", this);
this.whiteboard = w;
this.segments = [];
this.points = [];
this.path = document.createElementNS("http://www.w3.org/2000/svg", "path");
this.path.setAttributeNS(null, "stroke", c);
this.path.setAttributeNS(null, "stroke-width", "2");
this.path.setAttributeNS(null, "fill", "transparent");
//console.log(this.path);
},
setup(event){
this.whiteboard.addEventListener("mousemove", e => {
const [x, y] = this.pos(e);
//console.log(x);
this.points.push({ x, y });
const test = this.path.getAttributeNS(null, "d");
//console.log(test);
this.path.setAttributeNS(null, "d", test + ` L${x},${y}`);
});
this.whiteboard.addEventListener("mouseleave", e =>{
this.whiteboard.removeEventListener("mousemove", this);
this.whiteboard.removeEventListener("mouseup", this);
this.whiteboard.removeEventListener("mouseleave", this);
});
this.whiteboard.addEventListener("mouseup", e =>{
this.whiteboard.removeEventListener("mousemove", this);
this.whiteboard.removeEventListener("mouseup", this);
this.whiteboard.removeEventListener("mouseleave", this);
});
},
pos(e){
const rect = this.whiteboard.getBoundingClientRect();
return [e.clientX - rect.left, e.clientY - rect.top];
},
When you handle the mousedown event for a particular element, you aren't guaranteed to receive the corresponding mouseup event on that same element because the mouse button may be released while the pointer is over a different element, or even outside the window entirely.
The only API to allow you to do this is setCapture, though that is very non-standard.
The recommended way to handle mouse events like this is to attach the mousemove and mouseup events to the document element while the mouse is down on the target element. This works because mouse events will bubble up, and mouseup will be fired on the document even when the pointer is outside the browser window.
Simplified:
const onMouseDown = e => {
document.addEventListener('mousemove', onMouseMove)
document.addEventListener('mouseup', onMouseUp)
}
const onMouseUp = e => {
document.removeEventListener('mousemove', onMouseMove)
document.removeEventListener('mouseup', onMouseUp)
}
const onMouseMove = e => {
// Handle move event
}
this.whiteboard.addEventListener('mousedown', onMouseDown)
You also have an error with the way you are calling removeEventListener:
this.whiteboard.removeEventListener("mousemove", this)
^^^^
The second argument should be the event listener function that you want to remove; this is the component object instance.

Simulate User-Agent click in browser with JS [duplicate]

I'm just wondering how I can use JavaScript to simulate a click on an element.
Currently I have:
function simulateClick(control) {
if (document.all) {
control.click();
} else {
var evObj = document.createEvent('MouseEvents');
evObj.initMouseEvent('click', true, true, window, 1, 12, 345, 7, 220, false, false, true, false, 0, null );
control.dispatchEvent(evObj);
}
}
test 1<br>
<script type="text/javascript">
simulateClick(document.getElementById('mytest1'));
</script>
But it's not working :(
Any ideas?
What about something simple like:
document.getElementById('elementID').click();
Supported even by IE.
[Edit 2022] The answer was really outdated. Modernized it. The original answer is at the bottom.
Use element.dispatchEvent with a freshly created Event of the desired type.
Here's an example using event delegation.
Fork this stackblitz project to play around with it.
// Note: {bubbles: true} because of the event delegation ...
document.addEventListener(`click`, handle);
document.addEventListener(`virtualhover`, handle);
// the actual 'trigger' function
const trigger = (el, etype, custom) => {
const evt = custom ?? new Event( etype, { bubbles: true } );
el.dispatchEvent( evt );
};
// a custom event ;)
const vHover = new CustomEvent(`virtualhover`,
{ bubbles: true, detail: `red` });
setTimeout( _ =>
trigger( document.querySelector(`#testMe`), `click` ), 1000 );
function handle(evt) {
if (evt.target.id === `clickTrigger`) {
trigger(document.querySelector(`#testMe`), `click`);
}
if (evt.type === `virtualhover`) {
evt.target.style.color = evt.detail;
return setTimeout( _ => evt.target.style.color = ``, 1000 );
}
if (evt.target.id === `testMe`) {
document.querySelector(`#testMeResult`)
.insertAdjacentHTML(`beforeend`, `<p>One of us clicked #testMe.
It was <i>${evt.isTrusted ? `<b>you</b>` : `me`}</i>.</p>`);
trigger(
document.querySelector(`#testMeResult p:last-child`),
`virtualhover`,
vHover );
}
}
body {
font: 1.2rem/1.5rem verdana, arial;
margin: 2rem;
}
#testMe {
cursor: pointer;
}
p {
margin: 0.2rem 0;
}
<div id="testMe">
Test me can be clicked
</div>
<p><button id='clickTrigger'>Click #testMe</button></p>
<div id="testMeResult"></div>
The old answer:
Here's what I cooked up. It's pretty simple, but it works:
function eventFire(el, etype){
if (el.fireEvent) {
el.fireEvent('on' + etype);
} else {
var evObj = document.createEvent('Events');
evObj.initEvent(etype, true, false);
el.dispatchEvent(evObj);
}
}
Have you considered using jQuery to avoid all the browser detection? With jQuery, it would be as simple as:
$("#mytest1").click();
var elem = document.getElementById('mytest1');
// Simulate clicking on the specified element.
triggerEvent( elem, 'click' );
/**
* Trigger the specified event on the specified element.
* #param {Object} elem the target element.
* #param {String} event the type of the event (e.g. 'click').
*/
function triggerEvent( elem, event ) {
var clickEvent = new Event( event ); // Create the event.
elem.dispatchEvent( clickEvent ); // Dispatch the event.
}
Reference
https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events
https://codepen.io/felquis/pen/damDA
You could save yourself a bunch of space by using jQuery. You only need to use:
$('#myElement').trigger("click")
The top answer is the best! However, it was not triggering mouse events for me in Firefox when etype = 'click'.
So, I changed the document.createEvent to 'MouseEvents' and that fixed the problem. The extra code is to test whether or not another bit of code was interfering with the event, and if it was cancelled I would log that to console.
function eventFire(el, etype){
if (el.fireEvent) {
el.fireEvent('on' + etype);
} else {
var evObj = document.createEvent('MouseEvents');
evObj.initEvent(etype, true, false);
var canceled = !el.dispatchEvent(evObj);
if (canceled) {
// A handler called preventDefault.
console.log("automatic click canceled");
} else {
// None of the handlers called preventDefault.
}
}
}
Simulating an event is similar to creating a custom event. To simulate a mouse event
we gonna have to create MouseEvent using document.createEvent().
Then using initMouseEvent(), we've to set up the mouse event that is going to occur.
Then dispatched the mouse event on the element on which you'd like to simulate an event.
In the following code, I've used setTimeout so that the button gets clicked automatically after 1 second.
const div = document.querySelector('div');
div.addEventListener('click', function(e) {
console.log('Simulated click');
});
const simulatedDivClick = document.createEvent('MouseEvents');
simulatedDivClick.initEvent(
'click', /* Event type */
true, /* bubbles */
true, /* cancelable */
document.defaultView, /* view */
0, /* detail */
0, /* screenx */
0, /* screeny */
0, /* clientx */
0, /* clienty */
false, /* ctrlKey */
false, /* altKey */
false, /* shiftKey */
0, /* metaKey */
null, /* button */
null /* relatedTarget */
);
// Automatically click after 1 second
setTimeout(function() {
div.dispatchEvent(simulatedDivClick);
}, 1000);
<div> Automatically click </div>
In javascript grab element by its id or class name and then apply .click() to make click happens
like:
document.getElementById("btnHandler").click();
document.getElementById('elementId').dispatchEvent(new MouseEvent("click",{bubbles: true, cancellable: true}));
Follow this link to know about the mouse events using Javascript and browser compatibility for the same
https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent#Browser_compatibility
Honestly none of the answers here worked for my specific case. jquery was out of the question so all those answers are untested. I will say I built this answer up from #mnishiguchi answer above but this was the only thing that actually ended up working.
// select the element by finding the id of mytest1
const el = document.querySelector('#mytest1');
// pass the element to the simulateClick function
simulateClick( el );
function simulateClick(element){
trigger( element, 'mousedown' );
trigger( element, 'click' );
trigger( element, 'mouseup' );
function trigger( elem, event ) {
elem.dispatchEvent( new MouseEvent( event ) );
}
}
Use timeout if the event is not getting triggered
setTimeout(function(){ document.getElementById('your_id').click(); }, 200);
This isn't very well documented, but we can trigger any kinds of events very simply.
This example will trigger 50 double click on the button:
let theclick = new Event("dblclick")
for (let i = 0;i < 50;i++){
action.dispatchEvent(theclick)
}
<button id="action" ondblclick="out.innerHTML+='Wtf '">TEST</button>
<div id="out"></div>
The Event interface represents an event which takes place in the DOM.
An event can be triggered by the user action e.g. clicking the mouse
button or tapping keyboard, or generated by APIs to represent the
progress of an asynchronous task. It can also be triggered
programmatically, such as by calling the HTMLElement.click() method of
an element, or by defining the event, then sending it to a specified
target using EventTarget.dispatchEvent().
https://developer.mozilla.org/en-US/docs/Web/API/Event
https://developer.mozilla.org/en-US/docs/Web/API/Event/Event
document.getElementById("element").click()
Simply select the element from the DOM. The node has a click function, which you can call.
Or
document.querySelector("#element").click()
The solution that worked for me....
Click event can be called on clicking the button or do it from JavaScript file.
In this code either click on the button to show alert or simply call it on some condition or without condition
function ss(){
alert('dddddddddddddddddddddddd');
}
var mybtn=document.getElementById('btn');
mybtn.click();
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
<button id="btn" onclick="ss()">click to see </button>
</body>
</html>
const Discord = require("discord.js");
const superagent = require("superagent");
module.exports = {
name: "hug",
category: "action",
description: "hug a user!",
usage: "hug <user>",
run: async (client, message, args) => {
let hugUser = message.mentions.users.first()
if(!hugUser) return message.channel.send("You forgot to mention somebody.");
let hugEmbed2 = new Discord.MessageEmbed()
.setColor("#36393F")
.setDescription(`**${message.author.username}** hugged **himself**`)
.setImage("https://i.kym-cdn.com/photos/images/original/000/859/605/3e7.gif")
.setFooter(`© Yuki V5.3.1`, "https://cdn.discordapp.com/avatars/489219428358160385/19ad8d8c2fefd03fa0e1a2e49a2915c4.png")
if (hugUser.id === message.author.id) return message.channel.send(hugEmbed2);
const {body} = await superagent
.get(`https://nekos.life/api/v2/img/hug`);
let hugEmbed = new Discord.MessageEmbed()
.setDescription(`**${message.author.username}** hugged **${message.mentions.users.first().username}**`)
.setImage(body.url)
.setColor("#36393F")
.setFooter(`© Yuki V5.3.1`, "https://cdn.discordapp.com/avatars/489219428358160385/19ad8d8c2fefd03fa0e1a2e49a2915c4.png")
message.channel.send(hugEmbed)
}
}

Tracking swipe events with Google Tag Manager

I have a client who wishes to track swipe events (swipe left, swipe right) on a FlexSlider photo gallery. I am using a small script to detect swipe events, and it works quite well to send an alert() or console.log() for testing purposes. However, when I tried to instead push an event to Google Tag Manager it doesn't appear to be sent.
Here is how I am attempting to track the events:
// Previous Photo
jQuery('#photo_gallery').on('swiperight', 'img', function() {
dataLayer.push({'category': 'photo-gallery', 'action' : 'photo-gallery-previous', 'label' : 'previous'});
});
// Next Photo
jQuery('#photo_gallery').on('swipeleft', 'img', function() {
dataLayer.push({'category': 'photo-gallery', 'action' : 'photo-gallery-next', 'label' : 'next'});
});
Where #photo_gallery is the ID of the standard <div class="flexslider"> container.
Here is the script I am using to create the swipeleft swiperight events:
(function($) {
$.detectSwipe = {
enabled: 'ontouchstart' in document.documentElement,
preventDefault: true,
threshold: 20
};
var startX,
startY,
isMoving = false;
function onTouchEnd() {
this.removeEventListener('touchmove', onTouchMove);
this.removeEventListener('touchend', onTouchEnd);
isMoving = false;
}
function onTouchMove(e) {
if ($.detectSwipe.preventDefault) { e.preventDefault(); }
if(isMoving) {
var x = e.touches[0].pageX;
var y = e.touches[0].pageY;
var dx = startX - x;
var dy = startY - y;
var dir;
if(Math.abs(dx) >= $.detectSwipe.threshold) {
dir = dx > 0 ? 'left' : 'right'
} else if(Math.abs(dy) >= $.detectSwipe.threshold) {
dir = dy > 0 ? 'down' : 'up'
}
if(dir) {
onTouchEnd.call(this);
$(this).trigger('swipe', dir).trigger('swipe' + dir);
}
}
}
function onTouchStart(e) {
if (e.touches.length == 1) {
startX = e.touches[0].pageX;
startY = e.touches[0].pageY;
isMoving = true;
this.addEventListener('touchmove', onTouchMove, false);
this.addEventListener('touchend', onTouchEnd, false);
}
}
function setup() {
this.addEventListener && this.addEventListener('touchstart', onTouchStart, false);
}
function teardown() {
this.removeEventListener('touchstart', onTouchStart);
}
$.event.special.swipe = { setup: setup };
$.each(['left', 'up', 'down', 'right'], function () {
$.event.special['swipe' + this] = { setup: function(){
$(this).on('swipe', $.noop);
} };
});
})(jQuery);
Note: The above script works for console logs and alerts
Does anyone have any experience tracking swipe events in Google Analytics/Tag Manager? It would be nice to tap into the FlexSlider built in swipe functionality, but I wouldn't want to modify any of the plugin code.
You should also include an "event" parameter (of, say, "swipe") to use in your GTM trigger:
dataLayer.push({
'event': 'swipe',
// your other parameters
})
Quoting from this: https://developers.google.com/tag-manager/devguide?hl=en
Google Tag Manager provides a special data layer variable called an
event that is used within JavaScript event listeners to initiate tag
firing when a user interacts with website elements such as a button.
You could then use the 'swipe' event to fire your tags.
Not sure if it is still of interest, but as an alternative to dataLayer (best option imho) you may create a "History Change" Trigger.
"Triggers based on the History Change event will fire a tag when the URL fragment (hash) changes or when a site is using the HTML5 pushstate APIs. This trigger is useful to fire tags tracking virtual pageview in an Ajax application, for instance."
https://support.google.com/tagmanager/answer/6106961?hl=en
trigger screenshot

Firing a modal manually that normally fires when a link is clicked

Im working with some JS code, since Im not front developer im having some issues to figuring out how to trigger an event on JS that normally fires when a link is clicked.
This is the link:
Demo
And the JS function that intercept the click on that link is:
(function (global) {
'use strict';
// Storage variable
var modal = {};
// Store for currently active element
modal.lastActive = undefined;
modal.activeElement = undefined;
// Polyfill addEventListener for IE8 (only very basic)
modal._addEventListener = function (element, event, callback) {
if (element.addEventListener) {
element.addEventListener(event, callback, false);
} else {
element.attachEvent('on' + event, callback);
}
};
// Hide overlay when ESC is pressed
modal._addEventListener(document, 'keyup', function (event) {
var hash = window.location.hash.replace('#', '');
// If hash is not set
if (hash === '' || hash === '!') {
return;
}
// If key ESC is pressed
if (event.keyCode === 27) {
window.location.hash = '!';
if (modal.lastActive) {
return false;
}
// Unfocus
modal.removeFocus();
}
}, false);
// Convenience function to trigger event
modal._dispatchEvent = function (event, modal) {
var eventTigger;
if (!document.createEvent) {
return;
}
eventTigger = document.createEvent('Event');
eventTigger.initEvent(event, true, true);
eventTigger.customData = { 'modal': modal };
document.dispatchEvent(eventTigger);
};
// When showing overlay, prevent background from scrolling
modal.mainHandler = function () {
var hash = window.location.hash.replace('#', '');
var modalElement = document.getElementById(hash);
var htmlClasses = document.documentElement.className;
var modalChild;
// If the hash element exists
if (modalElement) {
// Get first element in selected element
modalChild = modalElement.children[0];
// When we deal with a modal and body-class `has-overlay` is not set
if (modalChild && modalChild.className.match(/modal-inner/) &&
!htmlClasses.match(/has-overlay/)) {
// Set an html class to prevent scrolling
//document.documentElement.className += ' has-overlay';
// Mark modal as active
modalElement.className += ' is-active';
modal.activeElement = modalElement;
// Set the focus to the modal
modal.setFocus(hash);
// Fire an event
modal._dispatchEvent('cssmodal:show', modal.activeElement);
}
} else {
document.documentElement.className =
htmlClasses.replace(' has-overlay', '');
// If activeElement is already defined, delete it
if (modal.activeElement) {
modal.activeElement.className =
modal.activeElement.className.replace(' is-active', '');
// Fire an event
modal._dispatchEvent('cssmodal:hide', modal.activeElement);
// Reset active element
modal.activeElement = null;
// Unfocus
modal.removeFocus();
}
}
};
modal._addEventListener(window, 'hashchange', modal.mainHandler);
modal._addEventListener(window, 'load', modal.mainHandler);
/*
* Accessibility
*/
// Focus modal
modal.setFocus = function () {
if (modal.activeElement) {
// Set element with last focus
modal.lastActive = document.activeElement;
// New focussing
modal.activeElement.focus();
}
};
// Unfocus
modal.removeFocus = function () {
if (modal.lastActive) {
modal.lastActive.focus();
}
};
// Export CSSModal into global space
global.CSSModal = modal;
}(window));
How can i call the function that gets called when the user clicks the link but manually on my page, something like <script>firelightbox(parameters);</script>
Using jQuery will solve this easily
$('.selector').click();
but plain old JavaScript may also have a solution for you
Let's just give your anchor element an Id (to keep things simple)
<a id="anchorToBeClicked" href="#modal-text" class="call-modal" title="Clicking this link shows the modal">Demo</a>
Let's create a function that simulates the click
function simulateClick() {
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
var cb = document.getElementById("anchorToBeClicked");
cb.dispatchEvent(evt);
}
Now call this function on window.onload
window.onload = function() {
simulateClick();
};
EDIT:
Actually, the code you are using is not working on actual click event of the anchor tag, instead it relies on hash change of Url in your browser window. You can simply invoke that functionality by using
window.onload = function() {
location.hash = '#modal-text'
};
If you are using jQuery, you can trigger the clicking of a link on page load using this code:
$(document).ready(function(){
$('.call-modal').click();
});

Simulate scroll event using Javascript

I am trying to Simulate a scroll event using Javascript for Mobile Safari.
I am using the following code
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("scroll", true, true, window,0, 0, 0, 0, 0, false, false, false, false, 0, null);
The above code is part of a jQuery plugin jQuery.UI.Ipad which basically maps touch events like touchstart, touchmove, touchend to mouse events like mouseover, mousedown, etc
However for some reasons the code for simulating a scroll event is not working... Please help me. So essentially my question is how do I simulate the scroll event.
I think people are confused as to why you would overide the scroll control. I can see why you want to imitate mouse events, but scroll maybe should not be one of them.
Usually for scroll changes you can just get the scroll with:
var top = document.body.scrollTop;
And set with:
document.body.scrollLeft = sX;
document.body.scrollTop = sY;
So, I know I' need to simulate it too. for me it's when you have a lightbox with a overflow box that you would need it. Just one case of many I can think of. looking to for an answer. Just thought I'd share where I'm at, thou not with the jQuery.Ui.Ipad I will Google that.. but here is what I got so far and does work but not perfectly.
var inTouch=false;
var timers_arr = new Array();
var c=0;
var t;
var timer_is_on=0;
//-------------------------------------------------------------------------------------------------------------------------------------------------------------
// jeremy's timer functions
//-------------------------------------------------------------------------------------------------------------------------------------------------------------
function clearCount(timer){
/// clear the time from timer
clearTimeout(timers_arr[timer]);
/// Make sure it's clear
timers_arr[''+timer+'']=0;
delete timers_arr[''+timer+''];
}
function setCount(timer,time,func){
clearCount(timer);
if(timers_arr[timer]==0||typeof(timers_arr[timer]) === 'undefined'){
timers_arr[timer]=setTimeout(function(){
func();
},time);
}
}
function updatePos(evt,startY){
setCount('touchmove',1,function(){
var orig = evt.originalEvent;
var curY = orig.changedTouches[0].pageY;
var y = curY - startY;
var sliderVal = $("#slider-vertical").slider("value");
sliderVal += (y*.008);
$("#slider-vertical").slider("value", sliderVal);
updatePos(evt,startY);
});
setCount('touchmove_anitMotion',200,function(){
clearCount('touchmove');
clearCount('touchmove_anitMotion');
});
}
var startX=0;
var startY=0;
var x=0;
var y=0;
var direction='';
$('body').bind("onorientationchange", updateOrientation, false);
$('#scroll-pane').live("touchstart", function(evt){
inTouch=true;
startX = event.targetTouches[0].pageX;
startY = event.targetTouches[0].pageY;
});
$('#scroll-pane').live("touchmove", function(evt){
evt.stopPropagation();
evt.preventDefault();
updatePos(evt,startY);
});
$('#scroll-pane').live("touchend", function(evt){
startX=0;
startY=0;
clearCount('touchmove');
inTouch=false;
});
$('#scroll-pane').live("touchcancel", function(evt){
startX=0;
startY=0;
clearCount('touchmove');
inTouch=false;
});
Again not perfect and looking to fix it.. but it's at the least working. Now note, this is a div that is using the jQuery UI slider for a scroll bar as (thou in mine it's vertical) shown in
http://jqueryui.com/demos/slider/#side-scroll
Hope that spurs some ideas. If I get a super stable answer I'll get back.
Cheers -Jeremy
I needed this to write a unit test , for which i need to simulate a scroll event
function dispatchScroll(target,newScrollTop) {
target.scrollTop = newScrollTop;
var e = document.createEvent("UIEvents");
// creates a scroll event that bubbles, can be cancelled,
// and with its view and detail property initialized to window and 1,
// respectively
e.initUIEvent("scroll", true, true, window, 1);
target.dispatchEvent(e);
}
For more details : https://developer.mozilla.org/en-US/docs/Web/API/event.initUIEvent
The event that worked for me was mousewheel, and the 5th parameter needs to be positive for scrolldown and negative for scrollup.
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("mousewheel", true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
Note that the event type is DOMMouseScroll for FireFox.
Events should now be created with CustomEvent as such new CustomEvent("wheel", { detail: { deltaY: 1 } }). document.createEvent is deprecated
https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent
I built this utility function that scrolls by 1 pixel every frame
const startFakeScrolling = (container: HTMLDivElement) => {
const cb = () => {
container.dispatchEvent(
new CustomEvent("wheel", { detail: { deltaY: 1 } })
);
window.requestAnimationFrame(cb);
};
window.requestAnimationFrame(cb);
};
You will also need to modify the event listener to use detail, as deltaY will be undefined
const delta = e.deltaY != null ? e.deltaY : (e.detail as any).deltaY;

Categories