1

My post method receives an object with the path to a dynamic created pdf, and I want to open the pdf. But some browser shows blocked popup in functions like window.open(). Then I'm trying to create an anchor and trigger a click on it, but doesn't seems to work:

$http.post('/Export/Create', params).success(function (o) {
    load.fadeOut(function () {
        if (o.Path.match(/\.pdf$/)) {
            console.log('returned PDF');
            var a = $('<a></a>').appendTo('body');
            a.attr({ 'href': o.Path, 'target': '_blank' });
            a.trigger('click');
        }
        // else ...
    });
}).error(function (x) { console.log(x); });

I am receiving the returned PDF message, so the problem is with the dynamic anchor.

Thanks in advance.

  • Related http://stackoverflow.com/questions/6068266/jquery-how-to-trigger-anchor-links-click-event#answer-12166799 Also Related http://stackoverflow.com/questions/773639/how-can-i-simulate-an-anchor-click-via-jquery – Stryner Nov 16 '15 at 15:21
  • you can try `a.click()` – Mihai Matei Nov 16 '15 at 15:21
  • @MateiMihai. Still doesn't work :( –  Nov 16 '15 at 15:58
  • @Stryner. The first answer of the first question worked for me, while still shows `blocked popup` on browser :( –  Nov 16 '15 at 15:59

1 Answers1

2

When adding dynamic content after the dom has loaded, the event handlers won't exist for the added elements, so you have to use something like

$(document).on("click", "a.anchor_class", function () {
    //click code here
}

The 'a' in the second parameter is the element type followed by a class name to hook the listener into e.g. "button.classname".

Additionally, the above .on("click") function can exist on the page before your dynamic content is loaded. It will register the clicks just fine after you add the <a> in later (as long as you add the matching class name to the <a>).

Whiplash450
  • 943
  • 2
  • 12
  • 22
  • That's not the case.. I am trying to simple trigger the default action of anchor tag. –  Nov 16 '15 at 15:57
  • I see, but it still won't trigger because there is no event listener waiting for the trigger call. So you have to do it using the way I posted and call something like $(this).trigger(); in the method. – Whiplash450 Nov 16 '15 at 16:01