Dynamically create and "click" a link with jQuery
Asked Answered
V

15

20

I want to dynamically create an <a href="mailto:..."> element, then "click" it. All without modifying the page.

I'm trying this:

$('<a href="mailto:[email protected]">&nbsp;</a>').click();

...to no avail

Volition answered 28/6, 2011 at 10:52 Comment(0)
L
16

Clicking on a link means changing window.location, so how about

window.location = "mailto:[email protected]";
Leotaleotard answered 28/6, 2011 at 10:57 Comment(3)
this doesn't pass referrer information in all browsers, so it's not strictly equivalent to creating a link and clicking itAtrice
see: #4762754Atrice
This doesn't solve the question. That only shows you how to change the current windows location. It doesn't answer how to programmatically create an element then programmatically click it.Temporize
P
47

Its not jquery, but it works just fine.

var link = document.createElement('a');
link.href = url;
document.body.appendChild(link);
link.click();    
Protanopia answered 1/3, 2013 at 18:45 Comment(3)
Thanks for answering what the question exactly asked :)Elytron
Very simple and easy to use solutionHeman
In case you are trying to download an xml file, add the following line: link.download = url; Otherwise, the xml file will be displayed in the browser.Ptomaine
L
16

Clicking on a link means changing window.location, so how about

window.location = "mailto:[email protected]";
Leotaleotard answered 28/6, 2011 at 10:57 Comment(3)
this doesn't pass referrer information in all browsers, so it's not strictly equivalent to creating a link and clicking itAtrice
see: #4762754Atrice
This doesn't solve the question. That only shows you how to change the current windows location. It doesn't answer how to programmatically create an element then programmatically click it.Temporize
H
16

To make it work with jQuery, you first need to select the DOM element inside the jQuery object.

$('body').append('<a id="link" href="mailto:[email protected]">&nbsp;</a>');
$('#link')[0].click();

Notice the [0]

fiddle: https://jsfiddle.net/fkwhvvhk/

Heliozoan answered 7/4, 2016 at 17:35 Comment(4)
Wow, just retrieve the DOM element then click it. But why jQuery click() function don't invoke the DOM one's for each query item?Pome
I think this is the least rubbish answer in a sea of rubbish answers. I just added [0] to my code and now it works. Ridiculous. The link is in the DOM, jQuery can find the link, but for no apparent reason it won't click it. No error, nothing. Thank you for this three character fix.Canicular
$('#link')[0].click(); gives an error in the console saying "TypeError: $(...)[0] is undefined". JQuery 3.2.1 and modern Firefox browser (ver 68). I too hate 'rubbish' answers...Talion
If you use this solution and you can get an error message "TypeError: $(...)[0] is undefined. The reason is simple, the element dows not exist YET. So you have to wait for it to exist. See my answer how you can do this: https://mcmap.net/q/609061/-dynamically-create-and-quot-click-quot-a-link-with-jqueryBrusquerie
T
10

.click() work with a DOM, not jQuery object

it should be:

$('<a href="mailto:[email protected]"></a>')[0].click();
Ting answered 27/5, 2017 at 6:52 Comment(2)
This is the simplest solution to the question. Can also use jQuery to avoid conflict with $: jQuery(<a href="/product-edit/${this.selected.id}"></a>)[0].click();Mayonnaise
If you use this solution and you can get an error message "TypeError: $(...)[0] is undefined. The reason is simple, the element dows not exist YET. So you have to wait for it to exist. See my answer how you can do this: https://mcmap.net/q/609061/-dynamically-create-and-quot-click-quot-a-link-with-jqueryBrusquerie
A
5

Try something like this...

Demo: http://jsfiddle.net/wdm954/xtTGX/1

$('.a').append('<a class="b" href="mailto:[email protected]">&nbsp;</a>');
$('.b').click(function() {
    window.location = $(this).attr('href');
}).click();
Alack answered 28/6, 2011 at 11:13 Comment(0)
F
2

Yo can create the tag this way:

