fumeng
fumeng

Reputation: 1820

Trigger click() for dynamically created elements

Ok, there are a couple approaches to the problem of triggering a click() for a dynamically-generated element. First, this will work for Chrome but not IE or FF:

var href="/myUrl";
var link = $("<a>");
link.prop("href", href);
link[0].click()

So, if the thinking is that using click() on an element that doesn't exist won't work in IE or FF, what's the best approach?

var href="/myUrl";
var link = $("<a>");
link.prop("href", href);
$(document).append(link); // Attach it to the DOM so it exists
link[0].click()

Or is there something even simpler that I'm missing? Thanks for any helpful tips.

Upvotes: 1

Views: 1184

Answers (2)

Donnie D&#39;Amato
Donnie D&#39;Amato

Reputation: 3940

The following is a function that I've used in production code, it's a bit different from yours but it might be what you need.

function psuedoClick(href, target){
    if(!target) target = '_self';
    var falseAnchor = $('<a/>').attr({
        'href' : href,
        'target' : target
    }).appendTo('body');
    falseAnchor[0].click();
    falseAnchor.remove();
};

Just pass in the arguments when you call the function and it'll work.

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1073978

You've said you want to trigger the download of a file. Another simple way to do that is to have an invisible iframe on the page:

<iframe src="about:blank" style="display: none" id="downloader"></iframe>

...then when you want to trigger the download:

$("#downloader").attr("src", "/myUrl");

As with your current solution, it's important that the response containing the file have a Content-Disposition header identifying it as an "attachment" (the same header can also suggest a name), to get consistent handling across MIME types.

Upvotes: 2

Related Questions