getelementsbyname addeventlistener - javascript

<form>
<a name='lala'/><a name='lala'/>
</form>
<script type='text/javascript'>
var elem=document.getElementsByName('lala');
alert(elem.length);
</script>
alert pops up 0!??
so that makes it next one not working!??
for(i in elem)
elem[i].addEventListener('click',function(){alert('lala');}, false);
many thanks!!

It is not working because by the time you call document.getElementsByName
the DOM elements are not loaded yet, therefore, your document.getElementsByName('lala'); will return null.
There are several ways to perform a function just when the DOM elements are ready. The simplest way is to create a function in your <head> and call it in the load event of your body
<head>
<script type="text/javascript">
function domLoaded() {
var elem=document.getElementsByName('lala');
alert(elem.length);
}
</script>
</head>
<body onload="domLoaded();">
....
</body>
When you placed the javascript function in the end of your tag, you just began to call the code when your elements where ready. That will work too, but isn't it better to do things the right way and place all your JS code in the head element? By throwing JS code all over the code is going to make you life hell when you need to fix things.

getElementsByName is not supported by all browsers, see here for all browser compatibilities.
It works for me, however. I am running Chrome 10.0.648.127

javascript code had to be included at the bottom of the page,
so that's why folks you should always put your js code to the bottom of the page.
many thanks to everybody ;)

Related

Correct JavaScript equivalent for <body onload=>

What is the correct JavaScript way to replacement <body onload="init();">, bearing in mind that we no-longer have need to support very old browsers.
In my case I want to add a onClick event to all tags and would like to keep the Javascript separate to my HTML page.
window.onload = init();
Started off with this but found the global document object is not available inside init(), this seems to be it seems to be a timing issue. Did it work better in older browsers?
document.addEventListener("DOMContentLoaded", init, false);
Seems to be a more modern reliable way but is this supported by all modern browsers?
Then there is the suggestion to just put the init() at the bottom of the page but that is obviously getting back to having the Javascript direct in the HTML.
<script type="text/javascript">init();</script>
Is there a definitive way I should be running my init code?
I think what you want is $(function(){}), or $(document).ready(...), as Marc B mentioned. That seems to accomplish what you're asking for, unless I'm misunderstanding your question. The jQuery API backs this up.
The .ready() method offers a way to run JavaScript code as soon as the page's Document Object Model (DOM) becomes safe to manipulate.
Most simple method is adding a script tag at the end of body with a self invoking anonymous function:
<body>
<!-- content here -->
<script type="text/javascript">
(function() {
//Run init code here
})();
</script>
</body>
For external js files:
<body>
<!-- content here -->
<script src="main.js" type="text/javascript"></script>
</body>
main.js file:
(function() {
//Run init code here
})();
Now that the problem of the extra brackets has been solved the final solution which I am just about to test is:
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", init);
} else {
window.onload = init;
}
I know JQuery can do this with it's .ready event but some of these pages are very small pages of Ajax content and I would prefer to avoid the overhead of JQuery if it is not necessary.

HTML onload not calling JavaScript function

