views:

32

answers:

1

It is always good to separate presentation layer and behaviour between HTML and Javascript based on head first book.

They tell me not to do:

<textarea onclick="showAlert()"></textarea>

But instead, do below:

The example below separate the behaviour from HTML code (structure).

<html>
<head>

<script type="text/javascript">
window.onload = init;

function init() {
  $('txt_area').onclick = showAlert;
}

function showAlert(say) {
  alert(say);
}
</script>
</head>
<body>
<textarea id="txt_area"></textarea>
</body>
</html>

This allows HTML (structure) to look clean and "behaviour" part is initialized in init() function when page loads. I understand that so far.

But then I wonder how am I supposed to pass an argument to showAlert() function???

Below does not work, it will call the showAlert() as soon as the page loads and this is not what I want to because it needs to be fired onclick.

function init() {
  $('txt_area').onclick = showAlert("hello");
}

Is it possible to pass arguments to showAlert() function but still separate the behaviour and structure?

UPDATE

Forgot to mention.. I'm using prototype.

+3  A: 

Wrap your code in a function.

$('txt_area').onclick = function() {
    showAlert("hello");
};
Anurag
this will surely give an error ;)
Reigel
Thanks, totally didn't think about it, js can do that!
masato-san
@Reigel: I've tested the provided code and it seems to work just fine.
masato-san
@masato-san - good for you. I find many error on that. first, `$('txt_area')` should be `$('#txt_area')`(with a `#`). second, `.onclick()` is a native JS, `$('#txt_area')` is a jQuery object. it should be `$('#txt_area').click()` XD
Reigel
@Reigel - maybe this is not jQuery? it works fine in some frameworks - http://jsbin.com/ecihe4
Anurag
@Reigel: I see.. my apology not mentioned framework, I'm using prototype.
masato-san
ahh okay. cheers!
Reigel