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>
Related
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?
Currently I'm dealing with namespaces in javascript. As a first step I build a test page.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Namespace</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
var NSVB = NSVB || {};
NSVB.sub = {
init: function(){
alert("NSVB rocks");
$("#click-test").bind("click",NSVB.sub.clicktest());
},
clicktest: function(){
alert("clicked");
}
}
NSVB.sub.init = function(){
alert("NSVB rocks overwirtten");
$("#click-test").bind("click",NSVB.sub.clicktest());
}
$(document).bind("load", NSVB.sub.init());
</script>
</head>
<body>
<p id="click-test">click to test</p>
</body>
</html>
What I expect my code to do is:
define the namespace with the function init() and clicktest()
overwrite the function init()
handle click event on #click-test when I click it
What my Code does:
define the namespace with the function init() and clicktest()
overwrite the function init()
call clicktest()
when I click nothing happens!!
I really don't get it! Hope someone could help.
Thanks in advance.
EDIT
After some testing I've have done the following:
Remove parenthesis
$("#click-test").bind("click",NSVB.sub.clicktest);
Replace
$(document).bind("load", NSVB.sub.init);
With (one of them, what you prefer to use)
document.addEventListener("DOMContentLoaded",NSVB.sub.init,false);
or
$(document).ready(function(e) {
NSVB.sub.init();
});
Everything works fine and as expected!
You didn't bind the function but the result of the function, that is nothing.
Change
$(document).bind("load", NSVB.sub.init());
to
$(document).bind("load", NSVB.sub.init);
You have the same problem elsewhere (except of course if NSVB.puzzle.clicktest() returns a function):
$("#click-test").bind("click",NSVB.puzzle.clicktest());
I have a working JavaScript function declared in the head of an HTML page. I know how to create a button and call the function when the user clicks the button. I want to call it myself some where on the page:
myfunction();
How do I do it?
You can call it like that:
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
var person = { name: 'Joe Blow' };
function myfunction() {
document.write(person.name);
}
</script>
</head>
<body>
<script type="text/javascript">
myfunction();
</script>
</body>
</html>
The result should be page with the only content: Joe Blow
Look here: http://jsfiddle.net/HWreP/
Best regards!
I'm not sure what you mean by "myself".
Any JavaScript function can be called by an event, but you must have some sort of event to trigger it.
e.g. On page load:
<body onload="myfunction();">
Or on mouseover:
<table onmouseover="myfunction();">
As a result the first question is, "What do you want to do to cause the function to execute?"
After you determine that it will be much easier to give you a direct answer.
Just drop
<script>
myfunction();
</script>
in the body where you want it to be called, understanding that when the page loads and the browser reaches that point, that's when the call will occur.
You can also put the JavaScript code in script tags, rather than a separate function. <script>//JS Code</script> This way the code will get executes on Page Load.
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.
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