vish09
vish09

Reputation: 3

Random Quote Generator : Tweet Button with Jquery

I am making a random quote generator. But I am not able to share it via twitter. I am getting a twitter page but the text box for the tweet is empty.

    <!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>title</title>
    <link rel="stylesheet" type="text/css" href="style.css">
  </head>
  <body>
  <div id="div1">
  <p id="quote"></p>
  <p id="author"></p>
<button id="btn">getquote</button>
<div>
<a href="https://twitter.com/intent/tweet" target="_blank">
<button type="button" id="twitter-share-button">tweet</button>
</a>
  </div>
  </div>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
  <script src="script.js"></script>

  </body>
</html>

Here is my Javascript code

var url1="http://api.forismatic.com/api/1.0/?method=getQuote&key=457653&format=jsonp&lang=en&jsonp=?";

//var url1=" http://date.jsontest.com/";


var getQuote=function(data){
    //console.log(data);
    var quot="https://twitter.com/intent/tweet?text=" + data.quoteText+data.quoteAuthor;
    console.log(quot);

    $('#quote').text(data.quoteText);
    $('#author').text(data.quoteAuthor);
    $('#twitter-share-button').attr("href", quot);
};

$(document).ready(function(){
$.getJSON(url1,getQuote,'jsonp');

});
$("#btn").on("click",function(){
    $.getJSON(url1,getQuote,'jsonp');

});

I get the quote randomly but clicking on tweet button in my code doesnt change the href using .attr in Jquery. Am I doing it correctly?

Upvotes: 0

Views: 450

Answers (2)

Tyler Roper
Tyler Roper

Reputation: 21672

You're applying the href to the button, instead of its containing <a>. Because the <a> is the direct parent of your button, you can easily just change your $('#twitter-share-button').attr("href", quot); line to include a .parent(), like so:

$('#twitter-share-button').parent().attr("href", quot);

Upvotes: 0

Sabir
Sabir

Reputation: 31

I don't know if I'm just missing something, but it looks like you are trying to change the href attribute of the button, but the button doesn't have a href attribute (and probably shouldn't).

$('#twitter-share-button').attr("href", quot);

Instead you want to do

$('#twitter-share-anchor').attr("href", quot);

And give the actual anchor the id:

<a id="twitter-share-anchor" href="https://twitter.com/intent/tweet" target="_blank">

Upvotes: 0

Related Questions