views:

47

answers:

4

Is there any way to use the onClick html attribute to call more than one JavaScript method?

EDIT:

Thanks for all of the answers guys! :)

A: 

Sure, simply bind multiple listeners to it.

Short cutting with jQuery

$("#id").bind("click", function () { alert("Event 1"); });
$(".foo").bind("click", function () { alert("Foo class"); });

<div class="foo" id="id">Click</div>
Josh K
never mentioned jQuery
hunter
@hunter: I was short cutting with jQuery. I don't exactly remember the native event listener code. You could also do what Marko mentions, but it's better to use an event listener.
Josh K
+7  A: 
onClick="doSomething();doSomethingElse();"

But really you're better off not using onClick at all and attaching the event handler to the DOM node through your JS code. This is known as unobtrusive javascript.

brad
Thanks for the reference to unobtrusive JS, I've come across this before, and I should refrain from writing obtrusive JS just because I'm lazy! xD
BOSS
no probs... I also highly recommend jQuery which will really help you with your unobtrusive goal. You can easily attach event handlers to DOM elements and do much much more all unobtrusively. I've used it for 2 years now and never looked back.
brad
+3  A: 

A link with 1 function defined

<a href="#" onclick="someFunc()">Click me To fire some functions</a>

Firing multiple functions from someFunc()

function someFunc() {
    showAlert();
    validate();
    anotherFunction();
    YetAnotherFunction();
}
Marko
+1  A: 

I would use the element.addEventListener method to link it to a function. From that function you can call multiple functions. This could be useful...

https://developer.mozilla.org/en/DOM/element.addEventListener

The advantage I see in binding an event to a single function and then calling multiple functions is that you can perform some error checking, have some if else statements so that some functions only get called if certain criteria is met.

girdus