setInterval cannot clear with mouseup - javascript

I am using mousedown and mouseup to trigger a setInterval function like so:
$("#rotateRight").mousedown(function() {
intervalIRight = setInterval(rotateRight, 0);
}).mouseup(function() {
clearInterval(intervalIRight);
});
This works great, however, if I release the mouse (mouseup) when I am not hovering over $("#rotateRight") then there is technically no 'mouseup' so the interval goes on forever and is never cleared.
I cannot use hover because I want the even to be when a user clicks and holds a mouse. But at the same time, I need to fix this 'mouseup bug.' Any ideas?
UPDATE: New code is as follows, but still does not clear interval because mouseup happens on an iframe, not the DOM.
var intervalIRight;
var intervalILeft;
$("#rotateRight").on('mousedown', function() {
intervalIRight = setInterval(rotateRight, 0);
});
$("#rotateLeft").on('mousedown', function() {
intervalILeft = setInterval(rotateLeft, 0);
});
$(document).on('mouseup', function() {
clearInterval(intervalIRight);
clearInterval(intervalILeft);
});

clear the interval on any mouseup by attaching the event handler to the document.
var intervalIRight;
$("#rotateRight").on('mousedown', function() {
intervalIRight = setInterval(rotateRight, 0);
});
$(document).on('mouseup', function() {
clearInterval(intervalIRight);
});
FIDDLE

Related

keep resizing element while mouse button is down

how to keep resizing an element continiously while mouse button is down?
I tried with mousedown - without success.
$('button').on('mousedown', function(){
let targ = $('.targ');
let x = targ.height();
x++;
targ.height(x);
});
.targ{background:orange;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>PRESS</button>
<br><br>
<div class='targ'>LOREM</div>
you can add an setInterval() to your mousedown event, and clear it on mouseup
here are an working example of setting it to 50 milliseconds:
var interval;
$('button').on({
mousedown: function() {
interval = setInterval(function() {
let targ = $('.targ');
let x = targ.height();
x++;
targ.height(x);
}, 50);
},
mouseup: function() {
window.clearInterval(interval);
}
});
Working fiddle also here: https://jsfiddle.net/qytd5h1n/2/
hope it helps :)
You could keep track of 3 events, 'enabling' the resize function when the mouse is clicked (click), and disabling the resize function with mouseup or mouseleave. Use setInterval to both check whether the mouse click was released or moved out of the element, assigning it (the timeout) to a variable so you can abort it on both of the other events (mouseup and mouseleave)

Creating an event that triggers a second event

