0

I am creating a class:

var MyClass;
(function($) {
    MyClass = new function() {

        $('a').off('click');
        $('a').on( 'click', function(event) {
            event.preventDefault();
        });

    };
})(jQuery);

When clicking on a link, a full request is still being issued.

When pasting ...

$('a').on( 'click', function(event) {
    event.preventDefault();
});

... in my console and retrying, everything works as expected.

Is it possible that I am not able to initialize an event listener from within a class definition. If so, how would I initialize my event listener then?

8
  • Probably initializing your class before those elements exist. That is a very strange class definition also Commented Jan 6, 2018 at 23:26
  • I hope this is a gross simplification of your class definition, otherwise it seems like there's no point to the class. Commented Jan 6, 2018 at 23:31
  • 2
    You either need to run this code inside $(document).ready() or you need to use event delegation to bind to dynamically-created elements. Commented Jan 6, 2018 at 23:32
  • @Barmar It is, it's just supposed to exemplify the problem. Commented Jan 6, 2018 at 23:35
  • @Barmar Your solution works. Don't know why I did not think of this myself ... Commented Jan 6, 2018 at 23:37

1 Answer 1

1

try :

$('body').off('click','a');

or:

$(document).off('click','a');

if you init your class before dom is ready.

Short way for your class:

var MyClass = (function($){
    // your code here
    // or with init method
    function init () {
        $('body').off('click','a');
    }
    return {init : init};
})(jQuery);

Than run dom ready:

$(function(){
    MyClass.init()
});
Sign up to request clarification or add additional context in comments.

1 Comment

+1 for proposing the init function. However, the problem has already been solved - read up on the comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.