简体   繁体   中英

Combine two javascript onclick events

I have an input button that calls a window.location.href event, and also want to add google analytics event tracking to the same button...

How would I combine these two events into one statement?

<input type="button" value="Learn More!"  onclick="window.location.href='site1'" />

and this event:

onclick="_gaq.push(['_trackPageview', '/externalsite/site1']);"

You could use jQuery.

But a quick fix is to just combine them:

<input type="button" value="Learn More!" onclick="_gaq.push(['_trackPageview', '/externalsite/site1']); window.location.href='site1'" />

Statements are separated with a semi-colon.

Concatenate both, and add them together:

<input type="button" value="Learn More!"
       onclick="_gaq.push(['_trackPageview', '/externalsite/site1']);
                window.location.href='site1';" />
<!-- Within HTML tags, newlines don't matter. For readability, I have split the 
      attributes over three lines-->

Note that the order matters . If you first use the window.location.href assignment, the second part can be ignored, because the page unloads.

<script>
function handleClick(){
  _gaq.push(['_trackPageview', '/externalsite/site1']);
  window.location.href='site1'
}
</script>
<input type="button" value="Learn More!"  onclick="handleClick()" />
<input type="button" value="Learn More!"  onclick="_gaq.push(['_trackPageview', '/externalsite/site1']); window.location.href='site1'" />

You should try moving your JavaScript off the element like so:

HTML

<input type="button" value="Learn More!" id="myBtn" />

JavaScript

(function(d, w) {
    var btn = d.getElementById('myBtn');
    btn.onclick = function() {
        _gaq.push(['_trackPageview', '/externalsite/site1']);
        w.location.href = 'site1';
    };
}(document, window));

It is always a better idea to use Unobtrusive JavaScript when you can. You can read more here:

You can combine statements with a semicolon:

<input type="button" value="Learn More!"  onclick="window.location.href='site1'" />

In your case, make sure to call the redirect as the last operation, it could be that execution is terminated when you are leaving the page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM