Clearinterval on mouse click or hover - javascript

I have a fullscreen image slider which doesn’t have an autoplay functionality, so I had to write custom script to click on the next button.
Here it is
var interval = setInterval(function() {
document.querySelector('.fp-controlArrow.fp-next').click();
}, 7000);
setTimeout(function( ) { clearInterval( interval ); }, 44000);
But now I’d love to clearInterval whenever user clicks on the button of the same class (.fp-controlArrow.fp-next) . Can the JS distinguish the difference between simulated click and real mouse click somehow? If so, what would be the code for that?
And if not, maybe it is possible to clear interval on hovering the button with the .fp-controlArrow.fp-next class ?
Thanks!

Yes, you can distinguish between a user generated event vs a code generated event by using isTrusted property of the event object in the event listener.
var elem = document.querySelector('.fp-controlArrow.fp-next');
elem.addEventListener("click", function( event ) {
if(event.isTrusted)
clearInterval(interval);
}, false);
https://developer.mozilla.org/en/docs/Web/API/Event/isTrusted

You can use mousedown event for Real click.
var el = document.querySelector('.fp-controlArrow.fp-next')
el.addEventListener('mousedown', function(){
clearInterval( interval );
});
Working example: https://jsfiddle.net/fov47eny/
Also you can use isTrusted but it has limited support on browsers.
if (e.isTrusted) {
/* The event is trusted. */
} else {
/* The event is not trusted. */
}

Related

JQuery - mousedown,mouseup and click on same element

I have a carousel and I need to make him work as Instagram carousel does.
On click change slide, but on mousedown just stop animation. My JQuery :
$(".fancy-carousel").on('mousedown',function (e) {
...stop animation
});
$(".fancy-carousel").on('mouseup',function (e) {
..continue animation
});
$(".fancy-carousel").on('click',function (e) {
..change slide
});
But i don´t know how can i let script know about difference between "click" and "mousedown". When i click on element and hold for a time, it stop animation but after "mouseup" it trigger "click" event too. Is there any way how to split this events? Or should i do it with some calculating of mouse hold time?
A “click” is just a full cycle of a “mousedown” and a “mouseup”. You can’t have one without the other.
For your code to know the difference, you’ll need a variable that tracks your intentions.
Create a variable to track your intention - default it to “click”.
var intention = "click";
In your mousedown function, pause the animation and start a timer. We will use this timer to detect how long the mouse is down for (I.e, if it’s for over a second, it’s not a click and you just want to trigger mouseup)
var detectIntention = setTimeout(function(){
intention = "mouseup";
})
In your mouse up function, cancel this timeout. If mouse up is called after just a few MS, then you want to do a click.
clearTimeout(detectIntention);
if (intention === "mouseup") {
// do mouseup stuff
}
// reset intention
intention = click;
Check in your click function that you wanted to do a click;
if (intention === "click") {
// do click stuff
}

prevent onDocumentMouseDown when clicking a button?

I made a small application where the user can draw.
He can toggle drawing by pressing the corresponding button.
The problem is when drawing is enabled and I want to press the button again to disable it I draw behind the button, this because I start my drawing with the "onDocumentMouseDown" function.
This function is also called when I press the button.
Is there a way to control or fix this?
var button = document.getElementById( 'draw' );
button.addEventListener( 'touchstart', function ( event ) {this.toggleDrawing();}.bind(this), false );
button.addEventListener( 'click', function ( event ) {this.toggleDrawing();}.bind(this), false );
In "toggleDrawing" I change the bool for drawing to false or true.
But like I said, pressing this button also causes my program to draw.
onDocumentMouseDown(event)
{
switch(event.button)
{
case 0:
if(this.canDraw)
{
this.startPos = new THREE.Vector3(event.clientX, event.clientY,0);
this.endPos = new THREE.Vector3(event.clientX, event.clientY,0);
this.startLine();
}
break;
default:
break;
}
}
So how do I click a button and call the function of this button without executing onDocumentMouseDown?
A little difficult to understand, but I think you want to not trigger a mousedown event that is registered on the document when you click inside the button.
If so, register a mousedown handler on the button that stops propagation of that event.
button.addEventListener('mousedown', function(event) {
event.stopPropagation()
}, false);
Otherwise, you could simply exit the drawing function early if the event.target is the draw button.
onDocumentMouseDown(event)
{
if (event.target.id === "draw")
return;
// your code
}
Unrelated side note, instead of .bind() on an anonymous function, you can call it on the method itself, assuming it doesn't mind receiving the event object.
button.addEventListener('click', this.toggleDrawing.bind(this), false);
or just use an arrow function.
button.addEventListener('click', () => this.toggleDrawing(), false);

When I dblclick, it runs .click twice

