Basic JavaScript EventListener NOT work? - javascript

I'm trying to learn the basics of JavaScript
I cant figure out why this doesn't work...it's so basic?
<html>
<head>
<meta charset="utf-8" />
<style type="text/css">
ul{
list-style-type:none;
}
div{
width:300px;
height:200px;
background-color:#0066cc;
}
</style>
<script language="text/javascript">
var testing = document.getElementById("addBtn");
testing.addEventListener("click", function(e){ alert("test") } , false);
</script>
</head>
<body>
<ul id="placeholder"></ul>
Add
</body>
</html>

The addBtn is not loaded when you attempt to access it. You should perform that action once the DOM has loaded, either by moving that code to the bottom of the file, or through the onload event:
window.onload = function() {
var testing = document.getElementById("addBtn");
testing.addEventListener("click", function(e){ alert("test") } , false);
}

When the code:
var testing = document.getElementById("addBtn");
gets run, the addBtn element has not yet been parsed. One thing you could do would be to move the <script> tag down to the bottom of the page.
Another thing you could do is run the code within the onload event. Something like:
<script language="text/javascript">
window.onload = function () {
var testing = document.getElementById("addBtn");
testing.addEventListener("click", function(e){ alert("test") } , false);
};
</script>

The other approach you can take is by using the defer attribute. As the name suggests it defers the load/execution of the script after the whole page has loaded. You just need to add the defer attribute to the opening script tag.
It just works like the window.onload.
It's something like this
<script defer type="text/javascript">
var testing = document.getElementById("addBtn");
testing.addEventListener("click", function(e){ alert("test") } , false);
</script>
And another way is that you can take this script element and put it right above the closing </body> tag. I suggest you to always put your script elements just right above your closing body tag and your code would just always work fine.

In addition to using window.onload (which is the key answer to your question), consider using <script> or <script type="text/javascript">, as the "language" attribute is deprecated. More info here.

Related

How to add onload to HTML without it being part of the body tag?

