Rubytastic
Rubytastic

Reputation: 15491

Execute javascript on page load but not on button click

Tried for several times to get below Javscript to execute on page load. Currently it works only on click of "Start" button.

How could this be made excited on load of the page?

<script type="text/javascript">
function getFlashMovie(movieName) {
    var isIE = navigator.appName.indexOf("Microsoft") != -1;
    return (isIE) ? window[movieName] : document[movieName];
}
function start() {

    var active = document.getElementById("buttonstart").value == "stop";
    getFlashMovie("test").setProperty("src",  !active ? document.getElementById('url2').value: null);
    document.getElementById("start").value = active ? "buttonstart" : "buttonstop";
}
</script>

the html

  <input id="url2" type="text" value="rtmp://localhost/?streammovie=test"/>

The getFlashMovie("test").setProperty is a function to pass variable to the SWF file. On page load I want it to get executed rather than on button click.

Upvotes: 0

Views: 2191

Answers (6)

Pawel
Pawel

Reputation: 2646

what you could do is:

<body onload="start();">

if you consider using jQuery at all then you could wrap your code within:

$(document).ready(function(){

      //the code

});

the code would execute when the page has been fully loaded, but i do not advise adding the jquery library just so you can use this feature.

Upvotes: 1

sushil bharwani
sushil bharwani

Reputation: 30187

Use window.onload event to fire your code on load.


window.onload = function(){

//your code to execute
}


Upvotes: 0

Stefan
Stefan

Reputation: 5672

Just make sure the DOM has been loaded before you attempt to access any elements. Try to run your start() function at the end of the HTML like this;

  </body>
  <script type="text/javascript">
    start();
  </script>
</html>

Upvotes: 1

Shadow Wizard
Shadow Wizard

Reputation: 66389

To have your function execute on page load have such code:

window.onload = function() {
    start();
};

Upvotes: 2

Ali Khalid
Ali Khalid

Reputation: 1345

Try this:

<script type="text/javascript">
function getFlashMovie(movieName) {
    var isIE = navigator.appName.indexOf("Microsoft") != -1;
    return (isIE) ? window[movieName] : document[movieName];
}
function start() {

    var active = document.getElementById("buttonstart").value == "stop";
    getFlashMovie("test").setProperty("src",  !active ? document.getElementById('url2').value: null);
    document.getElementById("start").value = active ? "buttonstart" : "buttonstop";
}
start(); //added this
</script>

Upvotes: 1

Bogdan Emil Mariesan
Bogdan Emil Mariesan

Reputation: 5647

Use:

(function($){

 $(function(){
 // my code comes here
 });     

})(jQuery)

Upvotes: 0

Related Questions