1

I'm trying to create a twitter button that allows the user to share the results of a random quote generator.
This is my html:

Quote Machine

 <button onclick="generateQuote()">Click me</button> 

 <p id="quotes"></p>

 <p id ="twitter"></p>

And this is my javascript:

              var quotearray =["Always be yourself","Stay in the moment","Be merry"];
 var pickAQuote = function () {
var newquote = quotearray[Math.floor(Math.random() * 3)];
var noquotes = newquote.replace(/['"]+/g, '');
return noquotes;
};


function generateQuote() {
var newquotes = pickAQuote();

document.getElementById("quotes").innerHTML= newquotes;  
document.getElementById("twitter").innerHTML ='<button onclick=' + 
  '"https://twitter.com/intent/tweet?text=' + newquotes + '";>Tweet 
This</button>';



  }

So the idea is that whatever the randomly generated quote is, the user can then share that quote on twitter. But I can't get it to work! Any advice would be much appreciated!

Nespony
  • 1,253
  • 4
  • 24
  • 42
  • 1
    `onclick` doesn't take you to another website, it executes JavaScript. You either want to use `window.location.href=` or replace your button with an anchor element. – Eric Dobbs May 12 '17 at 15:03
  • Possible duplicate of [How to create an HTML button that acts like a link?](http://stackoverflow.com/questions/2906582/how-to-create-an-html-button-that-acts-like-a-link) – Yaskier May 12 '17 at 15:18

1 Answers1

1

If you want to change the url using the onClick event you should do something like this:

document.getElementById("twitter").innerHTML ='<button onclick="location.href = \'https://twitter.com/intent/tweet?text=' + newquotes + '\'";>Tweet This</button>';
Yaskier
  • 66
  • 4