fightstarr20
fightstarr20

Reputation: 12568

jQuery - Create link element and click it

I am trying to dynamically generate a link to Post a tweet on twitter and then click on it like this...

$("body").prepend("<a id=\"twitter_link\" href='https://twitter.com/intent/tweet'></a>");

$( "#twitter_link" ).click(function() {
  console.log( "Handler for .click() called." );
});

This is not working, where am i going wrong?

Upvotes: 0

Views: 949

Answers (3)

Ele
Ele

Reputation: 33726

Your code is 99% done!

Your new a element doesn't have text

Important

The click event it's necessary if you need to execute a logic when the new link is clicked, otherwise, that event it's unnecessary.

$("body").prepend("<a id=\"twitter_link\" href='https://twitter.com/intent/tweet'>Hello World</a>");

$( "#twitter_link" ).click(function(e) {
  e.preventDefault(); //This is just to show your logic is working!
  console.log( "Handler for .click() called." );  
  location.href = this.href; //This is to redirect to the specific page after any previous executed logic.
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Resource

Upvotes: 3

mpen
mpen

Reputation: 282805

If you actually want to automatically click the link, you have to call .click() on the element -- you're binding a click handler. Here's an example without jQuery adapted from a project I'm working on:

function clickLink(url) {
    let anchor = document.createElement('a');
    anchor.href = url;
    document.body.appendChild(anchor); // Firefox requires us to actually insert the element into the DOM before we can click it
    anchor.click();
    document.body.removeChild(anchor);
}

clickLink('https://stackoverflow.com')

Watch your devtools console though, because if you try linking to another domain you might get this error:

Refused to display 'https://www.google.ca/?gfe_rd=cr&dcr=0&ei=--R8WpqeLpTM8AeZoYbgAg' in a frame because it set 'X-Frame-Options' to 'sameorigin'.

Upvotes: 1

AngelSalazar
AngelSalazar

Reputation: 3113

you can also try creating the element first, adding the event listener and then appending to the body

var $a = $("<a id=\"twitter_link\" href='#'>test</a>" );

$a.click(function(e) {
  e.preventDefault();
  console.log( "Handler for .click() called." );
});

$("body").prepend($a);

Upvotes: 1

Related Questions