1

I have two functions that I want to run on window.onload event but only the last function seems to work so far. One function is for an image slider and the other one retrieves data from a google spreadsheet cell.

function fun1() { //image slider

  var ul;
  var li_items;
  var imageNumber;
  var imageWidth;
  var prev, next;
  var currentPostion = 0;
  var currentImage = 0;

  function init() {
    ul = document.getElementById('image_slider');
    li_items = ul.children;
    imageNumber = li_items.length;
    imageWidth = li_items[0].children[0].clientWidth;
    ul.style.width = parseInt(imageWidth * imageNumber) + 'px';
    prev = document.getElementById("prev");
    next = document.getElementById("next");

    prev.onclick = function() {
      onClickPrev();
    };
    next.onclick = function() {
      onClickNext();
    };
  }

  function animate(opts) {
    var start = new Date;
    var id = setInterval(function() {
      var timePassed = new Date - start;
      var progress = timePassed / opts.duration;
      if (progress > 1) {
        progress = 1;
      }
      var delta = opts.delta(progress);
      opts.step(delta);
      if (progress == 1) {
        clearInterval(id);
        opts.callback();
      }
    }, opts.delay || 17);

  }

  function slideTo(imageToGo) {
    var direction;
    var numOfImageToGo = Math.abs(imageToGo - currentImage);


    direction = currentImage > imageToGo ? 1 : -1;
    currentPostion = -1 * currentImage * imageWidth;
    var opts = {
      duration: 1000,
      delta: function(p) {
        return p;
      },
      step: function(delta) {
        ul.style.left = parseInt(currentPostion + direction * delta * imageWidth * numOfImageToGo) + 'px';
      },
      callback: function() {
        currentImage = imageToGo;
      }
    };
    animate(opts);
  }

  function onClickPrev() {
    if (currentImage == 0) {
      slideTo(imageNumber - 1);
    } else {
      slideTo(currentImage - 1);
    }
  }

  function onClickNext() {
    if (currentImage == imageNumber - 1) {
      slideTo(0);
    } else {
      slideTo(currentImage + 1);
    }
  }

}

function fun2() {
  // Google spreadsheet js

  google.load('visualization', '1', {
    callback: function() {

      var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1sA7M5kG6Xo8YScD1Df38PIA_G0bvhGRdqoExXg0KJTs/gviz/tq?tqx=out:html&tq?gid=0&headers=0&range=A1:C');
      query.send(displayData);
    }
  });

  function displayData(response) {

    numRows = response.getDataTable().getValue(0, 0);

    document.getElementById('data').innerHTML = numRows;
  }
}


var addFunctionOnWindowLoad = function(callback) {
  if (window.addEventListener) {
    window.addEventListener('load', callback, false);
  } else {
    window.attachEvent('onload', callback);
  }
}

addFunctionOnWindowLoad(fun1);
addFunctionOnWindowLoad(fun2);

This is the answer I've tried link but I can't seem to figure out where I'm going wrong.

Community
  • 1
  • 1
manicdav
  • 45
  • 8
  • 1
    I put it to you that if each of the functions were simple 1-liners, i.e alert("func1") and alert("func2"), that you'd get two alerts shown. That the code fails, tells me there's a problem with one of the functions. What does the console have to say? The problem will almost certainly be readily identifiable from there, in my experience. – enhzflep Mar 26 '16 at 10:51
  • Hi, the console is not showing any errors – manicdav Mar 26 '16 at 11:48
  • Johnyy2 - I just dropped code into each function as the first line. I used the code `alert('fun1');` for one of them and `alert('fun2')` for the other. Both alerts were shown. I then got an error saying `blank.html:180 Uncaught ReferenceError: google is not defined` - this was to be expected, since I just used the code you've shown. From this, it's fair to say there's a problem inside your `fun1` function. :) – enhzflep Mar 26 '16 at 12:04
  • Why are you supporting `attachEvent`? –  Mar 26 '16 at 12:59
  • Can you provide a minimal example (meaning <= 25 lines)? –  Mar 26 '16 at 13:01
  • @enhzflep I think you're right as I've just tried using addeventload from the answer below and the last function works. – manicdav Mar 26 '16 at 13:03

2 Answers2

1

This is what I ended up doing, and now all the functions work.

