I want to make a custom event which I can use like
$('.entry').on('click', function().......
I need it for detecting a longtap for mobile devices. I want to call it like this:
$('.entry').on('longtap', function().......
I read a lot about creating events but the most ways are with bind and trigger. So is there a way to do this?
Here is a way to implement long tap:
var clickStart;
document.getElementById("cool_button").addEventListener('mousedown', function() {
console.log('mouse down');
this.clickStart = new Date().getTime();
});
document.getElementById("cool_button").addEventListener('mouseup', function() {
console.log('mouse up');
if ((new Date().getTime() - this.clickStart) >= 1000) {
console.log('this is a long tap');
}
});
<button id="cool_button">i'm a long tap button</button>
You may use one of the handmade solutions, provided here.
You may attach it as third-party script.
There is a special taphold event for jQuery Mobile.
As said here , you don't need to create a custom event for longtap, you only need js timer and two already exsiting events like mouseup, mousedown:
var pressTimer;
$(".entry").mouseup(function(){
clearTimeout(pressTimer);
// Clear timeout
return false;
}).mousedown(function(){
// Set timeout
pressTimer = window.setTimeout(function() {
console.log("hi!")
},1000);
return false;
});
I made an example for you
https://jsfiddle.net/sOoN92/74rbc2ph/
Related
I want to check if my users arrive at a certain point in my page. SO I created the following JS code:
$(document).on('scroll', function() {
if($(this).scrollTop()>=$('#page2').position().top){
alert("trigger");
}
})
Which checks if the users reached my id="page2". But I want this to trigger ONLY once, no matter if the users goes back up and back down, right now it gets trigger everytime the page2.position().top = scrollTop.
How can I do this ?
You can use event.namespace and off() to unbind event handler after execution of desired statement.
$(document).on('scroll.something', function() {
if ($(this).scrollTop() >= $('#page2').position().top) {
//Do something
//Unbind the event
$(document).off('scroll.something')
}
})
You can use this code to achieve your desired output.
var checkonce = false;
$(document).on('scroll', function() {
if($(this).scrollTop()>=$('#page2').position().top){
if(checkonce == false) {
alert("trigger");
checkonce = true;
}
}
});
You can just off the scroll event on your document after the first scroll has reached.
Edit: Also it would be better if you name your events, Which will help us remove the specific event by using the name. (Satpal already mentioned this in his answer before me, I am improving my answer standard as well.)
$(document).on('scroll.Page2ScrollEvent', function() {
if($(this).scrollTop()>=$('#page2').position().top){
$(this).off('scroll.Page2ScrollEvent'); // remove specific scroll event.
alert("trigger");
}
})
I am creating a phonegap application, but as I came to know that it takes 300MS to trigger click event instead of touchevent.
I don't want to apply both event. Is there any way to know if it's touch device without modernizer.
Here is jquery code for assumption
$('#id').on('click',funciton(e){
alert('id was clicked');
});
is there anyway to do it with pure JS/jQuery as phonegap application already takes more memory I want to use less library as I can.
I mean really you should Modernizr but...
var supportsTouch = 'ontouchstart' in window || navigator.msMaxTouchPoints;
var eventType = supportsTouch ? 'ontouchstart' : 'click';
Then declare your event listeners as such:
$('#id').on(eventType, function(e) {
alert('id was clicked');
});
This should eliminate the 300ms delay and trigger simulated clicks on desktop and touch devices :
$('#id').on('mousedown touchstart', function() {
$(this).one('mouseup touchend', function() {
alert('id was clicked');
});
});
If the item has a link in it (normally triggered by click), it would need some adaptation :
$('#id a').on('mousedown touchstart', function() {
var destination = this.attr('href');
$(this).one('mouseup touchend', function() {
if (destination) window.location = destination;
});
});
Edit - already having an accepted answer, this reply was more of an additional note. But nirmal was correct in the comments that touch devices emulating mouse events might lead to complications. The above code is therefore better suited to use with touch events only.
To be more complete with this answer, I'll post my approach for handling both touch and mouse events simultaneously. Either sequence will then trigger a custom event named page:tap. Listening for these simulated clicks can then be done as follows:
$(subject).on('page:tap', function() { ... });
Mouse and touch events are separated and any emulation triggering additional events is prevented by adding a class to body in between touchend and click, removing it again when the latter occurs.
var root = $('body'), subject = '#example_1, #example_2';
$(document).on('mousedown touchstart', subject, function(e) {
if (e.type == 'mousedown' && e.which != 1) return; // only respond to left clicks
var mean = $(e.currentTarget);
mean.one('mouseup touchend', function(e) {
if (e.type == 'touchend' && !root.hasClass('punch')) root.addClass('punch');
else if (root.hasClass('punch')) return;
mean.trigger('page:tap');
});
})
.on('click', subject, function() {
root.removeClass('punch');
return false;
});
One could also choose to add the class to the active element itself or html for example, that depends a bit on the setup as a whole.
Apply fastclick to your application. You'll find a .js file and a documentation over there. The shortest (jQuery) way of implementing that would be:
$(function() {
FastClick.attach(document.body);
});
If you don't use jQuery, you can choose the other way:
if ('addEventListener' in document) {
document.addEventListener('DOMContentLoaded', function() {
FastClick.attach(document.body);
}, false);
}
Let me know if you need further help!
This is the direct link to the fastclick.js file
You can try:
var clickEvent = ((document.ontouchstart!==null)?'click':'touchstart');
$("#mylink").on(clickEvent, myClickHandler);
for anyone coming here in 2021, use pointers events, and check pointerType to distinguish between mouse, touch, and pen.
I am trying to create a Virtual Keyboard using Javascript and an SVG keyboard image.
I have been able to access the onmousedown property of a 'button' element and make a call to myFunction when that button is pressed.
button.onmousedown = (function(self) {
return function() { self.myFunction(); };
})(this);
I was hoping to add a repeat key feature and want to incorporate setInterval so that myFunction repeats every second or so. I am having trouble incorporating the setInterval into the onmousedown functionality. Should I try to add setInterval to above code or add it to myFunction? I want to use just basic Javascript. Thanks in advance.
var interval;
button.addEventListener('mousedown', function() {
interval = setInterval(doSomething, 20);
});
button.addEventListener('mouseup', function () {
clearInterval(interval);
});
function doSomething()
{
//your code here
}
Something like this?
Live example: http://cssdeck.com/labs/cbpb6qqm
How can one automatically translate long tap events to right click events? Since many touch devices like the iPad don't provide a way to do a right click on a website this would be very handy because a website's code doesn't need to be adjusted.
For example this code is designed for desktop browser having mouse support:
<html>
<head><title>Long tap to right click test</title></head>
<body>
<img src="dummy.png" oncontextmenu="alert('Hi!'); return false;" width="20" height="20" />
</body>
</html>
The goal is to translate a long tap event to the right click event without modifying the code. (Just loading some JavaScript, of course.)
If've seen that https://github.com/furf/jquery-ui-touch-punch/ does something similar for drag'n'drop support on jQuery widgets. However this plugin doesn't support the long tap.
Also http://code.google.com/p/jquery-ui-for-ipad-and-iphone/ does actually perform the desired translation but it brakes scrolling, thus making it useless for regular websites with the need of scroll support.
Any help is appreciated - thanks!
You can write simple plugin to handle this type of events. Lets call it longTap event. Example:
$.fn.longTap = function(options) {
options = $.extend({
delay: 1000,
onRelease: null
}, options);
var eventType = {
mousedown: 'ontouchstart' in window ? 'touchstart' : 'mousedown',
mouseup: 'ontouchend' in window ? 'touchend' : 'mouseup'
};
return this.each(function() {
$(this).on(eventType.mousedown + '.longtap', function() {
$(this).data('touchstart', +new Date);
})
.on(eventType.mouseup + '.longtap', function(e) {
var now = +new Date,
than = $(this).data('touchstart');
now - than >= options.delay && options.onRelease && options.onRelease.call(this, e);
});
});
};
Obviously you want to change mousedown and mouseup to touchstart and touchend in case of iPad.
Usage: http://jsfiddle.net/dfsq/RZgxT/1/
You can use a timeout for that:
var timeoutLongTouch;
var $mydiv = $j('#myDiv');
// Listen to mousedown event
$mydiv.on('mousedown.LongTouch', function () {
timeoutLongTouch = setTimeout(function () {
$mydiv.trigger('contextmenu');
}, 1000);
})
// Listen to mouseup event
.on('mouseup.LongTouch', function () {
// Prevent long touch
clearTimeout(timeoutLongTouch);
});
All solutions not work in desktop browsers.
You should also tune up 'click' handler behaviour, cause all 'longtap' events should also be followed by 'click' event.
In this case something code like this:
itemEl.click(function(event){
if ($(this).data('itemlongtouch')){
$(this).data('itemlongtouch', false);
}else{
//some work
}
});
itemEl.longTap(function(event){
$(this).data('itemlongtouch', true);
//some work
});
Is there a JavaScript or jQuery solution to run a function repeatedly (after setTimeout) while the mouse is over a DOM object? Otherwise said, is there a JavaScript "do while mouseover" (or "if mouseover")?
$('someObject').bind('mouseover', function() {
//Do the following while mouseover
$('someOtherObject').css('margin-left',adjustedLeft + 'px');
setTimeout(/*do it again*/,25);
});
$('someObject').on('mouseenter', function() {
this.iid = setInterval(function() {
// do something
}, 25);
}).on('mouseleave', function(){
this.iid && clearInterval(this.iid);
});
Example Look here
I would solve this issue using the onmouseout event.
Start whatever you intended to do while the mouse is over the specified component on the mouseover event.
When onmouseout event occurs i would stop it.
i use new bind style of jQuery.
$(el).bind({
'mouseenter': function(){console.log('Mouse over');},
'mouseleave': function(){console.log('Mouse leave');}
});
I know this is kind of old, but I think the proper function is already in JavaScript, onmousemove does just that.
OBJ.addEventListener("mouseenter", function() {
focus=true;
});
OBJ.addEventListener("mouseleave", function() {
focus=false;
});
Just in case you don't want to use jquery you can use this :)