I had some scripts running on 1.7.1 jQuery and now I am on Wordpress's 1.12.4. The code wouldn't run. I had two errors running:
Uncaught TypeError: $ is not a function https://grumans.ca/delicatessen/:1734
This line on the page is $(window).load(function(){Grumans.deli.init();});
and this
Uncaught TypeError: $ is not a function https://grumans.ca/js/script.js:1162
$(window).load(function(){
//Grumans.deli.init();
});
I found what I thought was a solution. Someone had posted for a different article that you could do this.
jQuery(function($) {
$(window).on("load", function() {
Grumans.deli.init();
});
});
This got rid of both errors when applied to the page and in the script code, and let my code run, but only if I refresh the page twice. When I first hit the page nothing happens. I am not a code writer. Does anyone know why and how to fix the code so that it runs as soon as the page loads?
CodePudding user response:
It's hard to know exactly what is going on in your particular case without also seeing the html, but given what you've presented, this might work:
jQuery(window).load(function(){
console.log('called on page load');
});
The reason your first example doesn't work is because the $
variable hasn't been attached to the window
object. It looks like you do have access to jQuery
though, which is another global that jQuery attaches to window that is an alias of $
.
CodePudding user response:
You are using a version of JQuery that doesn't define $ by default like the older versions did. You can just replace $
with JQuery
if you really want the load event, but typically DOMReady is a more useful event. Some of the images may not have completely downloaded at that point, but you can usually run any other functions that manipulate the DOM.
The code you put in runs on DOMReady, which means the Load
handler isn't installed until then and it may be too late by then.
jQuery(function($) {
Grumans.deli.init();
});
The above should run the Grumans code every time the page loads, but it does so on DOMReady event.