Prevent click event on mouseup and mouseup event on Click

364 Views Asked by At

I've created a dragbar , which will increase and decrease container width on dragging and on click it will contract/expand. But whenever I'm trying to drag it click event is triggering and dragbar is contracting. I'm using backbone.js and using the code below.

events: {
    'click .sideNavBar': 'toggleHeadersSection',
    'mousedown #dragBar': 'increaseDragBarWidth',
    'mouseup #dragBar': 'decreaseDragBarWidth',
    'click #dragBar': 'toggleHeadersSection',
},

increaseDragBarWidth: function (event){
    $(document).mousemove(function(event){
        $('.clinical-data-accordion').css("width",event.pageX+2);
    });

},

decreaseDragBarWidth: function (event){
    $(document).unbind('mousemove');
},
toggleHeadersSection: function(event){
       let clinicalDetailSection = this.$el.find("#clinicalDetailSection");
       let isHidden = $(clinicalDetailSection).hasClass('isHidden');
       this.displayHeadersSection(isHidden);
   
},
1

There are 1 best solutions below

0
Jesper On

Here is a JSFiddle with some images that you can drag and click. (it is pure js)

There a click is separated from a drag by checking the time difference of mouse down and up events.

let timeDelta;

function startDrag(e) { // mouse up
    timeDelta = Date.now(); // get current millis
    ...

function stopDrag() { // mouse down
    if (typeof drag == "undefined") return;

    if (drag) {
        if (Date.now() - timeDelta > 150) { // we dragged
    ...

If you hold the mouse down for more than 150ms, it is not counted as a click. If you add that check to your click event, it should work.