Run javascript after page load - javascript

setup_account ui-mobile-viewport ui-overlay-c
When a page i make loads like this:
var location = location.href+"&rndm="+2*Math.random()+" #updatecomment0>*"
$("#updatecomment0").load(location, function(){});
I have multiple scripts running on the updatecomment0 div:
<div id="updatecomment0">
<div id="javascript1">hi</div>
<div style="float:right;" class="javascript2">delete</div>
</div>
I don't know how to make this other JavaScripts run after page load.
Can someone please tell me how to with this.
Thank you

Use $(document).ready().

Use jQuery, you can do this very easily.
jQuery(document).ready(function(){
alert('Your DOM is ready.Now below this u can run all ur javascript');
});

Here is a sample layout for you
<script type="text/javascript">
$(document).ready(function(){
/// here you can put all the code that you want to run after page load
function Javascript1(){
//code here
}
function Javascript2(){
// code here
}
$("#btnOK").live('click',function(){
// some codes here
Javascript1();
Javascript2();
});
});
</script>
<div id="MyDiv">
<input type="button" id="btnOK" value="OK"/>
</div>

write code inside ready
jQuery(document).ready(function(){
// write here
});
suggestion : use live or bind

Unless you need javascript to do something before the page is loaded, add your scripts to the bottom om the html document, just before the body end tag.
The page will load faster, and you can do whatever you need to, right in the js file, without the document ready functions.
If the scripts is the last to load, the DOM is already guaranteed to be "ready".

$(window).load(function() {
// code here
});

$(document).ready() is all you needed.

You can make JavaScript wait for a specified time using the setTimeout method:
.setTimeout("name_of_function()",time_in_millis);

I hope this can help you too, I had a similar issue and I fixed it by calling the following just after loading the content in the page (like after an AJAX request for a page to be shown inside a div):
(function($) {
$(document).ready(function() {
// your pretty function call, or generic code
});
}(jQuery));
Remember to not call this in the document you load, but in the function that load it, after it as been loaded.

Using vanilla Javascript, this can done thusly:
<html>
<head>
<script type="text/javascript">
// other javascript here
function onAfterLoad() { /*...*/ }
// other javascript here
</script>
</head>
<body>
<!-- HTML content here -->
<!-- onAfterLoad event handling -->
<div style="display:none;"><iframe onload="onAfterLoad();"></iframe></div>
</body>
</html>

Related

function on javascript can't remove

