Prevent click event after drag in jQuery - javascript

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
}

Related

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);

I can't get hover or mouseenter to unbind and rebind again

I have tried sooooo many different methods of this that others have suggested, but I don't understand what i'm doing wrong and really need some help. I have tried using various combinations of hover, mouseenter/mouseleave, on/off, bind/unbind.
Basically, I can get things to unbind, but I can't get them to bind again afterwards.
I put together a jsfiddle with a basic example. If you click the "Hover Off" button, mouseenter is disabled like intended. But then if you click the "Hover On" button after, mouseenter does not enable again.
http://jsfiddle.net/770b5p8q/3/
Here is "hover" functionality:
$('.square').each(function(){
$(this).bind("mouseenter", function(){
$(this).addClass('active');
});
$(this).bind("mouseleave", function(){
$(this).removeClass('active');
});
});
Here is what should enable/disable it:
$('.hover_enabled').click(function(){
$('.square').each(function(){
$(this).bind("mouseenter");
$(this).bind("mouseleave");
});
});
$('.hover_disabled').click(function(){
$('.square').each(function(){
$(this).unbind("mouseenter");
$(this).unbind("mouseleave");
});
});
You should pass the function for binding and unbinding the handlers, something like:
var mouseEnterHandler = function () {
$(this).addClass('active');
}
var mouseLeaveHandler = function () {
$(this).removeClass('active');
};
$('.square').bind("mouseenter", mouseEnterHandler)
.bind("mouseleave", mouseLeaveHandler);
$('.hover_enabled').click(function () {
$(this).addClass('active');
$('.hover_disabled').removeClass('active');
// I need to bind hover here
$('.square').bind("mouseenter", mouseEnterHandler)
.bind("mouseleave", mouseLeaveHandler);
});
But the code becomes ugly and unmaintainable. You can use event delegation instead:
$(document).on('mouseenter mouseleave', '.square.hoverable', function(event) {
// toggle the class by checking the type of the event
$(this).toggleClass('active', event.type === 'mouseenter');
});
// caching the state changers
var $e = $('.hover_enabled, .hover_disabled').click(function () {
var $this = $(this).addClass('active'),
isHoverable = $this.hasClass('hover_enabled');
// exclude the clicked element from the set and remove the class
$e.not($this).removeClass('active');
$('.square').toggleClass('hoverable', isHoverable);
});
The above mouseenter mouseleave handler is only executed when the .square element has hoverable className. You can also remove the event handler and use CSS for styling.
.square.hoverable:hover {
}
http://jsfiddle.net/bztec1f4/
Once you rebind it back you need to pass function as well.
$('.hover_enabled').click(function(){
$('.square').each(function(){
$(this).bind("mouseenter", function(){
$(this).addClass('active');
});
$(this).bind("mouseleave", function(){
$(this).removeClass('active');
});
});
});

How to combine Hover, Out, Click event together

