Javascript window.onLoad element content not changing - javascript

Im having a problem with changing an elements content
HTML Code:
<script type="text/javascript">
// Javascript
function promptLogin()
{
var person=prompt("Please enter your name","User");
if (person!=null)
{
x="Hello " + person + ", welcome to JBA Limited";
document.getElementById("topBar_message").innerHTML=x;
}
}
</script>
</head>
<body>
<script>window.onLoad = promptLogin()</script>
<header>
<div class="bul_header_topBar">
<p id="topBar_message">Welcome to JBA Limited</p>
</div>
I am unsure of the problem but I fear the problem is with the function being called before the webpage is loaded and therefore no id is present. Either that or have spelt/defined something wrong.
Bull

You need to strip the () from promptLogin
edit: oh yeah, and it's onload, not onLoad
bigger edit:
window.onload waits until your DOM is loaded, so there's no way it's not there. This is just a case where you are trying to pass a method that has already been run. The () at the end of promptLogin means "window.onLoad is equal to the return value of this function", not what you are looking for ("window.onLoad equals this function").
Also, once upon a time browsers were less case-sensitive when it came to these callbacks, but now they are. it's window.onload.

My guess is that your dom is not loaded yet, so when you try to "get" your element its not loaded/there yet.
You can either add what I suggest below, or leave everything as it is, except remove the onload etc.. and put that call (with the script tag) at the very bottom of your page.
//at the bottom of your page within script tags
<script>promptLogin()</script>
Put this code at the bottom (under) your dom.
add the code below to your page, at bottom within script tags.
remove this window.onLoad = promptLogin()
(function()
{
var person=prompt("Please enter your name","User");
if (person!=null)
{
x="Hello " + person + ", welcome to JBA Limited";
document.getElementById("topBar_message").innerHTML=x;
}
})()

What el_bob says is correct, however rather than just stripping () I would use the anonymous function syntax because it is more common thus more readable:
window.onload = function(){
promptLogin();
}
The main advantage of this syntax is that you can make multiple calls:
window.onload = function(){
promptLogin();
anotherFunction();
thirdFunction();
}

Related

How to access an HTML element within a self invoked function.

I am pretty new to JavaScript so I don't know the ins and outs of the language but I do have some knowledge of it. I created a self invoked function that would sort an array of zip-codes and then output it to a div element in the html file.
Unfortunately, the output isn't going into the div element because the function is executed before the html elements is ready, therefor it doesn't exist.
Is there anyway that I could access the div element within the function without having to use Window.Load, etc?
Thank you! click on the link below to view my function.
Screenshot of function
Is there anyway that I could access the div element within the
function without having to use Window.Load, etc?
Just move that code to the end of your html - after elements in question.
For example after </body>
From what I know, you can't access the DOM if it doesn't exist in that moment.
I know I know, don't use window.onload. But I assure you this is different than waiting for the DOM to load and then follow up with your calculations.
You can have a function evaluate something, then actually hang on the result and wait, and then finally fill the innerHTML when the DOMContentLoaded event has fired... or perhaps something of similar flavour, have a look at this.
<script>
const calculations = (function () {
// Super smart calculations...
var output = "Result of smart calculations";
function findWhereOutputGoes() {
return document.getElementById('output-div');
}
return {
output: output,
findWhereOutputGoes: findWhereOutputGoes,
}
})();
document.addEventListener('DOMContentLoaded', function(){ // Fires as soon as DOM has loaded
calculations.findWhereOutputGoes().innerHTML = calculations.output;
});
</script>
<div id="output-div">
</div>

Initialize more than one html element using jQuery and Javascript

I have tried to lead my html element to fire my customized JS file's method.
Third textarea appears nicely.
First and second textareas does not effect any of the settings i am trying to change in myJSFile.js file.
Here's my problem : js file loads the last textarea nicely, but cannot initialize previous ones properly using my js methods.
I'm doing something wrong with my JS file, and i'd appreciate if you help me.
P.S. : Initalizing some plugin and working on CKEditor.
Here's my HTML file :
<textarea id="myTextAreaID" name="myTextArea"></textarea>
<script type="text/javascript" src="../public/js/myJSFile.js"onload="setTextAreaValues('myTextAreaID')"></script>
<textarea id="myTextAreaID2" name="myTextArea2"></textarea>
<script type="text/javascript" src="../public/js/myJSFile.js"onload="setTextAreaValues('myTextAreaID2')"></script>
<textarea id="myTextAreaID3" name="myTextArea3"></textarea>
<script type="text/javascript" src="../public/js/myJSFile.js"onload="setTextAreaValues('myTextAreaID3')"></script>
Here's myJSFile.js file
var textAreaID;
$(function(){
var myTextArea = $('#'+textAreaID);
//something is being loaded here, and it is loaded fine.
});
function setTextAreaParameters(param){
textAreaID = param;
}
Thanks in advance.
This is not very good idea to do it like this, however it's interesting to understand why it happens. In your code below you are defining global variable textAreaID:
var textAreaID;
$(function() {
var myTextArea = $('#' + textAreaID);
//something is being loaded here, and it is loaded fine.
});
function setTextAreaParameters(param) {
textAreaID = param;
}
This script is injected three times into document. After the last script tag the value of textAreaID variable will be myTextAreaID3, because it's global and the last setTextAreaParameters invocation will override previous. Remember that scripts are loaded synchronously in your case (no async or deferred attribute), it means that onload callbacks don't wait and immediately set textAreaID to new values.
However DOMContentLoaded event has not yet fired. This is the event you are subscribing with this code:
$(function() {
// DOMContentLoaded
});
When it eventually does - only the third textarea will be processed - the one with id myTextAreaID3.
Better approach would be to have only one script tag and set textareas the same className attribute:
<textarea id="myTextAreaID2" name="myTextArea2" class="editor"></textarea>
Then in the script probably have some sort of map with configuration parameters for each individual textarea.
You are including the same script three times, but the browser is probably smart enough to only load it once (no reason to load the same script on the same page more than once).
What you need to do is to include the script only once, say before the end of the body tag
...
<script type="text/javascript" src="../public/js/myJSFile.js"></script>
</body>
and then in the JS file, wait for the document to load, and handle all text areas accordingly:
$(function() {
$('textarea').each(function(i, j) {
console.log('do something for the ' + i + 'th text area');
});
})