how to remove ALL DOM in specific id, we know http://jsfiddle.net can test javascript for all condition.
directory file:
\root
\root\index.php
\root\load.php
index.php have script tag id='index' and this index.php using .load() (jQuery) for load.php, in load.php have script tag id='load',
i try use this method (in load.php for clean DOM from index.php):
$(document).ready(function(){
$("#index").remove();
});
but this not remove DOM Function, why??
EDIT :
This trouble is DOM cant be remove
i needed is delete a < script id='index' > and DOM Function (ALL FROM THIS TAG) if i loaded "load.php"
You can't use multiple elements with same id if you want to do so you need to use classes instead:
$(document).ready(function(){
$(".index").remove();
});
UPDATE
if what you want to hide your script when you load another file you could do so by surrounding your script between a div to hide for example:
<div class="divtohide">
<script>
$(document).ready(function(){
$("button").click(function(){
$(".test").load("load.php");
});
});
</script>
</div>
and in your load.php you could create a script to remove the .divtohide div:
<script>
$(document).ready(function(){
$(".divtohide").remove();
});
</script>
Your JavaScript will be run at .load(). So, we need to remove the string before loading the content into the webpage. I decided to use $.get, which will fetch the information as text. Then I run the data through a regex that will remove script#index. From there, I then append it to the page (for testing). If you notice there is no console.log's despite it being in the source of removeIndex.html, that's because we have successfully removed the JavaScript at script#index.
$.get("http://neil.computer/stack/removeIndex.html", function (data) {
data = data.replace(/<script.+?id=["']index["'](.|[\r\n])*?<\/script>/gi,"");
$("#container").html(data);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container"></div>
removeIndex.html
This file has some sample input:
<div>
Testing stuff
</div>
<script id="index">
console.log("ignore me");
</script>
<div>
Testing more stuff
</div>

js code is not working in an external file, but works file when placed in the same html page

I have this code in the footer of my html page
<script type="text/javascript">
// using jQuery
$('video,audio').mediaelementplayer();
</script>
the above code is adding video player on the html page.
Now I have created a separate js file in which I have already have some line of code which is creating owl sliders, tooltips, number counters etc.
When I add the above code into that separate js file it does not work, instead when I keep it in the footer of the html page it works fine.
Try placing your code within $(function(){ ... }. This will execute when the DOM is loaded (currently your code is being executed before jQuery is loaded, if you check the JavaScript console, you will see an error something like $ is not defined)
$(function(){
$('video,audio').mediaelementplayer();
});
or
$( document ).ready(function() {
$('video,audio').mediaelementplayer();
});
You can read about what that is doing here. $(function() is the same as $( document ).ready()
your html(basically) should look like this:
<html>
<head>
</head>
<body>
<!-- html code here -->
<!-- add jquery lib -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- your script -->
<script src="you/file/path.js"></script>
</body>
</html>
and your jquery file:
jQuery(function($) {
// your functions here
$('video,audio').mediaelementplayer();
});
Do you have a proper link to the separate js file in your page, generally at the bottom of the body? It should look something like this:
<script type="text/javascript" src="/joyride_odoo_models/static/js/scripts.js"/>
If you've done that properly, have you tried clearing your browser cache? You may need to do that to detect new javascript files.
How do you call your external js file ?
You must add your references js before your external js file.
you must add your function on document.ready.
You may wait until jQuery is full loaded or ready.
Ex.
$(document).ready(function($) {
// Your code goes here
$('video,audio').mediaelementplayer();
});
This code goes in external js file, then you need to include the file in the HTML
<script type="text/javascript" src="path/to/your/js/file"></script>

get link post use script 'data:post.url' blogger not work

I want to show URLs on my blog with javascript or jQuery, but it did not work.
My code:
$('.elementDIV').html("<a href='data:post.url'>Link</a>")
How to change it to work?
Try to wrap your code with ready function:
$(document).ready(function() {
$('.elementDIV').html("<a href='data:post.url'>Link</a>");
});
Well as your script is in the head and the <div class="elementDIV"> </div> is in the body. when your code runs, the div hasn't loaded yet and doesn't exist. put your script somewhere after the div. the best place would be before closing the body tag:
<script type="text/javascript">
$('.elementDIV').html("<a href='data:post.url'>Link</a>")
</script>
</body>

Why can I call a javascript function from inside an event like onblur, but when I call the function at the bottom of <body> it becomes 'undefined'?

Here's a basic example of what's happening. I can understand that I'm probably calling the function in body before it's defined but then why is it so common to put javascript at the bottom of the page? I know my boss is going to say use bottom javascript so what should I do?
Also the root issue is when the page is first loaded, if there is a username from the server I need to run the CheckUsername() function. So is there a better way to do it conditionally?
<body>
<input type="text" name="username"
id="username" onblur="CheckUsername()"
maxlength="30" value="#username" />
#if (username.length > 5)
{
<script>
CheckUsername(); // this is the one that's undefined
</script>
}
#section bottomjavascript
{
<script language="JavaScript">
function CheckUsername() {
// does work
}
</script>
}
</body>
The actual body tags come from the master layout. But why can I use CheckUsername in the input tag, but I can't just call it on the page?
I decided to just remove the #section bottomjavascript so it wouldn't move any scripts in there below the body tag.. Not really a solution since this page no longer uses the master section for javascript but it works now
Put the function definition before the first call. When you call it the first time, the parser does not know what CheckUsername() is. So do this:
<body>
<input type="text" name="username" id="username" onblur="CheckUsername()" maxlength="30" value="#username" />
#section bottomjavascript
{
<script language="JavaScript">
function CheckUsername() {
// does work
}
</script>
}
<script>
$(document).ready(function() {
if (#{username.length} > 5)
{
CheckUsername(); // this is the one that's undefined
}
});
</script>
</body>
I normally put these functions in there own js file and reference them in the head of the document. That way it is defined when I need it below.
If you put the code in document.ready, then all js files should be loaded and you will be able to run the function. To do that, you have to put your if statement from razor into js.
Make the check execute when the page is loaded, like this:
#if (username.length > 5)
{
<script>
window.addEventListener("load", function() {
CheckUsername();
});
</script>
}
It does not matter where this script ends up: top, bottom, ... does not matter.
Adding Javascript before the </body> tag is recommended to prevents render blocking while the scripts load and is much better for site perception head. Adding Javascript before the </body tag will also improve the site loading speed.
You can find more about this on this topic: JavaScript in <head> or just before </body>?
To answer one question, script tags should be put just before </body> i.e just before the end of the document.
Why?
With stylesheets, progressive rendering is blocked until all stylesheets have been downloaded. Thats why its best to move stylesheets to the document HEAD, so they get downloaded first and rendering isnt blocked. With scripts, progressive rendering is blocked for all content below the script.
Use this:
<script>
window.addEventListener("DOMContentLoaded", function (event){
//do stuff
});
</script>
This checks if the page is fully loaded before firing off your function. Libraries e.g., jQuery $(document).ready automatically does this for you.

Best way to access external JavaScript file and place contents in div?

So, lets say you have a page that wants to load from a javascript file and it includes
temp.html file
<script src="example.js"></script>
<p class="one"></p>
Now in the example.js file you have a function that is
function getInfo() {
var place = "foo"
$(".one").html(place);
}
//Edit currently I call the function inside the JS file
getInfo();
My question is how would you connect the two files so that the external javascript file knows that it is pointed to the paragraph with the class one?
Normally when this is in a single page, you would call the function and the info will be set.
I have seen a getScript method and a load method for Jquery. Would that be applicable here?
Any ideas on how to approach this? If you provide some code that will be super helpful.
Thanks in advance.
Looks like you want to execute getInfo() as soon as it's defined (i.e.: example.js is loaded).
You can try this approach:
<script src="example.js" onload="getInfo();"></script>
In your example.js, change getInfo() to something like this:
function getInfo() {
$(document).ready(function() {
var place = "foo"
$(".one").html(place);
});
}
Your language is confusing, but you could use jQuery's $(document).ready function which would suffice. Generally speaking, an externally loaded file should execute where the tag is in the script.
A hack could be to place a tag before the end of your document body, give it an id, and then use $('#id').ready() there. In general though, you could just try coding the transclusion concept (I'm guessing you're used to this) from scratch using intervals and timeouts.
<div id="rdy">
</div>
</body>
Then in your file:
$('#rdy').ready(getInfo);
Just my added opinion, you should consider that Google is up to some not-so-nice things these days, they are long-gone from the "do no evil" mantra.
If we assume you have a JavaScript file that contains this content:
function getInfo() {
var place = "foo"
$(".one").html(place);
}
then your markup will look something like this:
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="example.js"></script>
<script>
$(function(){
getInfo();
});
</script>
</head>
<body>
<p class="one"></p>
</body>
</html>
$(function(){ ... }); is just the simplified version of $(document).ready(function(){ ... });. They both more or less handle the onload event, which fires when page has finished loading.

Categories