Nelson McCullough
Nelson McCullough

Reputation: 63

jquery window load function not doing anything on load

posting for the first time on here, just wondering what im doing wrong within this little jquery script I wrote for a external html file containing my menu element. It works on resize just not load. I've tried a standalone $(window).load(); event as well and nothing seems to work. I'm new to jQuery and just know the do's and donts yet!

jQuery(document).ready(function($) {
  var vwidth = $(window).width();
  var vheight = $(window).height();
  var menu = $('#menu_container');

  $( window ).on('load resize', function() {
    if (vwidth >= 1000) {
      menu.css('zoom', '1');
    } else {
      menu.css('zoom', '0.8');
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 0

Views: 142

Answers (3)

Leo
Leo

Reputation: 14820

There are two problems here. One already explained by @Mr. Polywhirl. The other one is the fact that the DOM ready event will excute AFTER the window.load event. That means that by the time jQuery(document).ready executes $(window).load has already happened, so the event registration for window.load it's a bit late. Try this instead...

//this is essentially the same as jQuery(document).ready
$(function(){
    toggleZoom();

    $(window).on("resize", function(){
        toggleZoom();
    });
});



function toggleZoom(){    
  var vwidth = $(window).width();
  //this isn't needed in this snippet
  //var vheight = $(window).height();
  var menu = $('#menu_container');


    if (vwidth >= 1000) {
      menu.css('zoom', '1');
    } else {
      menu.css('zoom', '0.8');
    }
}

Upvotes: 1

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48600

jQuery(document).ready(function($) {

Remove the dollar sign ($) from the function above. You are redefining the global as a function argument for the scope of the jQuery.ready function.

jQuery(document).ready(function() {

Edit

If that does not work, try some of these basic calls and see what the console prints out.

When I click the Run code snippet button, I get the following output:

Document ready()
Window resize()
Window load()
Window load() x2
Window resize()

$(document).ready(function() {
  console.log("Document ready()");
});

$(window).on('load', function() {
  console.log("Window load()");
});

// or

$(window).on({
  load : function() {
    console.log("Window load() x2");
  },
  resize : function() {
    console.log("Window resize()");
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 1

qelli
qelli

Reputation: 2077

The correct usage for jQuery ready() function is:

jQuery(document).ready(function(){
   //The code you want to execute.
});

For more info look at:

https://api.jquery.com/ready/

Upvotes: 0

Related Questions