23

I have a page with an anchor tag. In my JavaScript I am setting the HREF attribute of the anchor tag dynamically based on some if-else conditions. Now I want to invoke the click event of the anchor tag programmatically. I used the below code, but was not successful.

var proxyImgSrc="CostMetrics.aspx?Model=" + model +"&KeepThis=true&TB_iframe=true&height=410&width=650";

document.getElementById("proxyAnchor").href=proxyImgSrc;
document.getElementById("proxyAnchor").onclick;

Can any one tell me how to go ahead? I have a jQuery light box implementation(thickbox) on this link.

Kindly advise. Thanks in advance.

Sampson
  • 265,109
  • 74
  • 539
  • 565
Shyju
  • 214,206
  • 104
  • 411
  • 497
  • Can I get to set the path where the file should be downloaded? because using this it's just downloading to the DOWNLOADS folder. i want to to save to the location of html file. – Arjun Dec 13 '16 at 19:30

6 Answers6

72

If you have jQuery installed then why not just do this:

$('#proxyAnchor')[0].click();

Note that we use [0] to specify the first element. The jQuery selector returns a jQuery instance, and calling click() on that only calls click javascript handler, not the href. Calling click() on the actual element (returned by [0]) will follow the link in an href etc.

See here for an example to illustrate the difference: http://jsfiddle.net/8hyU9/

As to why your original code is not working - it is probably because you are calling onclick, and not onclick(). Without the parenthesis JavaScript will return whatever is assigned to the onclick property, not try to execute it.

Try the following simple example to see what I mean:

var f = function() { return "Hello"; };     
alert(f);
alert(f());

The first will display the actual text of the function, while the second will display the word "Hello" as expected.

samjudson
  • 56,243
  • 7
  • 59
  • 69
  • 2
    For the use case of "follow the href defined in the anchor" [this answer fails](http://jsfiddle.net/SNdHW/show/) – Roatin Marth Jun 26 '12 at 12:08
  • @RoatinMarth Actually, it does work for that. Part of the problem is that you're using JSFiddle (Clicking the link itself doesn't work in JSFiddle). For a perfect example of it working in JSFiddle, try setting the target to _blank. Also, you didn't do [0]. I tested it without the target on my own server, and it worked just fine. So here's a "fixed" version for JSFiddle: https://jsfiddle.net/SNdHW/4/show/ – TheOneWhoSighs Dec 01 '15 at 20:31
  • Can I get to set the path where the file should be downloaded? because using this it's just downloading to the DOWNLOADS folder. i want to to save to the location of html file. – Arjun Dec 13 '16 at 19:30
  • @TheOneWhoSighs check the timestamps of this answer's edits. My comment was in reply to the original answer (the "pure jQuery" solution). – Roatin Marth Jun 05 '21 at 02:12
13

You should call click event like this:

document.getElementById("proxyAnchor").click();
// $('#proxyAnchor').click();

but in your case you should set the window's location to a redirect page, if you want that.

Liam
  • 27,717
  • 28
  • 128
  • 190
Canavar
  • 47,715
  • 17
  • 91
  • 122
  • Can I get to set the path where the file should be downloaded? because using this it's just downloading to the DOWNLOADS folder. i want to to save to the location of html file. – Arjun Dec 13 '16 at 19:30
1

I believe you want to invoke the click event. Not the "onClick." Also, be sure to include the parenthesis () when you're invoking a method. Don't confuse methods (which end with ( and )) with attributes and properties which do not end with ( and ).

// Using jQuery - Which you tagged...
$("#proxyAnchor").attr("href", proxyImgSrc).click();
Sampson
  • 265,109
  • 74
  • 539
  • 565
1

I believe this is what you're after:

var proxyImgSrc="CostMetrics.aspx?Model=" + model +"&KeepThis=true&TB_iframe=true&height=410&width=650";
$("#proxyAnchor").attr('href', proxyImgSrc).trigger("click");;
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
karim79
  • 339,989
  • 67
  • 413
  • 406
1

For an immediate page change, you can also do this:

var proxyImgSrc= "CostMetrics.aspx?Model=" + model + "&KeepThis=true&TB_iframe=true&height=410&width=650";
window.location = proxyImgSrc;

Here's an example from W3 Schools: http://www.w3schools.com/js/tryit.asp?filename=tryjs_location

0

If you are looking for support of IE, then this example below may help:

suppose you have the blob document in response object:

                 var blob = new Blob([response.responseText], { type: headers['content-type'] });
            if (navigator.msSaveOrOpenBlob) {
                //Launches the associated application for a File or Blob saving for non webkit based browser such as safari or IE
                navigator.msSaveOrOpenBlob(blob, "cvSummary.xml");
            }
            else {
                //code for webkit based browser
                var link = document.createElement('a');
                document.body.appendChild(link);
                link.style = "display: none";
                var url = window.URL.createObjectURL(blob);
                link.href = window.URL.createObjectURL(blob);
                link.download = "cvSummary.xml";
                link.dataset.downloadurl = ["text/xml", link.download, link.href].join(':');
                link.click();
                window.URL.revokeObjectURL(url);
            }