I'm trying to create a jQuery event that triggers a second event. The first event is clicking on the emoji id which refers to an image. The second is a mousemove event which moves the image around the page. The third event stops this event when the mouse click happens again anywhere in the body of the page and places the image at that absolute position. I was able to get the second and the third events to work but I can't get the first event to work with the second. Here is what I have so far for my jQuery:
var mouseTracker = function(event) {
console.log(event.pageX, event.pageY, !!event.which)
$('#emoji').css('top', event.pageY);
$('#emoji').css('bottom', event.pageY);
$('#emoji').css('left', event.pageX);
$('#emoji').css('right', event.pageX);
}
var begin = function() {
$('body').on('mousemove', mouseTracker);
$('body').css('cursor', 'none');
}
var stop = function() {
$('body').off('mousemove', mouseTracker);
$('#emoji').css('postion', 'absolute')
$('body').css('cursor', 'default');
}
$('#emoji').on('click', begin);
$('body').on('click', stop);`
Initialize the event from within the first event call.
$('#emoji').on('click', function() {
begin();
$('body').on('click', stop);
});
During the click on #emoji the body click even is also triggered.
That leads to calling stop(). The propagation of that event to body can be blocked by event.stopPropagation() (or equivalent return false from begin()). The propagation should be manually stopped even if body on click handler is attached in begin().
You may want one-time usage of some events. That can be done by binding using .one(). In that case the handler is detached after the first usage without manual .off():
var begin = function (event) {
$('body').on('mousemove', mouseTracker);
$('body').one('click', stop);
$('body').css('cursor', 'none');
return false; // event.stopPropagation();
}
var stop = function () {
$('#emoji').one('click', begin);
$('body').off('mousemove', mouseTracker);
$('#emoji').css('postion', 'absolute')
$('body').css('cursor', 'default');
}
$('#emoji').one('click', begin);

How to prevent mouseenter event action with jQuery

I have this simple mouseenter : mouseleave action:
call = $('.js-call');
call.on({
mouseenter: function(e){
// animation
e.stopPropagation();
},
mouseleave: function(e){
// animation
}
});
In this action i have two CSS animations, which have a duration of 300ms. How can I prevent mouseover event for animation end, and fire it again if i'm properly on call element. When i moving fast on my call element action call many times. How to prevent it? Thx for help.
I would go with placing timeouts on both events, and activate the animation only if at the end of that timeout you still meet a condition. Something like that:
var timeoutIn, timeoutOut, delay = 300;
$element.hover(
function() {
if (timeoutOut){
clearTimeout(timeoutOut);
}
timeoutIn = setTimeout(function() {
// ##################
// 'MOUSEENTER' STUFF GOES HERE
// ##################
}, delay);
},
function() {
if (timeoutIn){
clearTimeout(timeoutIn);
}
timeoutOut = setTimeout(function() {
// ##################
// 'MOUSELEAVE' STUFF GOES HERE
// ##################
}, delay);
}
);
Update: I've just created a jQuery plugin called jQuery.hoverDelay.js, you can check it out here: jQuery hoverDelay.js
what you could do is use .bind( eventType [, eventData ], handler(eventObject) ).
bind the event mouseleave after you're done with the animation and vice versa. this should fix it.
Using jQuery .stop() is the correct approach.
Heres a working fiddle starting and stoping an animation with mouseenter and mousleave, without starting new animation if theres already running one.
http://jsfiddle.net/CZtLe/
function animateMe(element, color) {
element.stop(true).animate({
backgroundColor: color,
duration: 300
});
}
$(function () {
call = $('.js-call');
call.on({
mouseenter: function (e) {
animateMe($(this), '#FF0000');
e.stopPropagation();
},
mouseout: function (e) {
animateMe($(this), '#000000');
}
});
});

Prevent click event after drag in jQuery

I have a draggable <div> with a click event and without any event for drag,
but after I drag <div> the click event is apply to <div>.
How can prevent of click event after drag?
$(function(){
$('div').bind('click', function(){
$(this).toggleClass('orange');
});
$('div').draggable();
});
http://jsfiddle.net/prince4prodigy/aG72R/
FIRST attach the draggable event, THEN the click event:
$(function(){
$('div').draggable();
$('div').click(function(){
$(this).toggleClass('orange');
});
});
Try it here:
http://jsfiddle.net/aG72R/55/
With an ES6 class (No jQuery)
To achieve this in javascript without the help of jQuery you can add and remove an event handler.
First create functions that will be added and removed form event listeners
flagged () {
this.isScrolled = true;
}
and this to stop all events on an event
preventClick (event) {
event.preventDefault();
event.stopImmediatePropagation();
}
Then add the flag when the mousedown and mousemove events are triggered one after the other.
element.addEventListener('mousedown', () => {
element.addEventListener('mousemove', flagged);
});
Remember to remove this on a mouse up so we don't get a huge stack of events repeated on this element.
element.addEventListener('mouseup', () => {
element.removeEventListener('mousemove', flagged);
});
Finally inside the mouseup event on our element we can use the flag logic to add and remove the click.
element.addEventListener('mouseup', (e) => {
if (this.isScrolled) {
e.target.addEventListener('click', preventClick);
} else {
e.target.removeEventListener('click', preventClick);
}
this.isScrolled = false;
element.removeEventListener('mousemove', flagged);
});
In the above example above I am targeting the real target that is clicked, so if this were a slider I would be targeting the image and not the main gallery element. to target the main element just change the add/remove event listeners like this.
element.addEventListener('mouseup', (e) => {
if (this.isScrolled) {
element.addEventListener('click', preventClick);
} else {
element.removeEventListener('click', preventClick);
}
this.isScrolled = false;
element.removeEventListener('mousemove', flagged);
});
Conclusion
By setting anonymous functions to const we don't have to bind them. Also this way they kind of have a "handle" allowing s to remove the specific function from the event instead of the entire set of functions on the event.
I made a solution with data and setTimeout. Maybe better than helper classes.
<div id="dragbox"></div>
and
$(function(){
$('#dragbox').bind('click', function(){
if($(this).data('dragging')) return;
$(this).toggleClass('orange');
});
$('#dragbox').draggable({
start: function(event, ui){
$(this).data('dragging', true);
},
stop: function(event, ui){
setTimeout(function(){
$(event.target).data('dragging', false);
}, 1);
}
});
});
Check the fiddle.
This should work:
$(function(){
$('div').draggable({
start: function(event, ui) {
$(this).addClass('noclick');
}
});
$('div').click(function(event) {
if ($(this).hasClass('noclick')) {
$(this).removeClass('noclick');
}
else {
$(this).toggleClass('orange');
}
});
});
DEMO
You can do it without jQuery UI draggable. Just using common 'click' and 'dragstart' events:
$('div').on('dragstart', function (e) {
e.preventDefault();
$(this).data('dragging', true);
}).on('click', function (e) {
if ($(this).data('dragging')) {
e.preventDefault();
$(this).data('dragging', false);
}
});
You can just check for jQuery UI's ui-draggable-dragging class on the draggable. If it's there, don't continue the click event, else, do. jQuery UI handles the setting and removal of this class, so you don't have to. :)
Code:
$(function(){
$('div').bind('click', function(){
if( $(this).hasClass('ui-draggable-dragging') ) { return false; }
$(this).toggleClass('orange');
});
$('div').draggable();
});
With React
This code is for React users, checked the draggedRef when mouse up.
I didn`t use click event. The click event checked by the mouse up event.
const draggedRef = useRef(false);
...
<button
type="button"
onMouseDown={() => (draggedRef.current = false)}
onMouseMove={() => (draggedRef.current = true)}
onMouseUp={() => {
if (draggedRef.current) return;
setLayerOpened(!layerOpened);
}}
>
BTN
</button>
I had the same problem (tho with p5.js) and I solved it by having a global lastDraggedAt variable, which was updated when the drag event ran. In the click event, I just checked if the last drag was less than 0.1 seconds ago.
function mouseDragged() {
// other code
lastDraggedAt = Date.now();
}
function mouseClicked() {
if (Date.now() - lastDraggedAt < 100)
return; // its just firing due to a drag so ignore
// other code
}

