Jump to content

Am I missing something to have this javascript button post a message?

johnmfuller@mac.com's Photo
Posted Aug 26 2012 05:27 PM
1312 Views

<!DOCTYPE html>
<html lang="en">
<head>
<title>John M. Fuller</title>
<script type="type/javascript">
//Javascript goes here
function hello()
{
document.getElementById('line1') .innerHTML="Hello World";
}
</script>

</head>
<body>


<div id="line1">Welcome to CSCI 4</div>
<button type="button" style="height: 26px">Click Me!</button>
<a href='#' onclick="hello()"></a>


</body>
</html>

I am most curious about the last three function lines of code, and specifically about the last two, creating a button that will post a "Hello World" message when clicked, I got a lot of this from an intro to programming (web programming obviously, and the book is O'Reilly's HTML5 Canvas. I have gone over multiple possible solutions, but as much as possible, I need to leave the fix in the last two lines of 'body' code.
Any ideas as to what I'm doing wrong? Or what I have copied or merged incorrectly from w3schools.com?

Tags:
1 Subscribe


1 Reply

0
  rachel.j's Photo
Posted Aug 27 2012 07:48 AM

Hi John,

The main problem here is actually just a tiny typo in your script tag:

<script type="type/javascript"> should be <script type="text/javascript">

Once you make that fix, this should work if you just place the onclick="hello()" on the button element (and you can remove the anchor tag), like this:

<!DOCTYPE html>
<html lang="en">
<head>
<title>John M. Fuller</title>
<script type="text/javascript">
//Javascript goes here
function hello() 
{
document.getElementById('line1') .innerHTML="Hello World";
}
</script>

</head>
<body>

<div id="line1">Welcome to CSCI 4</div>
<button type="button" style="height: 26px" onclick="hello()">Click Me!</button>

</body>
</html>



Here's how I'd do it, by moving the onclick into the Javascript itself:

<!DOCTYPE html>
<html lang="en">
<head>
<title>John M. Fuller</title>

<script type="text/javascript">
/* A function that's called when the window is loaded and the document is ready.
This function calls the function 'hello' when there's a click on #button */

window.onload = function() {
    document.getElementById('button').onclick = hello;
}

/* I've structured this function definition slightly differently, 
but it does the same thing */

var hello = function() {
    document.getElementById('line1').innerHTML = "Hello World";
}
</script>

</head>
<body>
<div id="line1">Welcome to CSCI 4</div>

<!-- I added an id to the button to make it easier to select with your js -->
<button type="button" style="height: 26px" id="button">Click Me!</button>

</body>
</html>


Hope that helps!

Rachel