Rose Perrone
Rose Perrone

Reputation: 63546

Intercept hyperlink clicks

I'm trying to intercept clicks on this link:

<a id="test-button" href="#">Test</a>

with this js:

(function() {
    $('#test-button').click(function (event) {
        console.log("This code never gets called.")
        event.preventDefault();
        $('#alert-placeholder').html(['<div class="alert"><a class="close"',
                                      'data-dismiss="alert">×</a>',
                                      '<span>"+message+"</span></div>'].join())
        return false;
    })
    console.log("yes, this code loads");
    debugger;
})();

but the URL '#' loads and the code in the click() function doesn't run. What am I missing?

I'm using this code in a flask app using bootstrap.

Upvotes: 0

Views: 95

Answers (1)

zerkms
zerkms

Reputation: 254916

Seems like you're trying to attach an event handler to the element that doesn't exist yet

(function() {
})();

only creates a local scope but doesn't guarantee DOM to load. To confirm it - add console.log($('#test-button').length); to your code.

What you need is to wrap your code with

$(function() {
    // your code is here
});

instead

Upvotes: 7

Related Questions