Stop repeating event.preventDefault()

If you end up repeating event.preventDefault(); in all/most of your event handlers, then you can stop yourself by using decorator over your actual event handlers.

Here is an example -

1
2
3
4
5
6
7
8
9
10
11
12
    $(document).ready(function() {
        function defaultPreventer(handler) {
            return function(event) {
                event.preventDefault();
                handler.apply(this, arguments);
            }
        };
        function clickHandler(event) {
            //..do something
        };
        $("#link").on("click", defaultPreventer(clickHandler));
    });

What defaultPreventer does here is, it returns the a decorator function for your actual event handler function clickHandler. Whenever the event is triggered, this decorator function gets called, and it executes event.preventDefault(); before executing actual event handler clickHandler.

Here is working example on JsFiddle.

Comments