0

I have an external javascript that I need to run on a button click. How would I go about doing that?

<script type='text/javascript' src='http://tracking.somedomain.com/include.js?
domain=www.somedomain.com'></script>
<script type='text/javascript' >
if(typeof sWOTrackPage=='function')sWOTrackPage();
</script>

I need this to run on the click of an html button. Any suggestions?

user8689
  • 29
  • 1
  • 3
  • what do you mean, I need `this` to run? Did that script add anything to the global namespace? Can you provide an example of where you got those docs from? – bitoiu Feb 19 '14 at 21:57

4 Answers4

3

Pure JavaScript:

document.getElementById('theIDofYourButton').onclick = function() {
    //your code here
}

jQuery:

$('#theIDofYourButton').click(function() {
    //your code here
});
Josh Beam
  • 19,292
  • 3
  • 45
  • 68
2

You can use addEventListener():

// Assuming the button has an id of 'btn':
var btn = document.getElementById('btn');

btn.addEventListener("click", function()
{
    // Your code.
    //

});

If you need support for older browsers, check out the older way to register event listeners.

Marty
  • 39,033
  • 19
  • 93
  • 162
1

try something like this: HTML:

<input type="button" value="Do" id="doer" />

JS:

document.getElementById("doer").onclick = function() {
    if(typeof sWOTrackPage=='function') sWOTrackPage();
}

The latter Javascript isn't practice-perfect, but that's not really the point here.

If you have any questions about how this was done, please ask away in the comments

user70585
  • 1,397
  • 1
  • 14
  • 19
-1

Simplest answer. Use the onclick attribute on your HTML button

shawsy
  • 457
  • 1
  • 6
  • 23