0

I have two chunks of code here, but only the first is functioning correctly. I'm not sure why. Does it have to do with the "download" attribute? Why? Or, is it because dl isn't correctly referncing the right object? Very confused here, been going at it for an hour or two now.

(Also, is there a way to click an object without appending it to the DOM? Guessing not.)

// WORKING
var a = document.createElement("a");
a.style = "display: none";
a.href = window.URL.createObjectURL(new Blob([this.list.join("\r\n")], {type: "octet/stream"}));
a.download = fileName;
a.click();
window.URL.revokeObjectURL(a.href);

// NOT WORKING
var dl = $('<a>',{
  style: 'display: none',
  download: fileName,
  href: window.URL.createObjectURL(new Blob([this.list.join("\r\n")], {type: "octet/stream"}))
});
$('body').append(dl);
dl.click();
window.URL.revokeObjectURL(dl.href);
Thirk
  • 571
  • 1
  • 7
  • 24
  • where is it failing? – JNF Jan 13 '15 at 08:49
  • Nothing is downloaded. dl is appended correctly, attributes and all, but .click() simply doesn't seem to work - or if it is, it's not doing anything. First example works fine, and I download a file with the blob data titled whatever fileName is at the time. – Thirk Jan 13 '15 at 08:51
  • 1
    `dl[0].click();` will work, you want to call native anchor click method, not triggering any jQuery click event – A. Wolff Jan 13 '15 at 08:52
  • As A. Wolff said, `dl[0].click()` works just fine, without the need to add it to the DOM – Jose Rui Santos Jan 13 '15 at 08:53
  • Excuse me for being incredibly naive, but why did that work? The importance of the `[0]` syntax is lost on me. – Thirk Jan 13 '15 at 08:55
  • 1
    Use the native element (that you can find inside the jQuery element): http://stackoverflow.com/questions/20782534/why-jquery-cannot-trigger-native-click-on-an-anchor-tag – A. Rama Jan 13 '15 at 08:55
  • 1
    BTW, `dl.href` should be `dl[0].href` or `dl.get(0).href` or `dl.prop('href')` still for the same reason – A. Wolff Jan 13 '15 at 08:57
  • Anchor elements don't navigate via `jquery.click()` call. See http://stackoverflow.com/q/773639/1305911 – JNF Jan 13 '15 at 09:20

1 Answers1

0

The first is a DOM object which has a click method, the second is a jQuery object which behaves as an array - to obtain the first DOM element from the array you do so like reading any normal javascript array using dl[0]. You can then call the click method on this object, which does not need to be added to the DOM.

dl[0].click()
Jamiec
  • 133,658
  • 13
  • 134
  • 193