Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
6
rated 0 times [  11] [ 5]  / answers: 1 / hits: 15266  / 14 Years ago, sat, july 17, 2010, 12:00:00



how can i add more behaviour to existing onclick events e.g.
if the existing object looks like



<a href=http://abc onclick=sayHello()>link</a>
<script>
function sayHello(){
alert('hello');
}

function sayGoodMorning(){
alert('Good Morning');
}
</script>


how can i add more behavior to the onclick that would do also the following



alert(say hello again);
sayGoodMorning()


Best Regards,
Keshav


More From » html

 Answers
45

Here's the dirtiest way :)



<a href=.. onclick='sayHello();alert(say hello again);sayGoodMorning()'>.</a>


Here's a somewhat saner version. Wrap everything into a function:



<a href=.. onclick=sayItAll()>..</a>


JavaScript:



function sayItAll() {
sayHello();
alert(say hello again);
sayGoodMorning();
}


And here's the proper way to do it. Use the event registration model instead of relying on the onclick attribute or property.



<a id=linkId href=...>some link</a>


JavaScript:



var link = document.getElementById(linkId);
addEvent(link, click, sayHello);
addEvent(link, click, function() {
alert(say hello again);
});
addEvent(link, click, sayGoodMorning);


A cross-browser implementation of the addEvent function is given below (from scottandrew.com):



function addEvent(obj, evType, fn) {
if (obj.addEventListener) {
obj.addEventListener(evType, fn, false);
return true;
} else if (obj.attachEvent) {
var r = obj.attachEvent(on + evType, fn);
return r;
} else {
alert(Handler could not be attached);
}
}


Note that if all 3 actions must be run sequentially, then you should still go ahead and wrap them in a single function. But this approach still tops the second approach, although it seems a little verbose.



var link = document.getElementById(linkId);
addEvent(link, click, function() {
sayHello();
alert(say hello again);
sayGoodMorning();
});

[#96198] Thursday, July 15, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
stacie

Total Points: 476
Total Questions: 92
Total Answers: 102

Location: Bosnia and Herzegovina
Member since Tue, Mar 29, 2022
2 Years ago
stacie questions
Fri, Jun 26, 20, 00:00, 4 Years ago
Thu, Jan 23, 20, 00:00, 4 Years ago
Fri, Aug 30, 19, 00:00, 5 Years ago
Fri, Aug 2, 19, 00:00, 5 Years ago
;