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

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.

Related

How to trigger onclick before page is fully loaded

My website is essentially all one very long page and I've got an element I'd like to click before the page is loaded (it takes a while because it's so long), but I can't get it to trigger.
To test what could possibly be the cause of problems I made a very basic button that wrote to the console when clicked and during the loading phase it did nothing and then eventually once everything was fully loaded it worked.
The strange part is that looking up possible solutions so this problem, people unanimously say that the javascript gets loaded at whatever line it's written in the code and the link to my .js file is the second thing in the (right after ) so surely it should be loading immediately.
This isn't the full code obviously because the site is quite long, but here are the relevant parts:
"use strict";
function test() {
console.log("testingtesting");
}
function init() {
document.getElementById("buttonName").onclick = test;
}
window.onload = init;
<head>
<title>Title</title>
<script src="script.js"></script>
</head>
<body>
<button id="buttonName">
</body>
Does anyone have an explanation for why it's behaving the way it is and if there's anything I can do to change it?
When using an button you could use this method.
"use strict";
function test() {
console.log("testingtesting");
}
<head>
<title>Title</title>
<script src="script.js"></script>
</head>
<body>
<button id="buttonName" onclick="test()"/>
</body>
And if you did like to start the function as soon as its loaded, you could try a self invoking function.
(function () {
// body of the function
}());
The CODE!
$(document).ready(function() {
test();
$("#buttonName").click(function() {
test();
});
function test() {
console.log("testtest");
}
});
button {
height: 80px;
width: 80px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="buttonName">
How it works.
The question you asked is an interesting one.
I've used jquery. A library of javascript that makes most functions alot easier.
First. It doesn't actually matter (to much) where your script sits.
some people place it in the head if its IMPORTANT And reaaaaly needs to be run at the very beginning.
However for the most part you can put javascript before the closing body tag. This is something google, for SEO, approves of.
$(document).ready(function() The function here is called once the page is ready. Or does it? You'll be surprised to know that as a matter of fact its harder for you to stop the script loading before the page is fully loaded. :)
When the browser encounters a script tag when parsing the HTML, it stops parsing and gets to work on the javascript interpreter, which then ends up running the script. The html wont continue until the script execution is complete just incase you have a 'document.ready' function somewhere. This is the default behavior.
As you've written the rest ill assume you already understand what the rest of the code does.
onclick requires a separate function. But as i stated the script will be loaded much before the page is fully loaded. So you can have the onclick work before. However as the button wouldn't have loaded yet there's nothing for you to click.
Another way of approaching the problem.
function test() {
console.log("testingtesting");
}
button {
height: 80px;
width: 80px;
}
<button id="buttonName" onclick="test()"/>
Unlike your script document.getElementById("buttonName").onclick = test; This function is called in the DOM here <button id="buttonName" onclick="test()"/>
thus not requiring another line for the onclick.
Further reading
https://api.jquery.com/
https://www.innoq.com/en/blog/loading-javascript/
http://www.bardev.com/2013/01/03/browser-script-loading/

click on an image link when a web page is opened using javascript

I'm new in Javascript and this is my code
<!DOCTYPE html>
<html>
<body>
<img src="http://www.example.com/1/img" border="0" />
<script>
function () {
document.getElementById('test').click();
};
function();
</script>
</body>
</html>
I was trying to open that link when the web page is loaded but I make some errors. Any help?
The way you define and invoke function is not correct. This is invalid syntax construction as function declaration (statement staring with function keyword) requires a name to be valid javascript code.
So you either give function a name an invoke it:
function somename() {
document.getElementById('test').click();
};
somename();
.. or use IIFE (immediately-invoked function expression):
(function() {
document.getElementById('test').click();
})();
However, in your case you don't really need as you don't use it for what it's really useful, i.e. creating new scope. Simple line
document.getElementById('test').click();
would be just enough.
You don't need the example function... remove onclick="example(this)...". Since you are clicking via javascript, the normal function of the click is to go to the link specified in the href attribute anyway.
If you just want to open a new link on page load, you can also remove all the body and just use the following:
<body>
<script>
window.location.assign = "http://example.com";
</script>
</body>
Do it like this:
<!DOCTYPE html>
<html>
<body>
asdf
<script>
document.getElementById('test').onclick();
function yourfunction(){
alert("clicked");
}
</script>
</body>
</html>
What we do here is assigning the function "yourfunction()" to "onclick" of your anchor (the element). Due to the fact that your code is automatically executed when you reload the page (note that we've just posted a line of code into the script tag) you can trigger the onclick event just by using ".onclick()".
However, you're executing "yourfunction()" every time you reload the page and as you click your anchor.
The function itself is pretty boring. It just makes an alert (small window with a message and ok button) which says "clicked".
Further reading:
How can I trigger a JavaScript event click
https://developer.mozilla.org/de/docs/Web/API/GlobalEventHandlers/onclick
https://developer.mozilla.org/de/docs/Web/API/Window/alert
Some further advice. I think you are trying to achieve a "redirection" to another site as soon as you got to a domain. You probably want to do stuff like redirecting a typo ("gogole.com") to your "real" domain (google.com). This shouldn't be done with Javascript! You have to configure your webserver to do so (it's pretty easy). See this for example.
However, ther is also another approach to achieve this:
<meta http-equiv="refresh" content="0; url=http://www.example.com/">
Put this line of code into the of your document.

Breakpoints does not work in Firefox (19.0) using Firebug(1.11.2)

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>An example</title>
<script type="text/javascript">
function User(id) {
this.id = id;
};
var bob = new User(32);
var jack = new User(bob.id);
jack.id = 100; // Set a breakpoint here, but it does not stop here
alert('end of test' + jack.id);
</script>
</head>
<body>
</body>
</html>
BTW, the breakpoints works normally in chrome.
I am confused... This should be a very simple example. Is this a bug of Firefox ?
Thanks!
Looks like a bug of firebug. Adding a new line before the last statement seems to fix the issue.
Indeed, I've also reproduced it. Seems to be a bug.
Some notes however:
Generally it's recommended to minimize the execution of JavaScript directly like you're doing it, but defer it after page load. E.g. you can wrap everything in a function called init and then use addEventListener / attachListener to the load event (or write <body onload="init()">). Executing JS as-you-go in the HTML slows down the rendering of the page; all the JS must be parsed and executed, because potentially it might add some HTML elements dynamically which will alter the rendering of the HTML later on the page. So avoid computation-heavy and long scripts added to the page in this way.
You can also wrap your code in so-called IIFE (immediately-invoked function expression):
<script type="text/javascript">
(function () {
function User(id) {
this.id = id;
};
var bob = new User(32);
var jack = new User(bob.id);
jack.id = 100; // Set a breakpoint here, but it does not stop here
alert('end of test' + jack.id);
})();
</script>
In that case, Firebug properly executes breakpoints.
Note that the line numbers 13 and 14 are not marked in green in the code listing in Firebug. This is the information from Firebug that no breakpoints will hit if you put it in this line. In most cases, it means there's no JavaScript in that line (e.g.: HTML, empty line, comment etc.) but sometimes it's due to a bug in Firebug.

when and where to put javascript in html

I am new to Java script. I am practicing code.When i put my code in the head section, then i get element null, and when i put it inside body, but before element, then i also get null, but if i put it inside body, but after element then i get the element. I want to ask why i am getting null in case of the first two cases. Here is my code
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="js/attributes.js"></script> // null
</head>
<body>
<script type="text/javascript" src="js/attributes.js"></script> // null
<a id="braingialink"
onclick="return showAttributes();"
href="http://www.braingia.org" >Steve Suehring's Web Site
</a>
<script type="text/javascript" src="js/attributes.js"></script> // ok
</body>
Here is my javascript
var a1 = document.getElementById("braingialink"); //get null in first two cases
window.alert(a1.getAttribute("href"));
a1.setAttribute("href", "www.google.com");
window.alert(a1.getAttribute("href"));
function showAttributes() {
var e = document.getElementById("braingialink");
var elementList = "";
for (var element in e) {
/**
* Sometimes, especially when first programming with JavaScript, you might not know what
* attributes are available for a given element. But you don’t have to worry about that, because
* of a loop that calls the getAttribute() method.
*/
var attrib = e.getAttribute(element);
elementList = elementList + element + ": " + attrib + "\n";
} //end of for()
alert(elementList);
} //end of function showAttributes
And also tell me, placing <script type="text/javascript" src="js/attributes.js"></script>
after the a element, is the same as i write script in the script tag , like
Steve Suehring's Web Site
<script type="text/javascript">
var a1 = document.getElementById("braingialink");
alert(a1.getAttribute("href"));
a1.setAttribute("href","http://www.microsoft.com");
alert(a1.getAttribute("href"));
</script>
Are both things mean to same?
Thanks
The browser parses the document from top to bottom, and if it encounters a <script> block (whether inline script or inclusion of an external JS file) it runs that JavaScript before parsing any more of the document. If that particular code block tries to refer to any elements it can only access the ones above it in the source, i.e., the ones already parsed.
The document.getElementById() method returns null if no element is found for the id you supply, so if you try to use it to access elements below it in the source they've not yet been parsed and can't be found.
The two most common practices to deal with this are:
Put all of your script at the bottom of the <body> such that when it runs all of the elements will have been parsed.
Create an "onload" handler, that is, define a function that will be run as soon as the document finishes loading. You can do this from a script block in the <head> - the JavaScript that defines the onload function is run immediately, but then the function is executed later after everything has loaded.
Following is the simplest way to do option 2:
window.onload = function() {
var x = document.getElementById("x");
// other element manipulation here
};
There is nothing stopping you doing 1 and 2 in the same document, along with throwing some <script> blocks in the middle of the document, but most people find it neater to keep all their code in the one spot.
You're getting null in the head because the DOM has not loaded - your objects are nonexistent at that time. Use this:
window.onload = function () {
// Your code
}
Oh and also take a look at the .ready() function of jQuery here. It would certainly help the headache later on.
Normally you should put script blocks inside the head tag. You can put them in the body tag if you have a special reason, for example to make the script load later because it comes from a slow server.
The reason that you can't access the element, is that the code runs before the browser has parsed the code for the element, so the element simply doesn't exist yet.
You use the load event to run the code after the document is loaded:
window.onload = function() {
// here you put the code that needs to access the elements
}
see http://www.w3schools.com/js/ and http://www.w3schools.com/js/js_whereto.asp
You can place an unlimited number of scripts in your document, and you can have scripts in both the body and the head section at the same time.
It is a common practice to put all functions in the head section, or at the bottom of the page. This way they are all in one place and do not interfere with page content.
You need to understand how web browsers load resources into a page. Firefox -> Firebug add-on Net tab shows the timeline of how resources are loaded. If you are using jQuery or something like it (and you aught to) - then stick your code inside $(document).ready(function() { .. } - that will ensure the page has fully loaded.
Also, it's a good practise to to include your custom js last thing before </body> tag - that way page DOM would have loaded.
Have a read if you want to understand this deeper:
http://www.goodreads.com/book/show/6438581-even-faster-web-sites
and
http://www.goodreads.com/book/show/1681559.High_Performance_Web_Sites
Best would be right before the closing body tag, to not disturb the page loading and rendering at all! It's also recommended by google, for example for analytics snippet and also by facebook!
you get nulls because your script executes while the browser is still loading the page. Since the page might not yet have all elements rendered, you get nulls. you need to run the script when the page has finished loading.
put your script in to the HEAD element, and invoke it on body's onload event.

getelementsbyname addeventlistener

<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 ;)

Categories