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>


GessWurkerAsked:
Who is Participating?
 
hackman_3vilGuyCommented:
function doSomethingClever()
{
NewPop('http://mopweb05.domain.com/scripts/savesearch/SvSrch.pl?InmDB='+DbTi+'&InmHost='+window.location.hostname+'&InmBU='+BUrl+'&SvSrch='+mystr,'saveSrchWin');
return false;
}

document.getElementById('myLink').onclick=doSomethingClever;
0
 
XxavierCommented:
<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>
0
 
GessWurkerAuthor Commented:
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


0
 
hackman_3vilGuyCommented:
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
0
 
GessWurkerAuthor Commented:
Thanks for the solution and the great explanation!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.