Is there any way to revert preventDefault method in Vanilla JavaScript?

Viewed 947

I'm trying to create a horizontal scrolling container. In a precise case i need to revert e.preventDefault(); from a click.

I tried a lot of options, changing 'window.location.href' in the else statement seems to be a great option. But i can't figure how to grab the href from the link clicked.

Any idea can help to achieve my goal. :)

slider.addEventListener('mouseup', () => {
    isDown = false;

    // Disable click event (for ever unfortunately)
    if(moved === true) {
        this.addEventListener('click', (e) => {
            e.preventDefault();
        });
    } else {
        // trying to reset click function
    }
2 Answers

You can conditionally prevent a click event from firing on your slider by registering a click event listener that shares the moved variable with your mousedown and mousemove event listeners.

The { passive: true } option indicates that the listener does not call event.preventDefault(), and saves a lot CPU time particularly for the mousemove event which can fire several times per second.

The true parameter indicates that the event listener should be called before the event starts to bubble up from the target element. This allows it to prevent propagation even to listeners that were already added on the same element, as long as they didn't also set useCapture to true.

const slider = document.querySelector('input[type="range"]');

// prevent this if mousemove occurred between mousedown and mouseup
slider.addEventListener('click', () => {
  console.log('click event fired on slider');
});

// fires just before click event
slider.addEventListener('mouseup', () => {
  console.log('mouseup event fired on slider');
});

let moved = false;

// reset for each potential click
slider.addEventListener('mousedown', () => {
  moved = false;
});

// indicate cancellation should occur for click
slider.addEventListener('mousemove', () => {
  moved = true;
}, { passive: true });

// prevents click event if mousemove occurred between mousedown and mouseup
slider.addEventListener('click', event => {
  if (moved) {
    event.preventDefault();
    event.stopImmediatePropagation();
  }
}, true);
<input type="range" />

You should remove the event listener containing the event.preventDefault();.

In order to do that you have to save your function reference into a variable like so:

const preventClickHandler = (e) => e.preventDefault;
slider.addEventListener('mouseup', () => {
    isDown = false;

    // Disable click event (for ever unfortunately)
    if(moved === true) {
        this.addEventListener('click', preventClickHandler);
    } else {
        this.removeEventListener('click', preventClickHandler);
    }
})
Related