getElementById() not working

The following code is somewhere between my head tags:
<script type="text/javascript" src="js/jquery-2.0.3.js"></script>
<script type="text/javascript" src="js/homepage.js"></script>
Somewhere in the body:
<input type="text" id="registreervoornaam" name="registreervoornaam" placeholder="Voornaam">
In my homepage.js:
window.onload=function(){
var regname = document.getElementById("registreervoornaam");
regname.focus = function() {
alert("bla");
};
};
Somehow I do not get an alert when focussing on the input field. Any idea's on what this might be? I added the function in the onload because otherwise regname will become null as the javascript file is parsed before the body.
What i would do to solve this:
See if the value returned by getElementById is null. If it is, it means that your element doesn't exist in the page. If that is the case, you may want to put all of your scripts at the end of the markup file, so that when the scripts are loaded, the whole DOM has already been loaded.
If you are already importing jQuery, why not use it? :D I would just do:
$("#registreervoornaam").focus(function() {
//do stuff here that you want to be triggered on focus
});
i just realised that there is no "focus" in plain js :/ I would use onfocus instead. Here are more details about it >> here
Good luck! :D
If you're going to set up the event handler that way, the property name is "onfocus", not "focus".
regname.onfocus = function() {
alert("bla");
};
And if you have jQuery on your page you could write :
$(function(){
$("#registreervoornaam").onfocus= function() {
alert("bla");
};
});

Div is not created before javascript run

I have a question about javascript/html.
First, I have this:
var post = document.body.getElementsByClassName("post");
var x=post[i].getElementsByClassName("MyDiv")[0].innerHTML;
I get from the debugger that x is not defined, it doesn't exists.
This javascript function runs onload of the body. I am sure that I gave the right classnames in my javascript, so it should find my div.
So, I read somewhere that sometimes javascript does not find an element because it is not yet there, it is not yet created in the browser ( whatever that means).
Is it possible that my function can't find the div with that classname because of this reason?
Is there a solution?
So, I read somewhere that sometimes javascript does not find an element because it is not yet there, it is not yet created in the browser ( whatever that means).
Browsers create the DOM progressively as they get the markup. When a script element is encountered, all processing of the markup stops (except where defer and async have an effect) while the script is run. If the script attempts to access an element that hasn't been created yet (probably because its markup hasn't been processed yet) then it won't be found.
This javascript function runs onload of the body.
If that means you are using something like:
<body onload="someFn()"...>
or perhaps
<script>
window.onload = function() {
someFn();
...
}
</script>
then when the function is called, all DOM nodes are available. Some, like images, may not be fully loaded, but their elements have been created.
If it means you have the script in the body and aren't using the load event, you should move the script to the bottom of the page (e.g. just before the closing body tag) and see if that fixes the issue.
Okay, instead of calling functions with
body onload, use jQuery's ready() function, or, if you don't want to use jQuery, you can use pure javascript, but this is up to you:
// jQuery
$(document).ready(function() {
var post = document.getElementsByClassName("post"),
x = post[i].getElementsByClassName("MyDiv")[0].innerHTML;
});
// JavaScript
window.onload = function initialization() {
var post = document.getElementsByClassName("post"),
x = post[i].getElementsByClassName("MyDiv")[0].innerHTML;
}
A few side notes, I don't know what the use of innerHTML
is, and also if you're doing a for loop with i then definitely
post that code, that's kind of important.
After some discussion, my answer seems to have worked for you, but you can also place your script at the end of your body tag as #RobG has suggested.

Can I put a script at the bottom of a web page, but call it from the top?

Could this cause potential problems:
<HTML>
<BODY>
...
<INPUT name="xyz" onchange="myFunction();">
...
<SCRIPT>
function myFunction()
{
...
}
</SCRIPT>
</BODY>
</HTML>
What happens if the page loads slowly and the form renders before the script portion at the bottom is loaded? Will a JavaScript error occur if the user enters some text into the INPUT box?
You need to load the script before you can call it. Why don't you change it to something like this:
<input name="xyz" id="myInput">
...
<script>
function myFunction
{
...
}
window.onload = function() {
var myInput = document.getElementById('myInput');
myInput.onchange = myFunction;
}
</script>
This approach allows you to separate your markup and scripting and have all of your js in one place.
JavaScript development has changed over the years.
Not only is your original question being debated, but to go back to the theme of your original question, so is your methodology itself.
I highly recommend reading this short bit on some JavaScript best practices:
http://www.catswhocode.com/blog/best-practices-for-modern-javascript-development.
It works, though it may be a problem if you loaded more HTML and it took longer for the browser to parse your JavaScript at the end. In that case, your function won't be defined and you will get...
myFunction() is not defined
Note you need to add open and closing parenthesis (( & )) after myFunction.
Whilst functions declarations are hoisted, they are only hoisted in their containing script block.
Also, you should really use lowercase tags, it isn't 1998 anymore :) And a doctype also helps, and finally, you should try and remove your event handlers from inline attributes.
The script needs to be defined in the DOM prior to it being executed. If script is at the bottom it needs to be loaded prior to use.

Categories