longpress to scroll :mobile - javascript

i have scollable area , i want to user long press and then scroll to scroll that area.
is there any way to detect mouse / touch event movement after long press so that i may do above functionality
see : http://liveweave.com/ggfAdD
please help i am stucked up
belwo i code of longpress, what top add code to make it work where user long press and move up / down
(function($) {
$.fn.longpress = function(longCallback, shortCallback, duration) {
if (typeof duration === "undefined") {
duration = 500;
}
return this.each(function() {
var $this = $(this);
// to keep track of how long something was pressed
var mouse_down_time;
var timeout;
// mousedown or touchstart callback
function mousedown_callback(e) {
mouse_down_time = new Date().getTime();
var context = $(this);
// set a timeout to call the longpress callback when time elapses
timeout = setTimeout(function() {
if (typeof longCallback === "function") {
longCallback.call(context, e);
} else {
$.error('Callback required for long press. You provided: ' + typeof longCallback);
}
}, duration);
}
// mouseup or touchend callback
function mouseup_callback(e) {
var press_time = new Date().getTime() - mouse_down_time;
if (press_time < duration) {
// cancel the timeout
clearTimeout(timeout);
// call the shortCallback if provided
if (typeof shortCallback === "function") {
shortCallback.call($(this), e);
} else if (typeof shortCallback === "undefined") {
;
} else {
$.error('Optional callback for short press should be a function.');
}
}
}
// cancel long press event if the finger or mouse was moved
function move_callback(e) {
clearTimeout(timeout);
}
// Browser Support
$this.on('mousedown', mousedown_callback);
$this.on('mouseup', mouseup_callback);
$this.on('mousemove', move_callback);
// Mobile Support
$this.on('touchstart', mousedown_callback);
$this.on('touchend', mouseup_callback);
$this.on('touchmove', move_callback);
});
};
}(jQuery));

Related

Element.scrollIntoView(); Not working in Chrome and Edge, Works in Firefox?