$('PARENT_TAG').append('<a id="dinamic_link" href="mailto:[email protected]">&nbsp;</a>');
//Now click it
$('#dinamic_link').click();

HTH!

Filter answered 28/6, 2011 at 10:55 Comment(1)
this doesn't seem to work for me. perhaps something is interfering, but .click() doesn't seem to work on /any/ linkVolition
E
2

why not just change the window location to the href of the link? Is there any specific reason you need to use a link?

Otherwise:

window.location = 'http://example.com';
Embellishment answered 28/6, 2011 at 10:58 Comment(0)
D
2

I have been found some problems with a similar issue and I found the simplest way for me:

    var link = document.createElement('a');

    link.download = 'profile.png';
    link.href = '...';
    link.id = 'example';
    link.class = '...';

    document.body.appendChild(link);

    link.click();

In my case I lost a lot of time trying to do this with jquery, doing $('#example').click()but does not work for me. At least the problem was jquery, I did it without it. I hope that it can be help for somenone. Is a simple way to set an anchor to download an image and do click just after.

Dermal answered 9/9, 2019 at 15:47 Comment(0)
G
1
$('#something').append('<a id="link" href="mailto:[email protected]"></a>');
$('#link').trigger('click');
Godhood answered 28/6, 2011 at 10:58 Comment(1)
this doesn't seem to work for me. perhaps something is interfering, but .click() doesn't seem to work on /any/ linkVolition
S
1

I would say you should consider adding the href to a container (mostly div) using .append() and call .click()

$('parent_div').append('<a id="link" href="mailto:[email protected]">&nbsp;</a>');
//Now click it
$('#link').click();
Seline answered 28/6, 2011 at 11:1 Comment(1)
this doesn't seem to work for me. perhaps something is interfering, but .click() doesn't seem to work on /any/ linkVolition
J
1

It is not possible to simulate normal clicks. You can only trigger click event handlers that have been bound to an element..

As @Alex has posted, you can change the window.location to achieve the same effect..

Jolt answered 28/6, 2011 at 11:2 Comment(0)
L
1

Just been doing a tutorial on this!

$("[href='mailto:[email protected]']").click();

This should select all elements with a href attribute with "mailto:[email protected]" as its value.

www.w3schools.com/jquery/jquery_selectors.asp

Lianaliane answered 28/6, 2011 at 11:13 Comment(0)
W
0

you have to use .on and then call .click . Dynamically generated hyper reference does not work with simple .click()

Wrennie answered 21/8, 2015 at 12:19 Comment(0)
B
0

If you want to use jQuery. This is basically the same answer as the answer from jBelanger:

$('body').append('<a id="link" href="mailto:[email protected]">&nbsp;</a>');
$('#link')[0].click();

The problem is $('#link')[0] might not exist YET! You have to wait for it to be created. How to do that? I found the answer here. The following worked for me:

$('body').append('<a id="link" href="mailto:[email protected]">&nbsp;</a>');
waitForElm('#link').then((elm) => { elm.click(); });

function waitForElm(selector) {
    return new Promise(resolve => {
        if (document.querySelector(selector)) {
            return resolve(document.querySelector(selector));
        }

        const observer = new MutationObserver(mutations => {
            if (document.querySelector(selector)) {
                resolve(document.querySelector(selector));
                observer.disconnect();
            }
        });

        observer.observe(document.body, {
            childList: true,
            subtree: true
        });
    });
}
Brusquerie answered 19/10, 2022 at 19:23 Comment(0)
D
-1
var link = document.createElement('<a>')
link.href = "mailto:[email protected]";
link.id = "hitme"
$('#hitme').click();
Daubery answered 28/6, 2011 at 10:55 Comment(2)
this doesn't seem to work for me. perhaps something is interfering, but .click() doesn't seem to work on /any/ linkVolition
the first line should be edited as var link = document.createElement('a') for it to work properly.Subatomic

© 2022 - 2025 — McMap. All rights reserved.