How to use using events in Js without html [duplicate]

0

How do I do this?

<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>
    
asked by anonymous 27.06.2016 / 17:52

1 answer

2

It is not working because by the time you get the element, it is not ready to load by JavaScript. To do this, you need to add the following line:

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

This script will run 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>
    
27.06.2016 / 17:58