Link to home
Start Free TrialLog in
Avatar of GessWurker
GessWurker

asked on

document.getElementById('myID').onclick ?

This works:
<a id="myLink">link test</a>
<script>
document.getElementById('myLink').href="javascript:NewPop('http://mopweb05.domain.com/scripts/savesearch/SvSrch.pl?InmDB='+DbTi+'&InmHost='+window.location.hostname+'&InmBU='+BUrl+'&SvSrch='+mystr,'saveSrchWin')";
</script>

Is it possible to do more or less the same thing with onclick? If so, how? I can't get it to work.

<a href="javascript:void(0)" id="myLink">link test</a>

<script>
document.getElementById('myLink').onclick="javascript:NewPop('http://mopweb05.domain.com/scripts/savesearch/SvSrch.pl?InmDB='+DbTi+'&InmHost='+window.location.hostname+'&InmBU='+BUrl+'&SvSrch='+mystr,'saveSrchWin')";
</script>


Avatar of Xxavier
Xxavier
Flag of Canada image

<script>
document.getElementById('myLink').onclick="function x(){NewPop('http://mopweb05.domain.com/scripts/savesearch/SvSrch.pl?InmDB='+DbTi+'&InmHost='+window.location.hostname+'&InmBU='+BUrl+'&SvSrch='+mystr,'saveSrchWin');return false}";
</script>
ASKER CERTIFIED SOLUTION
Avatar of hackman_3vilGuy
hackman_3vilGuy

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of GessWurker
GessWurker

ASKER

hackman_3vilGuy: Yours worked for me. Thanks!

Can't use any quotes though, right?

document.getElementById('myLink').onclick=doSomethingClever;  <--this works

document.getElementById('myLink').onclick="doSomethingClever";<--this doesn't work
document.getElementById('myLink').onclick="doSomethingClever()";<-- this doesn't work
document.getElementById('myLink').onclick=doSomethingClever();<--this doesn't work either


Note that in the registration of an event handler you do not use brackets (). The onclick method expects to be assigned an entire function. If you’d do

element.onclick = doSomething();

the function would be executed and its result would be registered to onclick. This is not what we want, we want the function to be executed when the event takes place. In addition the function has usually been written to expect an event and if we’d execute it without any such context it would get terribly confused and produce JavaScript errors.

Instead we copy the function doSomething() to the event handler in its entirety. We do not execute it yet, that should only happen when the event actually takes place.

see http://www.quirksmode.org/js/events_tradmod.html for more info
Thanks for the solution and the great explanation!