Properly calling a body onload event handler in jQuery - javascript

My doOnLoad function is not running when page is loaded. Any idea what is wrong with my code?
<script type="text/javascript" src="../js/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="../js/events.js"></script>
<script type="text/javascript">
$(document).ready(function() {
//Not working. How do I get this function to run when the body is loaded?
$("body").load(function() {
doOnLoad();
});
//doOnChange is running properly
$('#mydirection').change(function() {
doOnChange();
})
});
</script>

From http://api.jquery.com/ready/:
The .ready() method is generally incompatible with the <body onload=""> attribute. If load must be used, either do not use .ready() or use jQuery's .load() method to attach load event handlers to the window or to more specific items, like images.

Related

Shopify app theme extensions jQuery not loading/not working

I'm trying to create a theme app extension for shopify to run some javascript when the add to cart button is clicked. As an example:
<head>
<script type="text/javascript" src={{ 'jquery-3.6.0.js' | asset_url }} defer></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js" rel="preload" defer="defer"></script>
</head>
...
<button id="add-btn">click me!</button>
<script>
jQuery( document ).ready(function() {
$('#add-btn').on('click', function(event){
alert("clicked")
})
});
</script>
This is within a sheet app extension in the blocks folder.
It seems like jquery isn't loading, and I get an error
Uncaught ReferenceError: jQuery is not defined
Any ideas why?
Summary: You are loading the jQuery library using the defer keyword so that it doesn't block the page load, but are referencing jQuery before the page finishes loading.
By loading jQuery using the defer attribute on the script tag, the browser will start loading the script immediately but won't execute the script until the DOM content has loaded:
<script type="text/javascript" src={{ 'jquery-3.6.0.js' | asset_url }} defer></script>
However, the inline script tag further down the page will be run immediately when the browser gets to it:
<script>
jQuery( document ).ready(function() { // ERROR! jQuery library hasn't been run yet, so we can't use jQuery to select the document!
$('#add-btn').on('click', function(event){
alert("clicked")
})
});
</script>
Since deferred scripts are executed in the order that they are defined, your instinct might be to try putting the defer keyword on the inline script tag - but unfortunately, defer and async only apply to external script files.
There are several ways that we could resolve this timing issue. Two possibilities are:
1: Move the inline script to an external Javascript file
If you create an external JS file, you can load the script using the defer keyword as all deferred scripts execute in the order that they were called once the DOM is ready. As an added bonus, you wouldn't need to wrap your function with the jQuery(document).ready as you would already know that the document is ready when the script executes.
2: Use vanilla Javascript rather than jQuery to set up your event listener
If the inline script tag makes sense, then using vanilla Javascript to set up your event will solve your issue. The equivalent code would be to use the addEventListener function to listen for the DOMContentLoaded event:
<script>
// This event is created before the DOM is loaded, so jQuery doesn't exist yet
document.addEventListener('DOMContentLoaded', function() {
// This event will be run after the deferred scripts above, so jQuery exists now
$('#add-btn').on('click', function(event){
alert("clicked")
})
});
</script>

jQuery not running locally

I have the following links declared inside the head tag:
<script type="text/javascript" src="javascript/jquery-3.1.0.min.js"></script>
<script type="text/javascript" src="javascript/scripts.js"></script>
And the following code inside the scripts file:
$("#person").hover(function() {
// trigger the mouseover event
$("#person-text span").addClass("important-info");
}, function() {
// trigger the mouseout event
$("#person-text span").removeClass("important-info");
});
$(document).ready(function(){
console.log( "ready!" );
});
I have also tried adding the jQuery library through Google and Microsoft CDNs, but it didn't work as well.
Here is a screenshot from the console errors:
I had a similar problem few days back. I moved the custom script tag at the end of the HTML page and the code worked. It generally happens for the $(document).ready() function.
<script type="text/javascript" src="javascript/scripts.js"></script>
Move the above line to the end of your Html page and that should work.
try using $(document).ready(function(){/*your code*/}) and try to change if your browser console showing 404 error for jQuery file
<script type="text/javascript" src="javascript/jquery-3.1.0.min.js"></script>
to
<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.0.min.js
"></script>

Object has no method 'dialog'

