Calling 2 events on onclick

Asked

Viewed 733 times

1

I’m developing a website, and I need to trigger two events when a text is clicked. A js function, and a google Analytics goal tracking code. Following example

function shownumber() {
    document.getElementById("number").innerHTML = "<small>(62)</small> 9999-9999";
}
<p class="fixed__box__number" id="number">
    <small>(62)</small> 9999-99...
    <span onclick="shownumber();ga('send', 'event', 'Telefone', 'Clicar');">ver telefone</span>
</p>

As I am doing on the localhost I cannot test whether the two are working. And I don’t think I am, because I changed the order of the call to the function and didn’t activate the function, so the code I sent here isn’t working.

How would you add 2 events to onclick with native Javascript? Is there another way to make this easier/right.

1 answer

3


You can do it two ways:

Usa (A(), B(), C()) to invoke multiple actions:

onclick="(foo('html'), bar('html'))"

or do everything in Javascript:

var button = document.querySelector('button');
button.addEventListener('click', function() {
    foo('addEventListener');
    bar('addEventListener');
});

An exmeplo with both versions below:

function foo(quem) {
    console.log('foo', quem);
}

function bar(quem) {
    console.log('bar', quem);
}

var button = document.querySelector('button');
button.addEventListener('click', function() {
    foo('addEventListener');
    bar('addEventListener');
});
<button type="button" onclick="(foo('html'), bar('html'))">Clica-me</button>

jsFiddle: https://jsfiddle.net/dheqgokq/

  • Brother, I am very beginner in javascript, and I didn’t get much of this code. There is some more explanatory solution or with my problem applied, in fact?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.