Piyush
Piyush

Reputation: 5315

Can I have two JavaScript onclick events in one element?

Can we put two JavaScript onclick events in one input type button tag? To call two different functions?

Upvotes: 44

Views: 218199

Answers (6)

NikhilBhagoria
NikhilBhagoria

Reputation: 1

The HTML

<button type="button" onclick="buttons()">Submit</button>

The JavaScript

function buttons() {
   alert("Part 1");
   button2();
}

function button2() {
   alert("Part 2");
}

Upvotes: -1

Luca Filosofi
Luca Filosofi

Reputation: 31173

There is no need to have two functions within one element, you need just one that calls the other two!

HTML

<a href="#" onclick="my_func()" >click</a>

JavaScript

function my_func() {
    my_func_1();
    my_func_2();
}

Upvotes: 12

Sean Kinsey
Sean Kinsey

Reputation: 38046

The HTML

<a href="#" id="btn">click</a>

And the javascript

// get a cross-browser function for adding events, place this in [global] or somewhere you can access it
var on = (function(){
    if (window.addEventListener) {
        return function(target, type, listener){
            target.addEventListener(type, listener, false);
        };
    }
    else {
        return function(object, sEvent, fpNotify){
            object.attachEvent("on" + sEvent, fpNotify);
        };
    }
}());

// find the element
var el = document.getElementById("btn");

// add the first listener
on(el, "click", function(){
    alert("foo");
});

// add the second listener
on(el, "click", function(){
    alert("bar");
});

This will alert both 'foo' and 'bar' when clicked.

Upvotes: 20

Elitmiar
Elitmiar

Reputation: 36839

You could try something like this as well

<a href="#" onclick="one(); two();" >click</a>

<script type="text/javascript">
    function one(){
        alert('test');
    }

    function two(){
        alert('test2');
    }
</script>

Upvotes: 0

Piotr Rochala
Piotr Rochala

Reputation: 7781

This one works:

<input type="button" value="test" onclick="alert('hey'); alert('ho');" />

And this one too:

function Hey()
{
    alert('hey');
}

function Ho()
{
    alert('ho');
}

.

<input type="button" value="test" onclick="Hey(); Ho();" />

So the answer is - yes you can :) However, I'd recommend to use unobtrusive JavaScript.. mixing js with HTML is just nasty.

Upvotes: 51

Jacob Relkin
Jacob Relkin

Reputation: 163248

You can attach a handler which would call as many others as you like:

<a href="#blah" id="myLink"/>

<script type="text/javascript">

function myOtherFunction() {
//do stuff...
}

document.getElementById( 'myLink' ).onclick = function() {
   //do stuff...
   myOtherFunction();
};

</script>

Upvotes: 8

Related Questions