I'm getting this error:
Uncaught TypeError: Object [object Object] has no method 'dialog'
This is my relevant HTML
<!DOCTYPE html>
<html lang="en">
<head>
<script src="/Scripts/modernizr-2.0.6-development-only.js"></script>
</head>
<body>
<div id="deleteConfirmationDialog" title="Confirm Withdrawl">
Are you sure?
</div>
<div class="appl-appliedfor">
<a class="deleteLink" href="/Applicant/WithdrawApplication/2">
<img class="appl-withdrawApplication"
src="/Content/Images/Delete.png" alt="Withdraw Application" />
</a>
</div>
<script src="/Scripts/Prime/jquery-1.8.2.min.js"></script>
<script src="/Scripts/Jqueryui/jquery-ui-1.9.2.custom.min.js"></script>
<script src="/Scripts/OnBoard/jquery-form-min.js"></script>
<script src="/Scripts/Prime/bootstrap.min.js"></script>
<script src="/Scripts/Prime/json2.js"></script>
<script src="/Scripts/Prime/selectivizr-min.js"></script>
<script src="/Scripts/Prime/jquery.cookie.js"></script>
<script src="/Scripts/Prime/jquery.maskedinput-1.3.min.js"></script>
<script src="/Scripts/OnBoard/OnBoardAll.js"></script>
<script src="/Scripts/OnBoard/ApplicantAll.js"></script>
<script src="/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script>
<script src="/Scripts/MvcFoolproofJQueryValidation.min.js"></script>
<script src="/Scripts/mvcfoolproof.unobtrusive.min.js"></script>
<script src="/Scripts/jqueryui/jquery.ui.dialog.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#deleteConfirmationDialog').dialog({
autoOpen: false,
modal: true
});
});
$('.deleteLink').click(function(e) {
$('#deleteConfirmationDialog').dialog({
buttons: {
"Yes - Withdraw Application": function() {
$(this).dialog("close");
},
"No - Do Nothing": function() {
e.preventDefault();
$(this).dialog("close");
}
}
});
$('#deleteConfirmationDialog').dialog("open");
});
</script>
<script type="application/json" id="__browserLink_initializationData">
{"appName":"Chrome","requestId":"28b6a62eb1fb42829a3191b7c3e270d4"}
</script>
<script type="text/javascript"
src="http://localhost:61108/d90608e9d0044daf98eb343c1b3769d7/browserLink"
async="async"></script>
</body>
</html>
Everywhere I've searched the error is because you have to include jquery and jquery UI.
I've tried including JQuery UI with and without jquery.ui.dialog. No Luck.
What am I missing? Thanks for reading.
Edit
The error points to the this line:
$(document).ready(function() {
$('#deleteConfirmationDialog').dialog({
if I type $.dialog in the console I get undefined
If I reference jquery.ui.dialog.js there is the following error:
Uncaught TypeError: Object function (a, b) { return new p.fn.init(a, b, c) } has no method 'widget'
otherwise there is no other error.
I get 200 OK's for everything.
I've removed the displayed javascript code in to its own file and referenced it last. I have also moved the function that was outside the document.ready event function to inside this function, still getting the same error.
I can see jquery-ui and jquery in the Sources tab.
I don't understand why I can see jqueryui in the sources tab but typing $.dialog in the console results in undefined
Only code that doesn't use external libraries and code that doesn't use the DOM may be executed directly in a <script> tag.
If you search for DOM Elements directly in a <script> tag without waiting for the Document / DOM to be ready, the elements that you are searching for may not exist yet (in the DOM) or they may be incomplete.
Also using JavaScript methods directly in a <script> tag without waiting for the Document / DOM to be ready, the external files might have not been downloaded yet which means the methods from those external files might not exist yet.
In order to be sure that nothing like that occurs you need to put the code inside an event handler -- this ensures the code will be executed only after the event is triggered. The necessary event is $(document).ready(event_handler_function) also shorthanded as $(event_handler_function)..

jQuery $(document).ready () fires twice

I've been sifting around the web trying to find out whats going on here and I have not been able to get a concrete answer.
I have one $(document).ready on my site that seams to run multiple times regardless of the code that is inside it.
I've read up on the bug reports for jQuery about how the .ready event will fire twice if you have an exception that occurs within your statement. However even when I have the following code it still runs twice:
$(document).ready(function() {
try{
console.log('ready');
}
catch(e){
console.log(e);
}
});
In the console all I see is "ready" logged twice. Is it possible that another .ready with an exception in it would cause an issue? My understanding was that all .ready tags were independent of each other, but I cannot seem to find where this is coming into play?
Here is the head block for the site:
<head>
<title>${path.title}</title>
<meta name="Description" content="${path.description}" />
<link href="${cssHost}${path.pathCss}" rel="stylesheet" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript" charset="utf-8"><!----></script>
<script src="media/js/fancybox/jquery.fancybox.pack.js" type="text/javascript" ><!-- --></script>
<script src="/media/es/jobsite/js/landing.js" type="text/javascript" ><!-- --></script>
<script src="/media/es/jobsite/js/functions.js" type="text/javascript"><!-- --> </script>
<script src="/media/es/jobsite/js/jobParsing.js" type="text/javascript" charset="utf-8"><!----></script>
<script src="/media/es/jobsite/js/queryNormilization.js" type="text/javascript" charset="utf-8"><!----></script>
<script src="${jsHost}/js/jquery/jquery.metadata.js" type="text/javascript" charset="utf-8"><!----></script>
<script src="${jsHost}/js/jquery/jquery.form.js" type="text/javascript" charset="utf-8"><!----></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.7/jquery.validate.min.js" type="text/javascript" charset="utf-8"><!----></script>
<script src="${jsHost}/js/jquery.i18n.properties-min.js" type="text/javascript" charset="utf-8"><!----></script>
<script type="text/javascript" charset="utf-8">
function updateBannerLink() {
var s4 = location.hash.substring(1);
$("#banner").attr('href','http://INTELATRACKING.ORG/?a=12240&c=29258&s4='+s4+'&s5=^');
}
</script>
</head>
Pay no attention to the JSP variables, but as you can see i'm only calling the functions.js file once (which is where the .ready function exists)
The ready event cannot fire twice. What is more than likely happening is you have code that is moving or manipulating the element that the code is contained within which causes the browser to re-execute the script block.
This can be avoided by including script tags in the <head> or before the closing </body> tag and not using $('body').wrapInner();. using $('body').html($('body').html().replace(...)); has the same effect.
It happened to me also, but I realized that the script had been included twice because of a bad merge.
This happened to me when using KendoUI... invoking a popup window would cause the document.ready event to fire multiple times. The easy solution is to set a global flag so that it only runs once:
var pageInitialized = false;
$(function()
{
if(pageInitialized) return;
pageInitialized = true;
// Put your init logic here.
});
It's sort of hack-ish, but it works.
Make sure you don't include JS file twice. That was my case
You might consider to use
window.onload
instead of
$(document).ready
try putting this in your functions.js to prevent it from being executed twice :
var checkit = window.check_var;
if(checkit === undefined){ //file never entered. the global var was not set.
window.check_var = 1;
}
else {
//your functions.js content
}
however i suggest that you look more into it to see where are you calling the second time.
I had a similar problem when I was trying to refresh a partial. I called a return ActionResult instead of a return PartialViewResult. The ActionResult caused my ready() to run twice.
There is a possibility to encounter this problem when you add same controller twice in the html.
For an instance:
[js]
app.controller('AppCtrl', function ($scope) {
$(document).ready(function () {
alert("Hello");
//this will call twice
});
});
[html]
//controller mentioned for the first time
<md-content ng-controller="AppCtrl">
//some thing
</md-content>
//same controller mentioned again
<md-content ng-controller="AppCtrl">
//some thing
</md-content>
I had a similar issue today. A <button type="submit"> caused the $(document).ready(...) event to fire again in my case. Changing the code to <button type="button"> solved the issue for me.
See document.ready function called again after submit button? here on stackoverflow for more details.
In my case $(document).ready was firing twice because of bad CSS, check if any part of your CSS has background-image: url('');
If the iframe doesnt show anything and is used for other reasons (like uploading a file without reload) you can do something like this :
<iframe id="upload_target" name="upload_target" style="width:0;height:0;border:0px solid #fff;"></iframe>
Notice that src is not included that prevents the second on ready trigger on the document.
I had this problem with window.load function was executed twice:
The reason was because I had reference to the same javascript-file in the main page as well as a .net usercontrol. When I removed the reference in the main page, the load-function was only executed once.
I had this happen to me this morning... and what I discovered after closely examining some html code in a jquery modal form that I had recently manipulated, that I'd accidentally removed a closing table tag. I haven't taken the time yet to fully understand why that caused the document.ready function to be called twice, but it did. Adding the closing table tag fixed this issue.
jQuery JavaScript Library v1.8.3 (yes, it is a legacy app)
My problem was that I had tags referencing my JS file in both my index.cshtml file AND my _Layout.cshtml. This was causing the document.ready function to fire twice, which was causing DataTables to bomb.

Defer parsing JavaScript files

I read that deferring the JavaScript files leads to smooth opening of the page and less load time..... using the:
<script type="text/javascript" defer="defer">
alert(document.getElementById("p1").firstChild.nodeValue);
</script>
<script type="text/javascript" defer="defer">
alert(document.getElementById("p1").firstChild.nodeValue);
</script>
<script type="text/javascript" defer="defer">
alert(document.getElementById("p1").firstChild.nodeValue);
</script>
I am referring to the "defer" in the above code but I read that it only works in IE. Is there any other method for deferring the parsing of JS? I already have compressed it.
You could just remove 2 of the script-elements and add an onload in the first. In this onload-function you can write the script-elements to the dom and they will be loaded async. Check out this link: Dynamic javascript loading
I should attach a event on the window.onload that fires when the window has been loaded.
example:
function deferMethod() {
// you're code here
}
// Check for browser support of event handling capability
if (window.addEventListener)
window.addEventListener("load", deferMethod, false);
else if (window.attachEvent)
window.attachEvent("onload", deferMethod);
else
window.onload = deferMethod;

Categories