I have looked at other questions similar to this, but I haven't found an answer.
My <body onload="doStuff()"> has stopped calling the doStuff() JavaScript function. I have tried replacing <body onload="doStuff()"> with <body onload="alert('Test');"> and that creates the alert successfully.
Then I tried putting that same alert just inside the doStuff() function (and reverting the onload to call doStuff()), but the alert did not appear.
Are there any reasons why this would happen? Also, it may be relevant to note that I am almost certain that I did not make any code changes in between this working and it not working (you may not believe that, but it's true); however, I did delete a sub-folder from the server that contained a Joomla installation.
Make sure that your script tag is correct.
<script src="myscript.js" /> will cause <body onload="...">...</body> to fail.
It should be:
<script src="myscript.js" type="text/javascript"></script>
Try to move away from inline calls and utilise jQuery as it was intended. Its really good working practice, (not to mention easier to debug) by keeping your style, and script logic separate.
for body on load, use this.
$(document).ready(function () {
doStuff();
});
or it can be shortened even further to
$(function () {
doStuff();
});
For whatever reason in firefox, my Scripts declared in the body of the page was preventing inline calls from firing. I moved my script tags to the header and then it worked.
The issue with the uncaught syntax error (see comments in original post) was that, when I was converting a PHP array into a JavaScript array, something was going wrong, i.e., a weird character was being appended. I solved this by replacing my DIY PHP-array-to-JS-array code with this code:
<?php
$js_array = json_encode($resultsArray);
echo "var jsResultsArray = ". $js_array . ";\n";
?>
This isn't really connected to the headline question of the post, but it was the root problem.

Simple javascript function not working in IE7

Code works across all major browsers, but firing a simple alert on click is not working.
This is in my header
<script type="text/javascript">
function this_function() {
alert("got here mango!");
}
</script>
This is in the body
<button type="button" onclick="this_function()">click me</button>
If I put the "onclick" into the tag then it works fine and dandy.
Any and all suggestions on how to get this to work in IE would be great. Thanks in advance.
Sorry, by "into the tag" i meant putting onclick="alert()" into the tag.
Try: <button type="button" onclick="javascript:this_function();">click me</button>
It's advised to separate JavaScript and markup. Thus regardless you should assign an ID to the button and attach the onclick handler like this:
document.getElementById("button").onclick = function() {
alert("got here mango!");
};
​
Are you running this sandboxed? If you aren't I would highly suggest trying this all by its self in a single HTML file with no other things going on. It is possible that IE7 is blowing up (quietly) on another script issue that is preventing your "this_function" from loading into the DOM properly.
After you have done this put the in your there is no need for it to be in the head and I have actually seen this cause problems under certain conditions

Javascript problem solved, don't understand what the problem was

In the HTML head section:
<script type="text/javascript" src="Scripts/editScripts.js"></script>
Just above the </body> tag(closing tag, bottom of the html page). Also: this is the old code, this is how it was when it was not working:
<script type="text/javascript">if(document.getElementById)initialize();loadEvents();</script>
</body>
</html>
In the editScripts.js file:
/*global document,addFileInput*/
function loadEvents() {
var a = document.getElementById('addField');
a.onclick = addFileInput;
}
var upload_number = 2;
function addFileInput() {
var d = document.createElement("div");
var file = document.createElement("input");
file.setAttribute("type", "file");
file.setAttribute("name", "addFile[]");
file.setAttribute("size", "35");
file.setAttribute("class", "file");
file.setAttribute("id", "addFile"+upload_number);
d.appendChild(file);
document.getElementById("moreUploads").appendChild(d);
upload_number++;
}
This would not work. I replace the javascript in the footer with this.This is the new code, which does work as I expect it to.:
<script type="text/javascript">if (document.getElementById)loadEvents();</script>
And now it does work... I don't see how leaving out that function call, even though it the function it was referring to doesn't exist, would mess things up so royally.
In an unbracketed if statement, only the first statement is conditional. Every statement following it is unconditional regardless of indentation.
Thus, in the first example, loadevents() executed unconditionally.
The browser would have reported an error when attempting to call the "initialize" function since there was no such function. Therefore, the very next line where you call "loadEvents" wouldn't run. See this example:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>JS Error Test</title>
</head>
<body>
<script type="text/javascript">
if(document.getElementById) {
initialize();
alert("You shouldn't see me!");
}
</script>
</body>
</html>
In that example, the alert box shouldn't appear because I haven't declared an "initialize" function and the browser will report a JS error. Removing the "initialize" function, however, will cause the alert box to appear.
So that's how by removing the cause of the Javascript error you fixed your problem.
probably because you arent calling your scripts on document load event. so when you called your scripts in the header before your dom fully loaded, none of it worked, but now when you are calling it after the dom loads, it works.
The correct fix for all of this should be calling your scripts after the document fully loads, or at least from the body onload event:
<body onload="initScripts()">
And then add all of the scripts you want to run on page load in the initScripts function.
also, there are much better ways of doing this, for example using jquery, and/or reading this: http://onlinetools.org/articles/unobtrusivejavascript/chapter4.html
You say: "I don't see how leaving out that function call, even though it the function it was referring to doesn't exist, would mess things up so royally." That's inconsistent with the rest of your question, which implies that adding the call messed things up. But I think the text I'm quoting is the correct description.
Here's the real answer. The old code:
if(document.getElementById)loadEvents();
does not call loadEvents if getElementsById is not defined. It's not defined in all browsers.
The new code, instead, you not only leave out the function call: the semantics change as well.
if(document.getElementById)initialize();loadEvents();
always calls loadEvents, so what you want to happen always does.

javascript doesn't execute on window.load

I have a javascript that executes within a element like : <a href="javascript:doSomething();"> but it doesn't execute on window.load , anyone knows why does that happen ?
With the example above doSomething() will only be called when the user clicks on the anchor. If you want it to execute on window.load you need to put the code in the head. i.e.
<script type="text/javascript">
window.onload = doSomething;
</script>
Also, if you're going to be using the onload event a lot I would personally recommend getting jQuery and using it's 'on DOM ready' event. This way your javascript will appear seamless to the end-user and won't have a flickering effect.
Have you tried writing <body onload="doSomething();">?
Assuming you did all the other suggestions, there is always a chance that someone later in the code (after your either <body onload=... or window.onload = ...) did exactly the same, and has overriden you.
If it happens to be the case (low chance) the solution to support both of your onload hooks, is window.attachEvent("onload", doSomething)
If I understand your problem correctly, you want to set an attribute in an element, calculating it dynamically via javascript, so that when the page is loaded your link points to the return value of "doSomething()".
For that you can use javascript's DOM manipulation utility functions.
In your case something like:
<a id="myLink">my anchor</a>
...
<script type="text/javascript">
getElementById('myLink').href = doSomething();
</script>

Categories