How to use Js events without html

Asked

Viewed 400 times

0

How do I make it spin ?

<html>
	<head>
		<script language="javascript">
			function teste(){
				alert("oi");
			}
		
				document.getElementById("as").onclick = function(){
					teste();
				}
			
			
			
			
		</script>
	</head>
	<body>
		<input type="button" id="as" value="AQUI">
	</body>
</html>

  • 2

    But "this" you posted has html, you want to use without html?

  • I expressed myself badly. I would like to know, actually, was : how to handle events without necessarily making use of EX: <body onload="//code">. Understood ?

  • Recommend to use setTimeout(function() { // CODE // }, 500); ... window.onload does not run all version browsers.

1 answer

2

It is not working because the moment you take the element, it is not yet ready to be loaded by Javascript. To do this, you need to add the following line:

window.onload = function(){
    //seu codigo vai aqui
}

This above script will be executed when the page is finally ready to be used with Javascript.

<html>
    <head>
        <script language="javascript">
            window.onload = function() {
                function teste() {
                    alert("oi");
                }

                document.getElementById("as").onclick = function() {
                    teste();
                }
            }
        </script>
    </head>

    <body>
        <input type="button" id="as" value="AQUI">
    </body>

</html>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.