javascript loading problem - javascript

When i am trying to write the code like
document.getElementById('id1') after teh script tag it is showing document.getElementById(..) null or not an object..
Is it necessary to write document.getElementById('id1') in function only.
If i write this code in function then it is accepting. So what the mistake here..
and if i want to execute a function on loading of the page where to write onLoad() function.. i try to write at but it is not loading.. please help me
Thank you

In order to be sure that your dom element is loaded, you have to wait the document is loaded.
To do this you can do:
<head>
<script type="text/javascript">
function foo(){
var elem = document.getElementById("yourElem");
//...
}
</script>
</head>
<body onload="foo()">...</body>
or
<head>
<script type="text/javascript">
function foo(){
var elem = document.getElementById("yourElem");
//...
}
window.onload = foo;
</script>
</head>
<body>...</body>

If you want the script to run after the page is loaded, you can use window.onload.
<script>
window.onload = function () {
//code goes here
}
.
.
.
</script>

Put your script bellow the element you are getting will also work.
<div id="ele"></div>
<script language="javascript">
alert(document.getElementById('ele').tagName);
</script>
<div id="ele1"></div>
But unless you have special purpose, it's a good habit to write handlers in after document loaded, that is, put your code in window.onload event handler.

Related

Call function in .js file from html?

Is it possible to call a function declared in a .js file from the body of the HTML. I'm assuming the reason it won't work is because the .js file is called after the function has been called in the HTML body. Is there a way around this.
I've had a look at some answers here, but can't seem to find what I'm looking for. My apologies if it's staring at me as a beginner I may not be using the correct terminology.
jqueryfunctions.js:
function someFunction() {
// do.something;
}
index.html:
<html>
<head>
<script type="text/javascript" src="//code.jquery.com/jquery-1.8.3.js"></script>
<script src="jqueryfunctions.js"></script>
</head>
<body>
<script>
someFunction();
</script>
</body>
</html>
Here is the full/actual .js file returnedMessage() is the function I was reffering to as someFunction().
The console error I'm getting is "returnedMessage() is not defined".
$(function(){
var timer = null;
function appendmessageBox() {
$('body').append('<div id="messageBox" class="datamessagebox"> </div> ');
}
// just before body tag.
appendmessageBox();
// makes MessageBox Disappear on MouseOver
$('#messageBox').on('mouseover click', function(){
$(this).fadeOut(300);
});
function returnedMessage(message) {
if (timer) {
clearTimeout(timer); //cancel the previous timer.
timer = null;
}
$( '#messageBox' ).css('display', 'inline-block');
timer = setTimeout(function(){
$( '#messageBox' ).fadeOut( 499 );
}, 5000);
$( '#messageBox' ).append('<msg>'+message+'<br /></msg>').fadeIn( 200 );
$( '#messageBox > msg:last-of-type' ).delay(3000).fadeOut( 3000 );
setTimeout(function(){
$( '#messageBox > msg:first-of-type' ).remove();
}, 5999);
}
// This test message bellow works correctly.
returnedMessage('hello world - test 1');
});
EDIT:
you should define your function like so:
var someFunction = function() {
// do something
}
Or like so
function someFunction() {
// do something
}
But always use the function word. More information on function definition in Javascript.
More about JS file import
Javascript code is inserted between <script> tags in an HTML file
<script>
console.log("Hello World!");
</script>
You usually place those script tags inside the <head> tag. However it's recommended you put them after your <body>. This way you allow the DOM to load before you run your JS script. This is important for exemple when you want to select elements in the DOM. If you put the JS code before the actual HTML that creates this element, then JS will not find the element you would be looking for because it doesn't yet exist.
Now it's not really efficient to work with script in your HTML code so it's helpful to write JS in .js files and then import them in you HTML file like you would for a CSS file. Use the <script> to do so:
<script src="myScript.js"></script>
You can use multiple <script> tags to pull in multiple JS files. But you need to be careful of the order you write them. For instance you have a functions.js file that holds all your functions, and a menu.js that handles the menu on your application. You're using functions from the code functions.js in menu.js so you need to import the files in this order:
<script src="functions.js"></script>
<script src="menu.js"></script>
First declared, first loaded.
You can write own function like this:
Here you can see simple example: https://jsbin.com/munowupipo/edit?html,output
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Define a Function in jQuery</title>
<script src="https://code.jquery.com/jquery-2.1.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.fn.myFunction = function() {
alert('You have successfully defined the function!');
}
$(".call-btn").click(function(){
$.fn.myFunction();
});
});
</script>
</head>
<body>
<button type="button" class="call-btn">Click Me</button>
</body>
</html>
Maybe you want to take the function on document is ready, so you must to write:
<script>
$(document).on("ready", function() { yourfunction(); });
</script>

call javascript method directly from html