I have 2 functions when you click on an item, .click and .dblclick
The problem is, that when you dblclick, it runs the .click function twice.
Is there a way to fix this?
$(".item").click(function() {
if (price[this.id] === 1) {
consoleUpdate("This item is worth " +price[this.id]+ " coin");
}
}
$("#fishItem").unbind("dblclick").bind("dblclick").dblclick(function() {
coins = coins+1;
coinUpdate();
invFish1--;
if (invFish1 === 0) {
$("#fishItem").appendTo("#itemStage");
}
});
Per the jQuery documentation for the dblclick event:
It is inadvisable to bind handlers to both the click and dblclick
events for the same element. The sequence of events triggered varies
from browser to browser, with some receiving two click events before
the dblclick and others only one. Double-click sensitivity (maximum
time between clicks that is detected as a double click) can vary by
operating system and browser, and is often user-configurable.
You want to change your events so that you don't have a .click and .dblclick on the same element.
http://api.jquery.com/dblclick/
var cnt=1;
$( "#target" ).click(function(e) {
if(cnt==1)
{
// action on single click if you dont want anything in in single click then use here
e.preventDefault();
}else{
// work on double click
cnt=1;// again set counter
}
cnt++;
});
reference e.preventDefault();
As others mentioned, you can't really bind both click and double click to the same item. There are, however, workarounds.
One way to handle this would be to handle the click code and then check for double-click:
var lastClickTime = 0;
$(".item").click(function() {
var thisClickTime = (new Date).getTime();
if (thisClickTime - lastClickTime < 500) {
//Double-click
}
else {
//Click
}
lastClickTime = thisClickTime;
});
This code essentially captures a "last click time" and if this click time is less than 500 milliseconds from the last click time, then it fires the double-click code. Otherwise it will fire the click code.
The downside with this is that the click-code will be called first and then the double-click code. Also, you're forcing your users into a 500ms double-click. While this is pretty standard, it's not guaranteed. (Slower clickers may have trouble with this.)
A JSFiddle that demonstrates this technique.
You could improve this code by setting a 500ms timeout for the click code and then cancelling the click event if a double-click is fired. The downside with this is that it will force a 500 ms delay between the click and the "click" code.
A JSFiddle that demonstrates the timeout.
If you don't mind handling one single-click, look at the event object details attribute. It is the number of clicks.
$(".item").click(function(event) {
if (event.details === 1) {
//handle single click
} else if (event.details === 2) {
// handle double click
}
}

Javascript mousedown and mouseup on different elements

I am trying to develop a word search game in JS which looks like this : https://jquery-wordsearch-game.googlecode.com/svn/trunk/demo.html
BTW I am not using that guy's plugin and instead, trying to develop on my own.
I am using the following code to fire a handler to highlight the cells when a user clicks and moves over them.
$('#puzzlecontainer').on('mousedown','.block',myHandler);
The problem is that the mousedown event is fired on the first cell only. I want handlers to fire on all cells in the path of the mouse.
Also how can I make this compatible with touch events ? I tried touchmove and touchdown.
Please help
UPDATE
With Shusl's help I added the following code :
var ismosedown = false;
$('#puzzlecontainer').on('vmousedown','.block', function(){
globalvars.ismousedown =true;
$(this).addClass("active");
});
$('#puzzlecontainer').on('vmouseover','.block', function(){
if(globalvars.ismousedown){
$(this).addClass("active");
}
});
$('#puzzlecontainer').on('vmouseup','.block', function(){
globalvars.ismousedown = false;
});
vmouseover works as desired on a desktop browser. But it is not working on my Android phone and tablet. Please help.
Fire a function to add and remove an event to be fired on mouseenter. Add this event when the mouse is down and remove it when mouse is up to stop highlighting...
$('#puzzlecontainer').on('mousedown','.block',startSelect);// Run when down
$('#puzzlecontainer').on('mouseup','.block',stopSelect);// Run when up
function startSelect(){
$('#puzzlecontainer').on('mouseenter','.block',myHandler);//Add Handler on enter.
// Fire the mouseenter event for the current element or it will not highlight.
$(this).trigger('mouseenter');
}
function stopSelect(){
$('#puzzlecontainer').off('mouseenter','.block',myHandler);//Remove Handler because mouseup.
}
You can use mouseover event on each cells and set a flag true in myHandler . check if it is true and then treat it as mousedown event
var ismosedown = false;
$('#puzzlecontainer').on('mousedown','.block', function(){ ismosedown =true; } );
$('allcells').mouseover(function(){
if(ismosedown ){ // do works
}
}).mouseup(function(){
ismosedown = false;
});

Display DIV only if user has been Idle for X amount of time

I would like to display a helpful DIV that basically shows the user how to accomplish something on a particular page, but only if the user has been idle for a period of time, say, 30seconds.
What I mean by "Idle" is:
Not clicking any links
Not right clicking anywhere
Exceptions:
I would like to exclude the following conditions from the Is User Idle rule:
User has scrolled up or down/left or right
User has pressed mouse button on an empty area on the site/ or on an element which has no source/link for example, an image with no hyperlink.
and, Pressing keyboard buttons
Can this be done? Or can we only detect when a particullar event occurs?
Any thoughts/suggestions/resources will be greatly appreciated.
Thank you
fairly basic...
var trigger = 30000
$.(function(){
setInterval('displayInf()',trigger );
$('body').bind('click dblclick keypress mousemove scroll', function(){
clearDisplayInf();
});
});
function displayInf()
{
$('body').append('<div>Your notification div</div>');
}
function clearDisplayInf()
{
trigger = clearInterval(trigger);
trigger = setInterval('displayInf()', 30000 );
}
that should do the trick - you could add some script to make the div removable and start the timer again once its removed but that just polishing up really..
Event in DOM would bubble from leaf to root, thus add a event listener on document would make sense.
But since we are possibiliy stop bubbling for click event in certain element, register click event on document may not work perfectly, in that case, register mousedown and mouseup event would help:
var timer; // create a timer at first
// restart timer on click
function startIdle() {
timer = setTimeout(function() { /* show div */ }, time);
}
if (document.addEventListener) {
document.addEventListener('mouseup', startIdle, false);
}
else {
document.attachEvent('onmouseup', startIdle);
}
// start the first timer
startIdle();

Categories

Resources