Attaching onclick event to element is not working - javascript

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?

Related

Why isn't the javascript onclick function called?

I have created a JSFiddle to describe the issue. Why isn't the alert displayed when I call the doSomething() function?
You need to disable framework option in jsfiddle for javascript to work
DEMO
function doSomething() {
alert('Hello!');
}
This is because doSomething() function is not defined in the HTML page. In jsfiddle your function (in js pane) is wrapped by document onload event of jquery. (see at the left side of jsfiddle for settings). So Its executed like this,
$(document).ready(function() {
function doSomething() {
alert('Hello!');
}
});
See how its wrapped. Its not accessible. To fix it you should assign it to window object.
In the js pane write the function as
window.doSomething=function() {
alert('Hello!');
}
It'll work
Its recommended you do not use onclick attributes of an HTML elements. Its better to assign event handler with JS.
$("img").click(function(){
alert("Hello");
});
This is a "fiddle-thing". Pick nowrap (head) from the first selection in the "Choose Framework" field.
What JsFiddle does for you is creating the <HTML>, <head> and <body> tags for you. You shouldn't include them in your HTML, because that would make the markup invalid after JsFiddle processed it. It also wraps your JS in the document's onload event. So your function was not defined in the root scope as you thought, but in th scope of the document.onload function, and you couldn't reach it from within the body, because that is outside of that function. I changed the JsFiddle attribute 'wrap in' to 'no wrap (head)' and it worked.
Your function dosomeThing() is not defined in the page
just replace header tag with this one
<head>
<script>
function doSomething() {
alert('Hello!');
}
</script>
</head>
and then try again
Here is your complete code. just copy and paste your editor. it is
<!doctype html>
<html lang='en'>
<head>
<meta charset='utf-8'>
<title>Javascript Events</title>
<script type='text/javascript'>
window.onload = function() {
var image_one = document.getElementById('imageOne');
var image_two = document.getElementById('imageTwo');
image_one.onclick = function() {
alert('Hello!');
}
image_two.onclick = function() {
alert('Hello!');
}
}
</script>
</head>
<body>
<img id="imageOne" src="http://upload.wikimedia.org/wikipedia/commons/thumb/0/0c/White_and_yellow_flower.JPG/320px-White_and_yellow_flower.JPG" />
<img id="imageTwo" src="http://upload.wikimedia.org/wikipedia/en/7/70/Example.png" />
</body>
</html>

Basic JavaScript EventListener NOT work?

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.

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.

Result of getElementById is null?

Just struggling with a Javascript class being used as a method for some cometishian code, how do I have a constructor for this code? The following code is invalid:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<link rel="Stylesheet" href="gStyle.css" />
<script type="text/javascript" language="javascript">
// Gantt chart object
function ganttChart(gContainerID) {
this.isDebugMode = true;
this.gContainer = document.getElementById(gContainerID);
if (this.isDebugMode) {
this.gContainer.innerHTML += "<div id=\"gDebug\">5,5 | 5.1</div>";
}
}
var myChart = new ganttChart("chart1");
</script>
</head>
</html>
<body>
<div id="chart1" class="gContainer"></div>
</body>
</html>
this.gContainer is null
That is because you are running the script before the page is ready, i.e. chart1 doesn't exist yet when you call new ganttChart("chart1");. Wrap the code inside window.onload = function() { } or run it at the bottom of the page.
The problem is that your script is running too early, it's looking for an element that doesn't exist in the DOM yet, either run your script onload, or place it at the end of the <body> so your id="chart1" element is there to be found when it runs.
Problem is that you run your code before the page has loaded yet, and thus the DOM element with id chart1 does not exist at the moment the code is executed.
use
window.onload = function(){myChart = new ganttChart("chart1");};
Note that using window.onload like that will override all previously stated window.onload declarations. Something along the following lines would be better:
<script type="text/javascript">
var prevOnload = window.onload || function () {};
window.onload = function () {
prevOnload();
// do your stuff here
};
</script>
Also, untill al images are fully loaded onload will not trigger, consider using jquery & $(document).ready or similar.
:)
Regards,
Pedro

Can't write to dynamic iframe using jQuery

My goal is to dynamically create an iframe and write ad JavaScript into it using jQuery (e.g. Google AdSense script). My code works on Chrome, but fails intermittently in Firefox i.e. sometimes the ad script runs and renders the ad, and other times it doesn't. When it doesn't work, the script code itself shows up in the iframe.
My guess is these intermittent failures occur because the iframe is not ready by the time I write to it. I have tried various iterations of iframe_html (my name for the function which is supposed to wait for the iframe to be ready), but no luck. Any help appreciated!
PS: I have read various threads (e.g. jQuery .ready in a dynamically inserted iframe). Just letting everyone know that I've done my research on this, but I'm stuck :)
Iteration 1:
function iframe_html(html){
$('<iframe name ="myiframe" id="myiframe"/>').appendTo('#maindiv');
$('#myiframe').load(
function(){
$('#myiframe').ready( function(){
var d = $("#myiframe")[0].contentWindow.document;
d.open();
d.close();
d.write(html);
});
}
);
};
Iteration 2:
function iframe_html(html){
$('<iframe id="myiframe"/>').appendTo('#maindiv').ready(
function(){
$("#myiframe").contents().get(0).write(html);
}
);
};
Honestly, the easiest and most reliable way I have found when dealing with the load events on iframes uses the "onload" attribute in the actual iframe tag. I have never had much of a problem with setting the content once the "onload" event fires. Here is an example:
<html>
<head>
<script type='text/javascript' src='jquery-1.3.2.js'></script>
<script type='text/javascript'>
$(function() {
var $iframe = $("<iframe id='myiframe' name='myiframe' src='iframe.html' onload='iframe_load()'></iframe>");
$("body").append($iframe);
});
function iframe_load() {
var doc = $("#myiframe").contents()[0];
$(doc.body).html("hi");
}
</script>
</head>
<body></body>
</html>
The problem with this is that you have to use attribute tags and global function declarations. If you absolutely CAN'T have one of these things, I haven't had problems with this (although it doesn't look much different than your attempts, so I'm not sure):
<html>
<head>
<script type='text/javascript' src='jquery-1.3.2.js'></script>
<script type='text/javascript'>
$(function() {
var $iframe = $("<iframe id='myiframe' name='myiframe' src='iframe.html'></iframe>");
$iframe.load(iframe_load);
$("body").append($iframe);
});
function iframe_load() {
var doc = $("#myiframe").contents()[0];
$(doc.body).html("hi");
}
</script>
</head>
<body></body>
</html>
This is one of the most frustrating parts of the DOM and JavaScript - my condolences are with you. If neither of these work, then open up Firebug and tell me what the error message is.
false.html:
<html>
<head><title></title></head>
<body></body>
</html>
JS:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"></script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script type="text/javascript">
function iframe_html(html)
{
var id = "myiframe_" + ((new Date()).getTime());
$('<iframe src="false.html" name ="'+id+'" id="'+id+'" />').appendTo('#maindiv');
var loadIFrame = function()
{
var elIF = window.document.frames[id];
if (elIF.window.document.readyState!="complete")
{
setTimeout(loadIFrame, 100);
return false;
}
$(elIF.window.document).find("body").html(html);
}
loadIFrame();
};
$(function(){
iframe_html("<div>hola</div>");
});
</script>
</head>
<body>
<div id="maindiv"></div>
</body>
</html>
then please see this link

Categories