...

View Full Version : What is wrong with this script??



2mato
07-10-2011, 11:25 AM
Hello all , I just start my self-lessons on javascript, it is pretty cool, but i have some trouble understanding some :mad:, can any one tell me what's wrong with this code, i would like when the user press the button the windows pop-ups.

the code:

<html>
<head>
<title>Hello World</title>
<script type="text/javascript" src="script.js"></script>
</head>

<body>
<form action="#">
<input type="button" value="Click Me!" id="hibut" />
</form>
</body>

</html>


--------------------------------------------

function Hibye(){
window.alert('Hello...');
window.alert('Bye');
}

var hi_button = document.getElementById('hibut');
hi_button.onclick = Hibye();

Thanks........

devnull69
07-10-2011, 11:37 AM
Two major problems

1. onclick is an event handler. As such it needs to be assigned to a function/method. You assign it to the result(!) of the execution of the function/method Hibye. You'll have to learn the difference between both


// function/method definition
function Hibye() {
...
return "something";
}

var myFunc = Hibye; // assignment of a function object to the variable myFunc
var myFuncResult = Hibye(); // assignment of the result (the return value) == "something"

onclick needs to be assigned to a function object!

2. If you try to access an element of the DOM you need to make sure that the DOM has already been loaded. The easiest way to achieve this is to put all your code accessing elements of the DOM into a function that is only executed after the DOM has finished loading


window.onload = function() {
var hi_button = document.getElementById('hibut');
hi_button.onclick = Hibye;
};

2mato
07-10-2011, 11:55 AM
Thanks ,,,,,

But this example is in the book I am learning from :eek:

I will but it in the :D, can U please send my a title or a link that i can learn JavaScript in a proper way ,,,,:thumbsup:

devnull69
07-10-2011, 12:12 PM
Which book is it? Are you sure you copied it literally? I am pretty sure that it's not in a book that way.

2mato
07-10-2011, 12:24 PM
Which book is it? Are you sure you copied it literally? I am pretty sure that it's not in a book that way.

JavaScript: A Beginnerís Guide Third Edition

Page 149

I copy it as it is , do you have a better resource for learning javaScript?

Kor
07-11-2011, 10:04 AM
http://www.howtocreate.co.uk/tutorials/javascript/important
http://www.java2s.com/Tutorial/JavaScript/CatalogJavaScript.htm



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum