Search code examples
javascriptjquerybackbone.jssingle-page-application

Do preventDefault and then do default behavior


I have a requirement in a single page application project, where I need to change a page's section when I click on a anchor tag based on the provided href attribute. Something like this:

<a class="page-click" href="#showPeople/1">Open</a>

This anchor is in a popup on that page. So, whenever I click on this anchor tag, the anchor should close the popup and change the window location to

http://www.example.com/#showPeople/1

Now, the anchor is changing the url (which is by default) but not closing the popup.

When I researched I found that for anchors, I should use e.preventDefault() to remove default behavior. But in my case, I need both default behavior as well as the custom behavior (closing the popup).

I found this link which has similar requirement but the thing is that I am attaching event dynamically.

$(document).on('click', '.page-click', function (e) {
     // e.preventDefault();
     // code here
});

and even if I somehow succeeded to unbind the event from that specific clicked anchor, the anchor will not close the popup, when the user opens the popup again (since the registered event has been removed).


Solution

  • Try

    $('button').click(function () {
        $('body').toggleClass('active');
    });
    $(document).on('click', 'a.page-click', function (e) {
        e.preventDefault();
        var $this = $(this);
        $('.popup').hide('fast', function() { 
            window.location.href = "http://example.com/" + $this.attr('href');
        });
    });