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.

6
  • 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. Commented Mar 26, 2016 at 10:51
  • Hi, the console is not showing any errors Commented Mar 26, 2016 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. :) Commented Mar 26, 2016 at 12:04
  • Why are you supporting attachEvent? Commented Mar 26, 2016 at 12:59
  • Can you provide a minimal example (meaning <= 25 lines)? Commented Mar 26, 2016 at 13:01

2 Answers 2

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() {
});
Sign up to request clarification or add additional context in comments.

Comments

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>

5 Comments

There is no logical reason to believe this will solve the OP's problem.
@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.
@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.
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?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.