var bar = $('.div_layer_Class');
$('a.second_line').click(function() {
$(this).unbind('mouseout');
}).mouseover(function() {
bar.css('display','inline');
}).mouseout(function() {
bar.css('display','none');
});
now the issue with 'onBodyclick' when i click anywhere on body again i want to invoke mouseoutevent something like this
$('body').click(function() {
bar.css('display','none');
event.preventDefault();
});
when I do this it overlaps $('a.second_line').click(function() event. any idea how I can Achieve this.
http://jsfiddle.net/qGJH4/56/
In addition to e.stopPropagation(),
you can do 2 things:
make a variable to reference the mouseout event handler so you can re-bind it whenever the user clicks elsewhere to the body.
or
A variable to store to whether a.second_line is focused or not. Something like
var focused = false;
You code now will be:
var bar = $('.div_layer_Class');
var focused = false;
$('a.second_line').click(function(e) {
focused = true;
e.stopPropagation();
}).mouseover(function() {
bar.css('display','inline');
}).mouseout(function() {
if (!focused)
bar.css('display','none');
});
$(document).click(function(e){
bar.css('display','none');
focused = false;
});
Example here
Try changing your code to this
var bar = $('.div_layer_Class');
$('a.second_line').click(function(e) {
bar.addClass('on');
e.stopPropagation();
}).mouseover(function() {
bar.css('display','inline');
}).mouseout(function() {
if(!bar.hasClass('on'))
bar.css('display','none');
});
$(document).on('click',function(){
bar.removeClass('on');
bar.css('display','none');
//return false;
});
Two lines to look at, first, the e in function(e)
$('a.second_line').click(function(e) {
and the stop e.stopPropagation();
That basically stops any parent handlers being notified. Read here

Javascript hover issues

When I user either jQuery's .hover() or Javascript's mouseenter(), the event triggers not only when the mouse enters the element, but also when the mouse crosses any element within that element. How can I stop this so that it only triggers when the mouse enters or exits that element, with the elements children having no effect on the event?
$(document).ready(function(){
introAnimation();
$('#nav-item1').hover(function() {
$('#createSub').slideDown(300);
});
$('#nav-item1').mouseout(function() {
$('#createSub').slideUp(300);
});
$('#nav-item2').hover(function() {
$('#manageSub').slideDown(300);
});
$('#nav-item2').mouseout(function() {
$('#manageSub').slideUp(300);
});
$('#nav-item3').hover(function() {
$('#storeSub').slideDown(300);
});
$('#nav-item3').mouseout(function() {
$('#storeSub').slideUp(300);
});
});
Hover has a method for unhovering. No need for the mouseout event, which gets fired when you mouse over a nested child element:
$(document).ready(function(){
introAnimation();
$('#nav-item1').hover(function() {
$('#createSub').slideDown(300);
},function() {
$('#createSub').slideUp(300);
});
$('#nav-item2').hover(function() {
$('#manageSub').slideDown(300);
},function() {
$('#manageSub').slideUp(300);
});
$('#nav-item3').hover(function() {
$('#storeSub').slideDown(300);
},function() {
$('#storeSub').slideUp(300);
});
});
add this within the handler:
if( ev.target !== this ){ return; }
ev.target is what the mouse event triggers on. this is what you bound the event to

Preventing click event with jQuery drag and drop

I have elements on the page which are draggable with jQuery. Do these elements have click event which navigates to another page (ordinary links for example).
What is the best way to prevent click from firing on dropping such element while allowing clicking it is not dragged and drop state?
I have this problem with sortable elements but think it is good to have a solution for general drag and drop.
I've solved the problem for myself. After that I found that same solution exists for Scriptaculous, but maybe someone has a better way to achieve that.
A solution that worked well for me and that doesn't require a timeout: (yes I'm a bit pedantic ;-)
I add a marker class to the element when dragging starts, e.g. 'noclick'. When the element is dropped, the click event is triggered -- more precisely if dragging ends, actually it doesn't have to be dropped onto a valid target. In the click handler, I remove the marker class if present, otherwise the click is handled normally.
$('your selector').draggable({
start: function(event, ui) {
$(this).addClass('noclick');
}
});
$('your selector').click(function(event) {
if ($(this).hasClass('noclick')) {
$(this).removeClass('noclick');
}
else {
// actual click event code
}
});
Solution is to add click handler that will prevent click to propagate on start of drag. And then remove that handler after drop is performed. The last action should be delayed a bit for click prevention to work.
Solution for sortable:
...
.sortable({
...
start: function(event, ui) {
ui.item.bind("click.prevent",
function(event) { event.preventDefault(); });
},
stop: function(event, ui) {
setTimeout(function(){ui.item.unbind("click.prevent");}, 300);
}
...
})
Solution for draggable:
...
.draggable({
...
start: function(event, ui) {
ui.helper.bind("click.prevent",
function(event) { event.preventDefault(); });
},
stop: function(event, ui) {
setTimeout(function(){ui.helper.unbind("click.prevent");}, 300);
}
...
})
I had the same problem and tried multiple approaches and none worked for me.
Solution 1
$('.item').click(function(e)
{
if ( $(this).is('.ui-draggable-dragging') ) return false;
});
does nothing for me. The item is being clicked after the dragging is done.
Solution 2 (by Tom de Boer)
$('.item').draggable(
{
stop: function(event, ui)
{
$( event.originalEvent.target).one('click', function(e){ e.stopImmediatePropagation(); } );
}
});
This works just fine but fails in one case- when I was going fullscreen onclick:
var body = $('body')[0];
req = body.requestFullScreen || body.webkitRequestFullScreen || body.mozRequestFullScreen;
req.call(body);
Solution 3 (by Sasha Yanovets)
$('.item').draggable({
start: function(event, ui) {
ui.helper.bind("click.prevent",
function(event) { event.preventDefault(); });
},
stop: function(event, ui) {
setTimeout(function(){ui.helper.unbind("click.prevent");}, 300);
}
})
This does not work for me.
Solution 4- the only one that worked just fine
$('.item').draggable(
{
});
$('.item').click(function(e)
{
});
Yep, that's it- the correct order does the trick- first you need to bind draggable() then click() event. Even when I put fullscreen toggling code in click() event it still didn't go to fullscreen when dragging. Perfect for me!
I'd like to add to this that it seems preventing the click event only works if the click event is defined AFTER the draggable or sortable event. If the click is added first, it gets activated on drag.
I don't really like to use timers or preventing, so what I did is this:
var el, dragged
el = $( '#some_element' );
el.on( 'mousedown', onMouseDown );
el.on( 'mouseup', onMouseUp );
el.draggable( { start: onStartDrag } );
onMouseDown = function( ) {
dragged = false;
}
onMouseUp = function( ) {
if( !dragged ) {
console.log('no drag, normal click')
}
}
onStartDrag = function( ) {
dragged = true;
}
Rocksolid..
lex82's version but for .sortable()
start: function(event, ui){
ui.item.find('.ui-widget-header').addClass('noclick');
},
and you may only need:
start: function(event, ui){
ui.item.addClass('noclick');
},
and here's what I'm using for the toggle:
$("#datasign-widgets .ui-widget-header").click(function(){
if ($(this).hasClass('noclick')) {
$(this).removeClass('noclick');
}
else {
$(this).next().slideToggle();
$(this).find('.ui-icon').toggleClass("ui-icon-minusthick").toggleClass("ui-icon-plusthick");
}
});
A possible alternative for Sasha's answer without preventing default:
var tmp_handler;
.sortable({
start : function(event,ui){
tmp_handler = ui.item.data("events").click[0].handler;
ui.item.off();
},
stop : function(event,ui){
setTimeout(function(){ui.item.on("click", tmp_handler)}, 300);
},
In jQuery UI, elements being dragged are given the class "ui-draggable-dragging".
We can therefore use this class to determine whether to click or not, just delay the event.
You don't need to use the "start" or "stop" callback functions, simply do:
$('#foo').on('mouseup', function () {
if (! $(this).hasClass('ui-draggable-dragging')) {
// your click function
}
});
This is triggered from "mouseup", rather than "mousedown" or "click" - so there's a slight delay, might not be perfect - but it's easier than other solutions suggested here.
In my case it worked like this:
$('#draggable').draggable({
start: function(event, ui) {
$(event.toElement).one('click', function(e) { e.stopPropagation(); });
}
});
After reading through this and a few threads this was the solution I went with.
var dragging = false;
$("#sortable").mouseover(function() {
$(this).parent().sortable({
start: function(event, ui) {
dragging = true;
},
stop: function(event, ui) {
// Update Code here
}
})
});
$("#sortable").click(function(mouseEvent){
if (!dragging) {
alert($(this).attr("id"));
} else {
dragging = false;
}
});
the most easy and robust solution? just create transparent element over your draggable.
.click-passthrough {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
background: transparent;
}
element.draggable({
start: function () {
},
drag: function(event, ui) {
// important! if create the 'cover' in start, then you will not see click events at all
if (!element.find('.click-passthrough').length) {
element.append("<div class='click-passthrough'></div>");
}
},
stop: function() {
// remove the cover
element.find('.click-passthrough').remove();
}
});
Have you tried disabling the link using event.preventDefault(); in the start event and re-enabling it in the drag stopped event or drop event using unbind?
Just a little wrinkle to add to the answers given above. I had to make a div that contains a SalesForce element draggable, but the SalesForce element has an onclick action defined in the html through some VisualForce gobbledigook.
Obviously this violates the "define click action after the drag action" rule, so as a workaround I redefined the SalesForce element's action to be triggered "onDblClick", and used this code for the container div:
$(this).draggable({
zIndex: 999,
revert: true,
revertDuration: 0,
start: function(event, ui) {
$(this).addClass('noclick');
}
});
$(this).click(function(){
if( $(this).hasClass('noclick'))
{
$(this).removeClass('noclick');
}
else
{
$(this).children(":first").trigger('dblclick');
}
});
The parent's click event essentially hides the need to double-click the child element, leaving the user experience intact.
I tried like this:
var dragging = true;
$(this).click(function(){
if(!dragging){
do str...
}
});
$(this).draggable({
start: function(event, ui) {
dragging = true;
},
stop: function(event, ui) {
setTimeout(function(){dragging = false;}, 300);
}
});
for me helped passing the helper in options object as:
.sortable({
helper : 'clone',
start:function(),
stop:function(),
.....
});
Seems cloning dom element that is dragged prevented the bubbling of the event. I couldnĀ“t avoid it with any eventPropagation, bubbling, etc. This was the only working solution for me.
The onmousedown and onmouseup events worked in one of my smaller projects.
var mousePos = [0,0];
function startClick()
{
mousePos = [event.clientX,event.clientY];
}
function endClick()
{
if ( event.clientX != mousePos[0] && event.clientY != mousePos[1] )
{
alert( "DRAG CLICK" );
}
else
{
alert( "CLICK" );
}
}
<img src=".." onmousedown="startClick();" onmouseup="endClick();" />
Yes, I know. Not the cleanest way, but you get the idea.

Categories