Javascript parameters

P

Paulo Almeida

Hi,

I have a Javascript function called changediv() that receives as a parameter
the
number that is the id of the element I want to change:

function changediv(divnum) {

}

On the web page I have the following code:

<div id="div1" onclick="changediv(1)">...</div>

This works OK.
But if I try to use the more modern way of associating an event with
an event handler, like,

function init() {
document.getElementById('div1').onclick=changediv(1);
}
window.onload=init;

it doesn't work because of the parameter. How can I pass a parameter
in this situation?

TIA

Paulo Almeida
 
J

Jonathan N. Little

Paulo said:
Hi,

I have a Javascript function called changediv() that receives as a parameter
the
number that is the id of the element I want to change:

function changediv(divnum) {

}

On the web page I have the following code:

<div id="div1" onclick="changediv(1)">...</div>

This works OK.
But if I try to use the more modern way of associating an event with
an event handler, like,

function init() {
document.getElementById('div1').onclick=changediv(1);
}
window.onload=init;

it doesn't work because of the parameter. How can I pass a parameter
in this situation?

Don't, just self reference with 'this'

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Example</title>

<style type="text/css">
div { margin: 1em; padding: 1em; background: #eee; }
</style>

<script type="text/javascript">
function changediv() {
var me=this;
alert("My id is " + me.id);
}

function init(){
var target=document.getElementById('div1');
target.onclick=changediv;
target=document.getElementById('div2');
target.onclick=changediv;
}

window.onload=init;

</script>

</head>
<body>

<div id="div1">Click the target DIV1</div>
<div id="div2">Click this other DIV2</div>

</body>
</html>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,817
Latest member
DicWeils

Latest Threads

Top