0

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?

fightstarr20
  • 11,682
  • 40
  • 154
  • 278

3 Answers3

3

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

Community
  • 1
  • 1
Ele
  • 33,468
  • 7
  • 37
  • 75
1

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);
AngelSalazar
  • 3,080
  • 1
  • 16
  • 22
1

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'.

mpen
  • 272,448
  • 266
  • 850
  • 1,236