With class ES6
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 from event listeners
flagged () { this.isScrolled = true; }
and this is to stop all events in the event
preventClick (event) { event.preventDefault(); event.stopImmediatePropagation(); }
Then add the flag when the mousedown and mousemove fire one after another.
element.addEventListener('mousedown', () => { element.addEventListener('mousemove', flagged); });
Do not forget to delete it with the mouse, so that we do not get a huge stack of events repeating in this element.
element.addEventListener('mouseup', () => { element.removeEventListener('mousemove', flagged); });
Finally, inside the mouseup event of our element, we can use the flag logic to add and remove a 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, I aimed at the real target that I clicked on, so if it were a slider, I would target the image, 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 do not need to bind them. Also in this way they have a "handle" that allows s to remove a specific function from the event instead of the entire set of functions in the event.