Let me preface by saying I am relatively green in respect to JavaScript. However, I am trying to create a JavaScript function that will listen for a wheel event, determine the direction of the scroll and scroll the next part of the page into view. Similar to a swipe gesture. I have it working in Firefox as intended, user scrolls down the page moves down, up the page moves up. However, in Chrome and Edge, the element.scrollIntoView() function seems to be called, but nothing happens.
I am using Blazor with JSInterop to get the page to scroll.
Here is the gist of the file:
// scrolldetection.js //
window.scrolldetection {
scrollSetup: function (elementId) {
autoscroller(elementId);
}
}
function autoscroller(elementId) {
// Set up vars
var idList = document.getElementById(elementId).children.id;
var idListIndex = // Gets current index based on current location on page
var curDirection;
document.addEventListener("wheel", function () {
var currentPos = window.scrollY;
if (!curDirection) {
// Check for what direction user scrolls
idListIndex = // Function that determines new index
scrollScreen(idList, idListIndex);
}
var timerId = setTimeout(function () {
curDirection = undefined;
clearTimeout(timerId);
}, 700);
}
}
function scrollScreen(idList, curIndex) {
console.log("list index: " + curIndex);
element = document.getElementById(idList[curIndex]);
console.log(element.id);
element.scrollIntoView({ behavior: 'smooth' });
}
I have another function that calls scrollIntoView() on the same elements, via a button press. Works just fine.
Here is that function:
// anchorlink.js // This one works as intended //
window.anchorlink = {
scrollIntoView: function (elementId) {
var elem = document.getElementById(elementId);
if (elem) {
elem.scrollIntoView({ behavior: 'smooth' });
}
}
}
The console.log() calls within the scrollScreen() function show up properly in the console in each browser. Leading me to believe that element.scrollIntoView() is being called, but something is going wrong to make it not function appropriately. If there is any other information you need, I will be happy to provide, thanks.
After working on this some more, I decided the concept I was using wasn't as user friendly as I had hoped.
I decided to let the user scroll freely along the page and when they stop scrolling, then determine the closest DOM element and scroll to it. Works on Edge, Chrome and Firefox.
window.contentcenter = {
contentCenter: function (elementId) {
var centeringFunction = debounce(function () { autocenter(elementId) }, 200);
document.addEventListener("scroll", centeringFunction);
}
}
function autocenter(elementId) {
var currentElement = detectCurrentElement(elementId);
currentElement.scrollIntoView({ behavior: "smooth" });
}
function detectCurrentElement(elementId) {
var element = document.getElementById(elementId);
var currentPos = window.scrollY;
var contentIdList = getContentIdList(elementId);
var currentElement = closestContent(currentPos, element, contentIdList);
return currentElement;
}
function closestContent(pos, element, contentIdList) {
var contentId = Math.round(pos / (element.offsetHeight / contentIdList.length));
var currentElement = document.getElementById(contentIdList[contentId]);
return currentElement;
}
function getContentIdList(elementId) {
var idList = []
var childElements = document.getElementById(elementId).children;
for (var i = 0; i < childElements.length; i++) {
idList.push(childElements[i].id);
}
return idList;
}
function debounce(func, timeout) {
var timer;
return function () {
var context = this, args = arguments;
var later = function () {
timer = null;
func.apply(context, args);
};
clearTimeout(timer);
timer = setTimeout(later, timeout)
};
}

keyUp is triggering without keyPress

I am trying to have an event trigger if a key is held for a certain amount of time, not doing so if the user releases the key before the interval is over.
const characters = /([AEIOUYNCaeiouync!\\?\\"])/g;
var poppedUp = false;
$(document).ready(function () {
checkLetter();
});
function checkLetter() {
var interval;
$(document).on('keypress', function(e) {
if (interval == null && characters.test(String.fromCharCode(e.keyCode))) {
console.log('keypress');
interval = setInterval(function() {
popUp();
called = true;
}, 400);
}
}).keyup(function(e) {
clearInterval(interval);
console.log('keyup');
poppedUp = false;
interval = null;
});
}
function popUp() {
if (!poppedUp) {
document.querySelector(".modal-popup").style.display = "flex";
poppedUp = true;
}
document.addEventListener('click', function()
{
document.querySelector(".modal-popup").style.display = "none";
});
}
The first time I press a key, the console logs keyPress and keyUp properly. The second time (if I just press and immediately release), it only logs keyUp. This pattern then repeats. Here are the console logs. With two keyup events for every one keypress.

While mousedown JS

I'm trying to run a function while mousedown but for the life of me I can't get it to work while holding down but everything works by just clicking. I'm trying to change color of countries on a map as I hold down.
Here's my code:
var int;
var mouseStillDown = false;
function mousedown(geography)
{ console.log('mousedown '+mousedownID);
mouseStillDown = true;
int = setInterval( performWhileMouseDown(geography), 100);
}
function mouseup()
{
clearInterval(int);
mouseStillDown = false;
}
function mouseout()
{
clearInterval(int);
}
function performWhileMouseDown(geography)
{
if (!mouseStillDown)
{console.log('error');}
if (mouseStillDown) {
if(data[geography.id])
{
data[geography.id] ++;
}else
{
data[geography.id] = 1;
}
var m = {};
m[geography.id] = color(data[geography.id]);
map.updateChoropleth(m);
}
/* if (mouseStillDown)
{ setInterval(performWhileMouseDown(geography), 100); }*/
}
You could try to use mousemove instead, mousedown will only fire once.
var mouseDown = false;
window.addEventListener('mousedown', function() { mouseDown = true })
window.addEventListener('mouseup', function() { mouseDown = false })
window.addEventListener('mousemove', function() {
if (!mouseDown) {
return;
}
// perform while mouse is moving
})
here's what worked for me
var timeout ;
function mouseDown(geography){
timeout = setInterval( function(){
if(data[geography.id]){
data[geography.id] ++;
}else{
data[geography.id] = 1;
}
var m = {};
m[geography.id] = color(data[geography.id]);
map.updateChoropleth(m);}, 100);
return false;
}
function mouseUp(geography){
clearInterval(timeout);
return false;
}
The two conditions for your event are that the code executes every time there is an update in mouse position AND the mouse button is pressed.
Addressing the first part can be done with the 'mousemove' event, which fires when the mouse is moved over the element.
The second filter can be solved, by checking the mouse event, on if the button is pressed. If not, we don't execute the following code.
window.addEventListener('mousemove', function() { // Attach listener
if (event.buttons == 0) // Check event for button
return; // Button not pressed, exit
// perform while mouse is moving
})

setTimeOut + window.onblur+ window.onfocus

I´m trying to use setTimeout to recall a function. When window is not on focus so we will set that function to take a pause until window is on focus again. Let see my script
(function() {
var time = 10000,
delta = 100,
tid;
tid = setInterval(function() {
if ( window.blurred ) { return; }
time -= delta;
if ( time <= 0 ) {
clearInterval(tid);
dosomething (user_id); // function to do something
}
}, delta);
})();
window.onblur = function() { window.blurred = true; };
window.onfocus = function() { window.blurred = false; };
Actually it work as I expected BUT
My question is :
I'm trying to change the method to-----> setTimeout and clearTimeout Why it doesn't work ?
After many test I found that this function doesn't work in IE, do we have any solution ?

Tap event firing X times a second in jquery

I'm trying to make touch controls for a little game I'm writting with the help of jquery. But i just can't figure out how to write a function that basicly does the same thing that happens when you keep a key pressed.
Could you please help me?
PS. its not originaly my code source
jQuery.fn.mousehold = function(timeout, f) {
if (timeout && typeof timeout == 'function') {
f = timeout;
timeout = 100;
}
if (f && typeof f == 'function') {
var timer = 0;
var fireStep = 0;
return this.each(function() {
jQuery(this).mousedown(function() {
fireStep = 1;
var ctr = 0;
var t = this;
timer = setInterval(function() {
ctr++;
f.call(t, ctr);
fireStep = 2;
}, timeout);
})
clearMousehold = function() {
clearInterval(timer);
if (fireStep == 1) f.call(this, 1);
fireStep = 0;
}
jQuery(this).mouseout(clearMousehold);
jQuery(this).mouseup(clearMousehold);
})
}
}
$.fn.extend({
disableSelection: function() {
this.each(function() {
this.onselectstart = function() {
return false;
};
this.unselectable = "on";
$(this).css('-moz-user-select', 'none');
$(this).css('-webkit-user-select', 'none');
});
}
});
Well the question is, how often do you want to check for a change in user input. You are quite limited when it comes to the resolution of a timer in JS. Although be aware that everything is running in sequence and thus events are queued and potentially sum up. This is especially true for setInterval() as it rigorously queues new events, even when previously triggered events were not yet processed.
Something like this works:
var pressed; // flag for continous press between mousedown and timer-events
var duration; // number of times the timer fired for a continous mousedown
var timeout; // reference to timer-event used to reset the timer on mouseup
$(document).mousedown = function(){
pressed = true;
handleMousedown(false);
}
function handleMousedown(continued){
if(pressed){ // if still pressed
if(continued){ // and fired by the timer
duration++;
// measure time, use duration
// do anything
}
timeout = setTimeout('handleMousedown(true)', 100); // wait for another 100ms then repeat
}
}
$(document).mouseup = function() {
// do sth on mouseup
pressed = false; // reset flag for continous mousedown
clearTimeout(timeout); // abandon the timer
}
$(document).mouseout = function() { // $(document).mouseenter = function(){
// do sth on mouse leave or mouse entering again according to how your game should behave
pressed = false; // reset flag for continous mousedown
clearTimeout(timeout); // abandon the timer
}

Categories