Skip to content Skip to sidebar Skip to footer

Only Starting A Function On Button Click?(javascript)

How would I make a start button for a function? I have 9 different functions for different animations on my page. I need to figure out how execute the animations only when a button

Solution 1:

document.getElementById('start').onclick = function(){
    animate0(0);
}

This is assuming you have an element with id='start'

Here is a fiddle: http://jsfiddle.net/maniator/TQqJ8/13/

Solution 2:

I think I may be misunderstanding your question, but if for instance you had this button (or indeed just about any other element):

<inputtype="button"id="theButton" value="Click Me">

Then you can hook up a handler for its click event in any of several ways.

  1. The simplest, but least powerful, is DOM0-style:

    document.getElementById("theButton").onclick = function() {
        animate0(0);
        returnfalse;
    };
    

    The problem with DOM0 handlers is that there can only be one handler/event type on each element.

  2. DOM2-style, which on standards-based browsers looks like this:

    document.getElementById("theButton").addEventListener('click', function(event) {
        event.preventDefault();
        animate0(0);
    }, false);
    

    ...and on older IE looks like this:

    document.getElementById("theButton").attachEvent('onclick', function() {
        animate0(0);
        returnfalse;
    });
    

Note the differences, the event name is "click" in the DOM2 standard, "onclick" for Microsoft, and the event object is passed in the first argument in the DOM2 standard, but it's a global variable (I didn't use) on Microsoft's older browsers. (Not dissing Microsoft, in the IE5 - IE6 timeframe, they did a lot to innovate web browsers, including ajax, innerHTML, and in fact multiple handlers per event per element via attachEvent, which predates the DOM2 standard. It's just after IE6 that they let the ball drop for...well...more than a decade.)

In all of those cases, I've called animate0 directly, since it does its first loop and then schedules the next bit itself. You could, of course, use setTimeout to schedule even the first bit to be asynchronous (probably just use a delay of 0, which will be 5-10 ms on most browsers). It depends on what you want to do.

Post a Comment for "Only Starting A Function On Button Click?(javascript)"