Search code examples
javascriptjqueryrandomonloadquote

How to display a random quote as soon as page loads?


I am working on a random quote app. Quote is display when click a new quote button but I want quote already display when page loads. I invoked a function but it still does not work. Thank you!

Here is my code:

$(document).ready(function() {
  function randomQuote() {
    $('#get-quote').on('click', function(e){
      e.preventDefault();
      // Using jQuery
      $.ajax( {
          url: "http://quotes.stormconsultancy.co.uk/random.json",
          dataType: "jsonp",
          type: 'GET',
          success: function(json) {
             // do something with data
             console.log(json);
             data = json[0];
             $('#quotation').html('"'+json.quote+'"');
             $('#author').html('-- '+json.author+' --');
             $('a.twitter-share-button').attr('data-text',json.quote);
           },

      });

    });
    $('#share-quote').on('click', function() {
         var tweetQuote=$('#quotation').html();
         var tweetAuthor=$('#author').html();
         var url='https://twitter.com/intent/tweet?text=' + encodeURIComponent(tweetQuote+"\n"+tweetAuthor);
         window.open(url)
    });

  }
  randomQuote();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


Solution

  • Try removing click listener. inside randomeQuote() remove click listener.

    keep your click listener out side of document.ready

    $(document).ready(function() {
           randomQuote(); // call initially and get random quote
    });
    
    
    function randomQuote() {
       
          $.ajax( {
              url: "https://quotes.stormconsultancy.co.uk/random.json",
              dataType: "jsonp",
              type: 'GET',
              success: function(json) {
                 // do something with data
                
                 data = json[0];
                 $('#quotation').html('"'+json.quote+'"');
                 $('#author').html('-- '+json.author+' --');
                 $('a.twitter-share-button').attr('data-text',json.quote);
               },
    
          });
    
        $('#share-quote').on('click', function() {
             var tweetQuote=$('#quotation').html();
             var tweetAuthor=$('#author').html();
             var url='https://twitter.com/intent/tweet?text=' + encodeURIComponent(tweetQuote+"\n"+tweetAuthor);
             window.open(url)
        });
    
      }
      
     $('#get-quote').on('click', function(e){
          e.preventDefault();
          randomQuote();
      });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <button id="get-quote">get quote</button>
    
    <div id="quotation"></div>