View Full Version : Assigning a function to an event
How do you do it? It's obvious for things like <body onload=etc but I want to assign my function to the onResize event of the window.
I would have guessed something like:
self.onResize=myfunction();
Sadly this doesn't work. Can anyone shed some light?
fredmv
08-31-2003, 01:30 PM
By doing that, you're now executing that function and assigning the return value of that function to the window's onresize event. What you really want to do, is this:
<script type="text/javascript">
function foo()
{
window.alert("Window is being resized.\n");
return;
}
window.onresize = foo;
</script>
This will not execute the function immediately -- It gives that certain event (resize) of the window a reference to the function -- So, as a result, the function foo will be executed when the window is resized. :thumbsup:
So all that's different is...
you used window instead of self, and you didn't include the parentheses (sp?) after foo (or myfunction).
Right?
fredmv
08-31-2003, 02:16 PM
Well - Using the self object would have worked fine too. The reason I removed the parentheses is because that is what results in the function executing. And we don't want the function to execute, we want to point a reference to it. So instead of the result of the function being the new value of the onresize event handler, the function gets executed on the onresize event.
I see.
Thanks a lot :):thumbsup:
fredmv
08-31-2003, 02:18 PM
No problem! :thumbsup:
Happy that cleared things up for you.
liorean
08-31-2003, 03:03 PM
Well, and the fact that you used onResize instead of onresize...
JavaScript is case sensitive.
Ah, my reference has it down as onResize. :)
Never mind, it works perfectly :)
brothercake
09-01-2003, 04:22 AM
Originally posted by me'
Ah, my reference has it down as onResize. :)
Never mind, it works perfectly :)
Sure, but if you're working in XHTML that's invalid, because event handler attributes should be all lower case.
Incidentally, another way to acheive the same thing is to use an anonymous function:
window.onresize = function()
{
... stuff ...
}
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.