JQuery - Binding / Appending to document.ready - javascript

I am working on a ASP.NET MVC 3 application that is using JQuery. In this application, I have my _Layout.cshtml file and MyView.cshtml. In _Layout.cshtml I have something like the following:
<div id="wrapper" style="background-color:Gray; height:100%;">
<div id="content" style="background-color:Silver;">
#RenderBody()
</div>
<div id="footer" style="background-color:Silver;">
Footer
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Do stuff
alert("Root Loaded");
});
</script>
In MyView.cshtml, I have the following:
<div id="contentDiv">
<!-- Page content is here -->
</div>
<script type="text/javascript">
$().ready(function () {
alert("Page Loaded");
});
</script>
At this time, the "Page Loaded" message box appears before the "Root Loaded" message. I kind of understand why this is happening. However, I would like to write a method in MyView.cshtml that gets called after the root document.ready function is called. Am I making sense? Is there a way to do this? If so, how?
Thank you

This should fire after all elements on the page are loaded, so, it should be later, than the ready event.
$(window).load(function () {
alert("Whole page Loaded");
});)

You might want to consider Queuing as suggested in the answer below:
jQuery multiple document ready queue order

Related

jQuery click action before other component load

Optimized my website with WP Rocket and delayed javascript execution with some exclusions. Excluded: /jquery-?0-9.(.min|.slim|.slim.min)?.js and js-(before|after) and my script which has code:
jQuery(document).ready(function() {
console.log('F Loaded');
jQuery('#div_id').bind('click', function() {
jQuery('#desired_element').css('display','block');
console.log('Clicked')
});
});
When I'm loading a website - getting first message in console "F loaded", but after click - action happens only after all rest scripts are loaded. Is there any way to avoid waiting for all other scripts and make that action (style add after click) immediately ? Tried with plain javascript but got same result.
You can use modern way to write click event outside the document ready you will be able to perform click outside document ready.
$(document).ready(function() {
console.log('F Loaded');
});
$(document).on('click', '#div_id', function(event){
jQuery('#desired_element').css('display','block');
console.log('Clicked')
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="div_id">Click me</div>
<div id="desired_element" style="display:none">TEST CONTENT</div>
<html>
<head><title>test</title></head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="Clickme">Click me</div>
<div id="Contentsection" style="display:none">Test Content content....</div>
<script>
$('#Clickme').on('click', function(event){
$('#Contentsection').show();
console.log('Clicked')
});
</script>
</body>
</html>

Importing an html page in a div and executing "body onload"

I'm a HTML/JS newbie.
I have an HTML page "B.html" with:
<body onload="init()" >
-----other html/js stuffs
that is loaded fine in browser.
I include B.html inside a div in "A.html" (tab) using:
<ul class="tab">
<li>Main</li>
.........
</ul>
<div id="Main" class="tabcontent"> </div>
.........
<script>
$(function(){ $("#Main").load("B.html"); });
function openTab(evt, tabName) {
.........
</script>
openTab function manage tab selections activating appropriate div
Now, opening B.html all things work fine.
Embedding B.html inside A.html as I wrote before, works except for js function that need to be initialized by "init". I cannot obviously use body onload="init()" because I'm already inside body of A.html
How I can do this?
Call the init function in the callback function of the load:
$("#Main").load("B.html", function() {
init();
});
The callback function is fired after the load has completed
More information about .load

jQuery : why is document.ready function not working properly

I am trying to learn jQuery and I am confused how document.ready() function works
$(document).ready(function(){}
In html,
<script type="text/javascript" src="jquery.js"></script>
<script src="script.js" type="text/javascript"></script>
links are at the very bottom of the document, just before the closing body tag. In my javaScript file, I have all my code inside the .ready function. Yet, when I load the page, and I hover over a link, my cursor doesn't turn into a pointer for a couple of seconds, and if I immediately scroll down, the text is not yet loaded for a couple of seconds, either.
My javaScript file has a bunch of iframes etc... so I can understand why the delay, but what confuses me is that I thought the whole point of the .ready function was that the javaScript wasn't loaded until everything else in the page was loaded first? So surely my text and my css should be working straight away? Here is my code if it helps. I can post css too if required.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>myPage</title>
<link rel="stylesheet" type="text/css" href="styles2.css">
</head>
<body>
<div id="container">
<div id="backgroundLeft"><img id='backgroundLeftImage' src="Left.jpg" width="100%"></div>
<div id="wrap">
<p id="text">...some text... <span id="firstLink" class="link">click me</span>.<span><iframe id="frame" class="rect" scrolling="no" marginwidth=0 marginheight=0></iframe>
</span> ...some more text.... <span id="secondLink" class="link">click me</span>,
</span><span>
<iframe id="frame2" class="rect" scrolling="no" marginwidth=0 marginheight=0></iframe>
</span>
... some more text... <span id="thirdLink" class="link">click me</span> </span><span>
<iframe id="frame3" class="rect" scrolling="no" marginwidth=0 marginheight=0></iframe>
</span> ... some more text...
ETC...
</p>
</div>
<div id="backgroundRight"><img id='backgroundRightImage' src="2VillesRight.jpg" width="100%"></div>
<script type="text/javascript" src="jquery.js"></script>
<script src="script2.js" type="text/javascript"></script>
</body>
</html>
js
$(document).ready(function(){
var frame = $("#frame");
frame.attr("src","iframe.html");
var frame2 = $("#frame2");
frame2.attr("src","iframe2.html");
var frame3 = $("#frame3");
etc...
var player;
frame.bind("load", function () {
player = $(this).contents().find("#firstVid");
player.on('ended', function () {
frame.removeClass("open");
});
});
$("#firsLink").click(function(){
if (frame.hasClass("open"))
{
frame.removeClass("open");
player[0].pause();
}
else {
frame.addClass("open");
player[0].play();
}
});
var player2;
frame2.bind("load", function () {
player2 = $(this).contents().find("#sylvainVid");
player2.on('ended', function () {
frame2.removeClass("open");
});
});
$("#secondLink").click(function(){
if (frame2.hasClass("open"))
{
frame2.removeClass("open");
player2[0].pause();
}
else {
frame2.addClass("open");
player2[0].play();
}
});
var player3;
frame3.bind("load", function () {
player3 = $(this).contents().find("#etienneVid");
player3.on('ended', function () {
frame3.removeClass("open");
});
});
$("#thirdLink").click(function(){
if (frame3.hasClass("open"))
{
frame3.removeClass("open");
player3[0].pause();
}
else {
frame3.addClass("open");
player3[0].play();
}
});
etc...
});
I do know my code is repetitive, I am teaching myself so focused on getting it to work for now. Why is my main page taking so long to load if all my code is inside the "document.ready"? Thanks for your time
you can instead bind your javascript to the window.load event like this
Edit: tis is not good practice and unsupported in newer versions of jQuery
$(window).load(function(){ ... });
Correct way to do this
$(window).on("load", function(){ ... });
document ready lets you access the complete markup, even if the images and iframes have not loaded yet, this is desired in most cases.
In your case however, you might want to take the time penalty of waiting for everything to load, this is that the window.load event does.
$(document).ready() will only wait for all of the page's elements to load. It will NOT wait for the iFrames to load their content.
You can refer to this post if you have more questions:
$(document).ready and iframe content
Are you sure JQuery is loading properly? The source (src) property needs to point to the correct path. I find using the developer's tools to review errors, manipulate CSS and check DOM state to be helpful when learning. I prefer Chrome.
Happened to me too. What I found that, the solution is to include the file at the bottom outside of html tag (i.e the file in which you are using $(document).ready() ).
I assume that, this is because the html document is not ready by the time when browser compiler reached at this function.

Run script in document load

I have a dialog in jQuery and I want to show the dialog when the document loads. But I don't want to put code in <body onload="showdialog();">. I want to put javascript in the main div or the footer div that works like onload in the body event. Any way to do this?
<body onload="$('#dialog').slideDown('slow');">
<div id="dialog">Dialog</div>
<footer></footer>
</body>
I want this:
<body>
<div id="dialog">Dialog</div>
<script> show dialog code in load page </script>
<footer>
// or this place =>
<script> show dialog code in load page </script>
</footer>
</body>
You want to take a look at the ready function, like so:
$(document).ready(function() {
$('#dialog').slideDown('slow');
});

Move to a div after page load. "onmouseover" works but "window.onload" does not

I have a page (and divs) that are being dynamically generated and what I need for this page to do is to scroll to a particular div immediately after the page loads. What is screwy about this code is this...
The "button" code below, when you run the mouse over it (or onclick), works perfectly. It executes the rolldownTo function perfectly. However when I try to specify to specify the same action using window.onload, nothing happens. I have included both the "button " code and the window.onload below.
<html>
<head>
<title>Help</title>
<script LANGUAGE="JavaScript1.2" type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/dojo/1.5/dojo/dojo.xd.js"
djConfig="usePlainJson : true, parseOnLoad: true">
</script>
<script type="text/javascript">
dojo.require("dojo.parser");
dojo.require("dijit.form.FilteringSelect");
dojo.require("dijit.form.TextBox");
dojo.require("dijit.layout.ContentPane");
dojo.require("dijit.layout.BorderContainer");
dojo.require("dijit.layout.TabContainer");
dojo.require("dojo.data.ItemFileReadStore");
dojo.require("dojo.window");
function rolldownTo(my_anchor){
dojo.window.scrollIntoView(my_anchor);
}
window.onload=rolldownTo('car_help');
</script>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs /dojo/1.5/dijit/themes/claro/claro.css"/>
</head>
<body class="claro">
<div dojoType="dijit.layout.BorderContainer" style="width: 100%; height: 100%;">
<div dojoType="dijit.layout.TabContainer" region="center">
<div dojoType="dijit.layout.ContentPane" title="CAR HELP" selected=true>
<button type=button id=button1 onmouseover="rolldownTo('car_help');">
scroll to car_help
</button>
........
LOTS OF DIVS LIVE IN THIS DIV, INCLUDING MY TARGET "car_help"
........
</div>
<div dojoType="dijit.layout.ContentPane" title="BIKE HELP" selected=false>
........
........
</div>
</div>
</div>
<script language="JavaScript1.2" type="text/javascript">
.... LOTS OF CODE THAT GENERATES CONTENT FOR THE DIVS ABOVE
</script>
</body>
</html>
Does anyone have an idea why a Javascript event like onmouseover or onclick would work perfectly but window.onload will not?
Your problem is this line:
window.onload=rolldownTo('car_help');
You're not assigning the function rolldownTo to as the callback for the onload event, you're executing the function and assigning the return value, in this case undefined.
You need to wrap the call with an anonymous function in order to make it work:
window.onload = function(){ rolldownTo('car_help'); };
Now the anonymous function will get called by the onload event and then call rolldownTo.
So much for the problem, as NiL has halfway pointed out (onload fires after DOMLoaded) you can use dojo.addOnLoad instead of window.onload here, but you still have to use the anonymous function for the reasons stated above.
The page load doesn't mean the the DOM tree has been fully initialized which mean that your script cannot move the div unless the tree finish working, you must wait it until finished by using the javascript Event DOMContentLoaded.
In dojo, There is a function that can be called, it waits until the browser finish the DOM Tree, you can use it as :
dojo.addOnLoad(function(){rolldownTo('car_help');});
I hope this would work for you
Best Regards
NiL

Categories