// Devign.Sequence class if (typeof(Devign)=="undefined") var Devign={}; Devign.Sequence=function () { // private fields this.list=[]; // a list of functions this.index=-1; this.aborted=false; // public fields this.finished=false; }; // public methods Devign.Sequence.prototype={ // adds a new function add:function (sequenceFunction) { this.list.push(sequenceFunction); }, // starts the sequence from the first function // fires 'onStart' if exists start:function () { this.index=-1; this.aborted=false; this.next(); if (typeof(this.onStart)=="function") this.onStart(); }, // ends the sequence // fires 'onEnd' if exists end:function () { if (typeof(this.onEnd)=="function") this.onEnd(); this.finished=true; }, // proceeds the sequence // if the sequence has finished calls 'end' next:function () { // if sequence was aborted - ignore next statements if (this.aborted) return; this.index++; if (this.index==this.list.length) return this.end(); var currFunction=this.list[this.index]; // calls the function with the sequence as an argument if (currFunction) currFunction(this); }, // aborts the sequence by setting the index to 'not started' and the flag aborted to true abort:function () { this.index=-1; this.aborted=true; } }; var sequence=new Devign.Sequence(); sequence.add(effectElement); sequence.add(showButton); sequence.add(requestServer); sequence.add(finish); window.addEventListener("load",function () { sequence.start(); },false); function effectElement(currSequence) { var div=document.getElementById("div"); var opacity=0; var iv=setInterval(function () { opacity+=.05; div.style.opacity=opacity; if (opacity>=1) { clearTimeout(iv); currSequence.next(); } },50); } function showButton(currSequence) { var button=document.getElementById("button"); button.style.display=""; button.addEventListener("click",function (e) { currSequence.next(); button.disabled=true; button.value="Wait..."; e.preventDefault(); },false); } function requestServer(currSequence) { var div=document.getElementById("div"); var xh=new XMLHttpRequest(); xh.open("POST","/ajax_html_echo/",true); // true – async call xh.onreadystatechange=function () { if (xh.readyState==4) { div.innerHTML=xh.responseText; currSequence.next(); } }; xh.send("html=Ajax completed"); } function finish(currSequence) { alert("finish"); currSequence.next(); }
<div id="div" style="opacity:0;height:50px;width:150px;padding:4px;border:1px solid #000;background-color:#32C3D7;"> <input type="button" id="button" value="Click" style="display:none"/> </div>