I was told to add a tag being generated in Joomla. I just need to add the onload=... between the body tags. Is there a way to add the onload=... by itself or must it be part of the tag? Thanks!
If I understand the question correctly, and you need to trigger some JavaScript to run after the document is ready without editing the body tag itself, you could add it as follows:
<script>
jQuery(document).ready(function() {
// Your code
}
</script>
Notice the lack of "$". In Joomla, avoid using $ to reference jQuery to prevent conflicts with other JS tools.
If I've completely missed the mark, please clarify in a comment.
You can bind the event handler with JavaScript.
<script>
addEventListener('load', yourFunction);
function yourFunction(event) {
// ...
}
</script>
If you add a <script> tag to the header of the page, you can then add an event listener for the page load. Or a better option is to prevent render blocking code and add the <script> tag to the bottom of the page and have it run right away, since the page is already loaded.
Render Blocking Method
<html>
<head>
<script>
window.addEventListener('load',pageLoaded,false);
function pageLoaded(e) { console.log('Loaded'); }
</script>
</head>
<body>
</body>
</html>
Non Render Blocking
<html>
<head>
</head>
<body>
<!-- All The Body Content -->
<script>
(function() {
console.log('Loaded');
})();
</script>
</body>
</html>

Attaching onclick event to element is not working

I just started learning Javascript, and I know next to nothing. I am trying to attached an onclick event to an element in my HTML.
var joinList = function() {
alert("This should display when clicked");
}
document.getElementById("header").onclick = joinList;
This is my code so far. Nothing happens when the element with the ID of header is clicked on. What am I doing wrong?
the following is my HTML code
<!DOCTYPE html>
<html>
<head>
<title>Testing Page</title>
<script src="testing.js"></script>
</head>
<body>
<h1 id="header">Andrew Dawson</h1>
</body>
</html>
The issue is, that you try to load a html element, which does not "exists" when the javascript function is executed, because the dom has not finished loading.
To make your code work, you can try following solutions:
Place your script tag below in the HTML:
<!DOCTYPE html>
<html>
<head>
<title>Testing Page</title>
</head>
<body>
<h1 id="header">Andrew Dawson</h1>
<script src="testing.js"></script>
</body>
</html>
Add an event handler to check if the window element is ready:
window.addEventListener("load", eventWindowLoaded, false);
function eventWindowLoaded(){
var joinList = function() {
alert("This should display when clicked");
}
document.getElementById("header").onclick = joinList;
}
Another solution would be to use jquery framework and the related document ready function
http://api.jquery.com/ready/
I think the solve you are looking for is
var joinList = function() {
alert("This should display when clicked");
}
document.getElementById("header").setAttribute("onclick", joinList);
Your code seems straight forward, maybe your script is running before the DOM fully loads. To keep it simple across all browsers we can place a self executing anonymous function at the end to initiate all your scripts after DOM loads.
<html>
<title></title>
<head></head>
<body>
html here!!
<script>
(function() {
//Any other scripts here
var joinList = function() {
alert("This should display when clicked");
}
document.getElementById("header").onclick = joinList;
})();
</script>
</body>
</html>
The above is purely javascript, not to be confused with the shorthand (see below) of the jquery "document onready" function (you would need to add jquery to your pages).
$(function() {
//your javascript code here
});
Why using self executing function?

Javascript: Does not change the div innerHTML

I really cannot understand why this does not work. I've tried couple of tricks but I just don't get it.
<html>
<head>
<script type="text/javascript">
alert('Hey');
var vText = document.getElementById("results");
vText.innerHTML = 'Changed';
alert(vText.innerHTML);
</script>
</head>
<body>
<div id="results">
hey there
</div>
</body>
</html>
This is working as you can see here:
http://jsfiddle.net/gHbss/
It's important that you put the JavaScript after your HTML div container.
The problem that you're facing is that the browser runs the JavaScript as it's encountered when rendering/processing the page. At this point it will alert() your message, but the relevant element, the #results div isn't present in the DOM, so nothing can be changed.
To address this, you can either place the script at the end of the page, just before the closing </body> tag, or run the code in the onload event of the body or window.
The script has to be placed after the div#results or executed onload, otherwise the element is still unknown when you try to access it.
You need to call this script in onload event
i.e
window.onload=function(){
//your code
}
<html>
<head>
<script type="text/javascript">
function onloadCall()
{
alert('Hey');
var vText = document.getElementById("results");
vText.innerHTML = 'Changed';
alert(vText.innerHTML);
}
</script>
</head>
<body onload="onloadCall()">
<div id="results">
hey there
</div>
</body>
</html>
Hope the above snippet shows you the fix

javascript tag trigger - code position on page

i use that tag to alert me when a tag has been shows up
<html>
<head>
</head>
<body>
<script type="text/javascript">
document.getElementsByTagName('iframe')[0].onload = function() {
alert('loaded');
}
</script>
<iframe></iframe>
</body>
</html>
strange , since this code working :
<html>
<head>
</head>
<body>
<iframe></iframe>
<script type="text/javascript">
document.getElementsByTagName('iframe')[0].onload = function() {
alert('loaded');
}
</script>
</body>
</html>
why the Js need to under the tag to work?
what's the problem here?
Because the code in a script tag is executed immediately. And in the first example the iframe doesn't exist at that time. But what you can do is to wrap you code into an onload (for the main page) event. E.g.:
window.onload = function() {
//your code
}
Then it doesn't matter where the code is placed.
Iframe tag does not exist at the moment you are trying to access it.
You may check that by simply alerting array length, like
alert(document.getElementsByTagName('iframe'));
Have you thought about executing your javascript after the page is loaded? You may use some frameworks like jQuery to facilitate crossbrowser issues. Or just put all your javascript code to the very bottom of body.

How to run JavaScript code before page load?

I have working in asp.net web application. Here I need to run JavaScript before page load.
I have tried:
<body oninit="funinit();" onprerender="funRender();" onload="funload();">
</body>
<script type="text/javascript" language="javascript">
function funinit() {
alert("funinit");
}
function funload() {
alert("funload");
}
function funRender() {
alert("funRender");
}
</script>
here only funload() is working.
You can use window.onpaint for such purpose like :
<script type="text/javascript">
function preloadFunc()
{
alert("PreLoad");
}
window.onpaint = preloadFunc();
</script>
I hope it helps you....
Just inline it?
<script type='text/javascript'>
alert("funload");
</script>
Or put it in a function and call it immediately. Try to put it to the topmost of your page, however since the DOM isnt loaded yet you cant get any other elements.
What is it you want to do?
just insert a <script> tag wherever inside the body you want it to run. it will be executed as soon as the parser reads it, as long as it doesn't reference an element not yet created
try to put your script in head section of the page:
<head>
<script type="text/javascript" language="javascript">
alert("funinit");
alert("funRender");
</script>
</head>
Why not Use the ClientScriptManager.RegisterClientScriptBlock Method
http://msdn.microsoft.com/en-us/library/btf44dc9.aspx

Categories