Search code examples
javascriptjquerytabletop.js

My function is running when page loads, but I only want it to run when a selected area is picked


I am making a random quote generator with JavaScript and Tabletop.js. When my page loads, the function to pull a quote and generate from my spreadsheet is automatically initialized. I don't want it to generate a new quote unless the page/area is clicked.

BTW, it's a vulgar page, basing it off of greatfu**ingstartupadvice.com

Here is the codepen page:

http://codepen.io/JonLangel/pen/kXdmqP?editors=1010

Here is the JS from the Codepen page:

var my_spreadsheet = 'https://docs.google.com/spreadsheets/d/1sX822Oiga0j0eHC8PvegRo6W8GGC0a28nVgnvSsOqo/pubhtml';

var sheet_data;

function init() {
  Tabletop.init( { 
    key: my_spreadsheet, 
    callback: saveData,
    simpleSheet: true
    });
}
function saveData(data, tabletop) {
  sheet_data = data; 
  newQuote(); 
}

 function newQuote() {
    var randNum = Math.floor(Math.random() * (sheet_data.length));

    $("#advice").html(sheet_data[randNum].Advice).addClass('animated     zoomIn').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(){
      $(this).removeClass();
        });
 }
 $(document).ready(function() {

   init();

   $('.container').onclick(function(){
     newQuote();

 }); 

});

Solution

  • In start of page You are initialising Tabletop, but in callback of init:

    callback: saveData //saveData is callback of init
    

    And code this function:

    function saveData(data, tabletop) {
      sheet_data = data; 
      newQuote();  //here You have newQuote called
    }
    

    Remove newQuote() from saveData and quote will be not generated at page load

    function saveData(data, tabletop) {
      sheet_data = data; 
    }