var ul;
var li_items;
var imageNumber;
var imageWidth;
var prev, next;
var currentPostion = 0;
var currentImage = 0;


function init() {
    ul = document.getElementById('image_slider');
    li_items = ul.children;
    imageNumber = li_items.length;
    imageWidth = li_items[0].children[0].clientWidth;
    ul.style.width = parseInt(imageWidth * imageNumber) + 'px';
    prev = document.getElementById("prev");
    next = document.getElementById("next");
        prev.onclick = function() {
        onClickPrev();
    };
    next.onclick = function() {
        onClickNext();
    };
}

function animate(opts) {
    var start = (new Date());
    var id = setInterval(function() {
        var timePassed = (new Date()) - start;
        var progress = timePassed / opts.duration;
        if (progress > 1) {
            progress = 1;
        }
        var delta = opts.delta(progress);
        opts.step(delta);
        if (progress == 1) {
            clearInterval(id);
            opts.callback();
        }
    }, opts.delay || 17);
    //return id;
}

function slideTo(imageToGo) {
    var direction;
    var numOfImageToGo = Math.abs(imageToGo - currentImage);
    // slide toward left

    direction = currentImage > imageToGo ? 1 : -1;
    currentPostion = -1 * currentImage * imageWidth;
    var opts = {
        duration: 1000,
        delta: function(p) {
            return p;
        },
        step: function(delta) {
            ul.style.left = parseInt(currentPostion + direction * delta * imageWidth * numOfImageToGo) + 'px';
        },
        callback: function() {
            currentImage = imageToGo;
        }
    };
    animate(opts);
}

function onClickPrev() {
    if (currentImage === 0) {
        slideTo(imageNumber - 1);
    } else {
        slideTo(currentImage - 1);
    }
}

function onClickNext() {
    if (currentImage == imageNumber - 1) {
        slideTo(0);
    } else {
        slideTo(currentImage + 1);
    }
}

window.onload = init;


function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            if (oldonload) {
                oldonload();
            }
            func();
        }
    }
}

function fun2() {
    // Google spreadsheet js

    google.load('visualization', '1', {
        callback: function() {

            var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1sA7M5kG6Xo8YScD1Df38PIA_G0bvhGRdqoExXg0KJTs/gviz/tq?tqx=out:html&amp;tq?gid=0&amp;headers=0&amp;range=A1:C');
            query.send(displayData);
        }
    });

    function displayData(response) {

        numRows = response.getDataTable().getValue(0, 0);

        document.getElementById('data').innerHTML = numRows;
    }


}
addLoadEvent(fun2);
addLoadEvent(function() {
});
manicdav
  • 45
  • 8
0

I found this function a while ago and believe it or not, I still need to use it every so often. addEventLoad() Just call addEventLoad while passing the function to load.

"The way this works is relatively simple: if window.onload has not already been assigned a function, the function passed to addLoadEvent is simply assigned to window.onload. If window.onload has already been set, a brand new function is created which first calls the original onload handler, then calls the new handler afterwards."

This snippet will load 3 functions on window.onload

Snippet

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}


function alert1() {
  alert("First Function Loaded");
}

function alert2() {
  alert("Second Function Loaded");
}

function alert3(str) {
  alert("Third Function Loaded; Msg: " + str);
}
addLoadEvent(alert1);
addLoadEvent(alert2);
addLoadEvent(function() {
  alert3("This works");
});
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
zer00ne
  • 31,838
  • 5
  • 32
  • 53
  • There is no logical reason to believe this will solve the OP's problem. –  Mar 26 '16 at 12:58
  • @zer00ne Thanks for your answer. I tried this and the last function actually works/loads, so I now think that there is a problem with my first function. – manicdav Mar 26 '16 at 13:03
  • @torazaburo Please state the reason why it is illogical? OP requested a way to load 2 functions on `window.onload`. This function has worked for me in the past. – zer00ne Mar 26 '16 at 13:03
  • In order to assert that your solution will work, by the basic rules of logic you must have a hypothesis about why his original code did not work, and how yours fixes that problem. What is your hypothesis about why his original code did not work? –  Mar 26 '16 at 13:25
  • I go with what is requested. That would be: *Combining two Javascript functions to one window.onload not working* I try not to volunteer extra help anymore unless asked specifically. Sometimes other posters become disruptive and it's headache. – zer00ne Mar 26 '16 at 14:10