user4227915
user4227915

Reputation:

jQuery dynamic anchor doesn't work

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.

Upvotes: 1

Views: 115

Answers (1)

Whiplash450
Whiplash450

Reputation: 964

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>).

Upvotes: 2

Related Questions