5

I currently have a JavaScript file that I call in my view page in which I get my data information to display. At the same time I have this piece of JavaScript that shows a menu bar once the image has been clicked. This scripted is being ran before the page is loaded completely or something because it is not working. How can I make a piece of my JavaScript take action after all other scripts have completed running and page is loaded? this is what I tried but not working right

JavaScript

(function ($) {

.... lines to load view page with data

$(document).ready(function () {
    $('figure').on('click', function (event) {
        $(event.currentTarget).toggleClass('open');
    });
});

})(jQuery);
5
  • 3
    @mplungjan - $ is passed in as a variable, but $() is never issued.
    – Travis J
    Commented Apr 5, 2013 at 18:00
  • 1
    @mplungjan The outer expression is an IIFE, the inner is $(document).ready
    – Ian
    Commented Apr 5, 2013 at 18:03
  • @ian I saw that (didn't know the acronym) but ignored it since it looks more like some method to protect jquery than what is needed. We will see what OP actually needs
    – mplungjan
    Commented Apr 5, 2013 at 18:04
  • @mplungjan benalman.com/news/2010/11/… , stackoverflow.com/questions/8228281/…
    – Ian
    Commented Apr 5, 2013 at 18:04
  • 1
    immediately-invoked function expression Commented Apr 5, 2013 at 18:04

1 Answer 1

8

You could use $(window).on("load") instead of $(document).ready if you want to wait until all the elements have loaded in that case:

$(window).on("load", function(){
    $('figure').on('click', function (event) {
        $(event.currentTarget).toggleClass('open');
    });    
});
25
  • 1
    I have found that the load event for window is more appropriate than document.ready in certain cases as well.
    – Travis J
    Commented Apr 5, 2013 at 18:01
  • 3
    @mplungjan - The situations I have needed to use the load version on window instead of document has been when images are still loading in parallax sites or when images are being rendered as the ready event fires. I have found that at times the dimensions can be slightly off when using ready in those situations.
    – Travis J
    Commented Apr 5, 2013 at 18:04
  • 2
    This worked like a charm just waiting till i could mark it as answered.
    – Masriyah
    Commented Apr 5, 2013 at 18:05
  • 1
    @JeffShaver - What replaced load? In these situations I usually just use window.onload = function(){} instead of jquery.
    – Travis J
    Commented Apr 5, 2013 at 18:08
  • 2
    There's a difference between .load() being deprecated and the "load" event. Just use .on("load", function () {}); instead then. There's a major difference between $(window).on("load", function () {}); and $(document).ready(function () {});
    – Ian
    Commented Apr 5, 2013 at 18:11

Not the answer you're looking for? Browse other questions tagged or ask your own question.