Saritha Ks
Saritha Ks

Reputation: 89

Click event triggering after dragging a button

I have a button with click event and I want to make that button draggable. What I did was,

$(function() {
$( "#btn-1834" ).draggable({
        cancel: false
    });
});

This is the script for dragging button. But when I drag it will trigger click event. Is there any solution for that, means I want to drag that button but not trigger click event after dragging and also there must be a click event for that button.

The button Id and modal Id are generated dynamically

Upvotes: 0

Views: 2960

Answers (4)

Cerlin
Cerlin

Reputation: 6722

try the below code.

var clickFlag = true;
$('#btn-1834').click(function(){
    if(clickFlag){
        //do the click action
    }
})
$('#btn-1834').draggable({
    cancel: false,
    start:function(e,ui){
        clickFlag = false;
    },
    stop: function (e, ui) {
        clickFlag = true;
    }
});

NOTE : I have not tested this yet.

UPDATE

NO need of flags or anything.. just assign the click event AFTER the draggable event and it works fine

FIDDLE

UPDATE 2

Remove the data-target attribute and run this code in same order[important]

$('#btn-1834').draggable({
    cancel: false
});

$('#btn-1834').click(function(){
    $('#key_edit_modal_1834').modal('show');
})

UPDATE 3

Change your html to

<button type="button" class="btn btn-default default-key keypress btn_row1 modalbtn" id="btn-<%= key_position.id %>" data-id="<%= key_position.id %>"></button>

<div id="key_edit_modal_<%= key_position.id %>" class="modal fade">

and run this after draggable

$(document).on('click','.modalbtn',function(){
    $('#key_edit_modal_'+$(this).data('id')).modal('show');
})

Upvotes: 0

SpringLearner
SpringLearner

Reputation: 13844

you can use off function like this

$(function() {
$( "#btn-1834" ).off('click');
$( "#btn-1834" ).draggable({
        cancel: false
    });
});

After the drag function is called you can then use on for click event

Upvotes: 0

Bas Dirks
Bas Dirks

Reputation: 411

$('#btn-1834').draggable({
    cancel: false
}).on('mouseup', function (e) {
    e.preventDefault();
    // your release code
});

Alternatively you can bind your release code to the stop event:

$('#btn-1834').draggable({
    cancel: false,
    stop: function (e, ui) {
        // your release code
    })
}) // ..

Upvotes: 0

Thor Jacobsen
Thor Jacobsen

Reputation: 8851

One way to solve this could be setting a flag somewhere, indicating that you're dragging the element, and then clearing the flag after a couple of milliseconds after dragging is done.

Then, in your click handler, check if the flag is set - if it is, don't do anything.

The exact implementation can vary a lot depending on the libraries you're using, so I can't get into anything more specific, I'm afraid.

Upvotes: 2

Related Questions