Make div open with your mouse and not click

I have make this: This In the right you see a red button. When you click on the red button. The content screen with the text is coming. But i have a question of this. Can i make this with a other animation. If you hold your mouse. Then you can slide open. With your mouse button to left. Then the content box open. Do you understand it? I hope you can help me.
You can see the code on jsfiddle. And you can change it there. I hope you can help me. I am a starting javascripter. And how And have no idea how I can make this.
To implement dragging, you can make use of mousedown/mouseup/mousemove like this: http://jsfiddle.net/pimvdb/25y4K/8/.
$(function () {
"use strict";
var box = $(".what-is-delicious"),
button = $(".what-is-delicious > a");
var mouseDown = false,
grabbed = 0,
start = -303;
button.mousedown(function(e) {
mouseDown = true;
$('*').bind('selectstart', false); // prevent selections when dragging
grabbed = e.pageX; // save where you grabbed
$("body").append('<div class="background-overlay"></div>');
});
$('body').mouseup(function() {
mouseDown = false;
$('*').unbind('selectstart', false); // allow selections again
$(".background-overlay").remove();
start = parseInt(box.css('right'), 10); // save start for next time
// (parseInt to remove 'px')
}).mousemove(function (e) {
if(mouseDown) { // only if you are dragging
// set right to grabbed - pageX (difference) + start 'right' when started
// dragging. And if you drag too far, set it to 0.
box.css("right", Math.min(grabbed - e.pageX + start, 0));
}
});
});
Here is an updated fiddle. Basically I just did a couple of things:
Changed the handler from "click" to "mouseenter"
Added a "mouseleave" handler that does the opposite thing
Put the handlers on the "what-is-delicious" container instead of the <a>
The code:
$(function () {
"use strict"
var box = $(".what-is-delicious"),
button = $(".what-is-delicious > a");
box.mouseenter(function (e) {
e.preventDefault();
if ($(button).hasClass("open")) {
} else {
$("body").append('<div class="background-overlay"></div>');
button.addClass("open");
box.animate({ right: "0"}, 750);
}
}).mouseleave(function (e) {
e.preventDefault();
if ($(button).hasClass("open")) {
$("body").find('div.background-overlay').remove();
button.removeClass("open");
box.animate({ right: -303}, 750);
} else {
}
});
});
The "preventDefault()" calls aren't really necessary anymore but I left them there.
I would assume you are toggling the Style.Display of the DIV currently in an OnClick() event.
The same code can be called from a Hover() or MouseOver()

Categories