Hello I want to call javascript method directly from jsp.Here is my dummy code in this javascript method print1() is not calling.
<html>`
<body>
<h1>hello</h1>
<script>print1()</script>
<p>hii</p>
<script>
function print1(){
alert("hello");
document.getElementsByTagName("p").innerHTML="hey";
}
</script>
</body>
</html>
Solving this can help me to great extent.
Note-I can't call it using onload as this is only dummy code I have to apply logic to some other code
First, there are a few syntax errors in your code that need to be fixed.
Then, You will need to call the function after it is defined (or in the same <script> tag). Function hoisting does not hoist print1() in time. That is because the browser tries to execute the script as soon as it encounters it. This means when the browser sees <script>print1()</script>, it is not even aware of the rest of the file.
So you need to invoke print1() after the function is defined. In addition to the solutions in comments and the other answer, another option would be to put the script in a separate file and invoke it with defer.
printFunc.js:
print1();
In the html file:
<script src="printFunc.js" defer></script>
This will invoke print1(). Note that defer does not work if the script is not external.
Just for fun (and To see how the browser goes through <script> tags), you can even invoke the function via setTimeout:
<script>
setTimeout(function(){ print1(); }, 3000);
</script>
<script>
function print1(){
alert("hello");
document.getElementsByTagName("p").innerHTML="hey";
}
</script>
There are two options to fix the issue:
Option1: Move the call <script>print1()</script> to the end of the file (i.e., define the function first before the call and look here for clear explanation on this)
Option2: Call it during the body onload as shown below:
<body onload="print1()">
</body>
Firstly its that you can call it in body tag as "onload", Secondly "getElementsByTagName" returns array so you have to tell at which array position you want to make your change
<html>`
<body onload= "print1()">
<h1>hello</h1>
<p>hii</p>
<script>
function print1(){
alert("hello");
document.getElementsByTagName("p")[0].innerHTML="hey";
}
</script>
You can do this way also
<html>`
<body>
<h1>hello</h1>
<p>hii</p>
<script>
function print1(){
alert("hello");
document.getElementsByTagName("p")[0].innerHTML="hey";
}
</script>
<script>print1();</script>
</body>
</html>

Access object from script tag

I'm writing java script code in script tag in head like:
<head>
<script language="javascript">
object o = new object({....});
</script>
</head>
and trying to use object a in body tag
<body>
<script>
alert(o.value);
</script>
</body>
how can i access object from body???
is their any alternatives?
<head>
<script language="javascript">
var o = new Object();
o.value="a"
</script>
</head>
<body>
<script>
$(document).ready(function()
{
alert(o.value)
});
</script>
</body>
In this case var a is accessible in complete application, but one thing you need to make sure if you are using external JS files then it must be loaded when you using the variable. try onload function to assure JS is loaded and ready to use in body:
window.onload = function ()
{
alert(a);
}
Since your variable is declared outside any functions it can be accessed from anywhere in your document from the same script block or from a seperate script block like in your example. it can even be accessed from html event-attributes like this (note that its better to attach events to html elements using using js):
<button onclick="alert(a);">Click this button to open an alert!</button>

Why is external javascript library blocking javascript on my page?

Here's a very simple question that my simple mind can't answer: why isn't the anonymous and onload function below being run when I load in the external library? I am missing something really, really basic. Library.js has only one line: console.log('library'). How much more basic can one get?
<script type="text/javascript" src='js/library.js' />
<script type="text/javascript">
(function () {
console.log('anon');
})();
window.onload = function () {
console.log('onload');
} ();
</script>
Your script syntax is invalid. You should have a separate closing tag instead of the self-closing version.
<!--------- v --------->
<script type="text/javascript" src='js/library.js'></script>
You also have an issue in that you're invoking the onload function immediately.
window.onload = function () {
console.log('onload');
}/* () */;
// ^^---remove these to assign the function instead of invoking it.

how must my javascript look like to run at the end of my ASP.NET page

this code is put at the top of my asp.net page:
function Test(HtmlDocument)
{
}
How can I execute this javascript function at the end of my page?
Just invoke the function in <script> tags immediately before the </body> tag.
<html>
<head>
<!-- snip -->
</head>
<body>
<!-- snip -->
<script>
Test(document);
</script>
</body>
</html>
Simply put
<script>Test(document);</script>
In the end of your html
The best way to achieve this is using windows.onload. The event can be used to perform some task as soon as the page finishes loading. Here is an example:
<script type="text/javascript">
function my_code(){
alert(" Alert inside my_code function");
}
window.onload=my_code();
</script>
Or you can put the function at the bottom of the code without the function declaration
<script>
Your javascript code here
</script>
The easy way is to drop a script manager on the page (anywhere within the body of the page) then put something like this on the page ...
<script type="text/javascript">
Sys.Application.add_load(function () {
// do your thing
});
</script>
That executes client side when the document has finished loading.

Categories