dimstef
dimstef

Reputation: 55

Javascript script doesn't work with html

I just got into web development and decided to create a test project to see how things work.

My html code is:

<!DOCTYPE html>
<html>

<head>
    <title>
        title
    </title>
    <script type="text/javascript" src="jstest.js"></script>
</head>

<body>
    <h1>heading1</h1>
    <button onclick="runcode()">click me</button>
</body>



</html>

And the script is this:

function runcode(){
alert("clicked"); 
}

I don't exactly know why the script is not working. I have put it right before the to ensure that the button loads first but it still didn't work

Upvotes: 2

Views: 2015

Answers (1)

caramba
caramba

Reputation: 22480

After the comments, can you change the code you have with those little bits:

function runcode(event){
    event.preventDefault();
    alert("clicked"); 
}
<h1>heading1</h1>
<button onclick="runcode(event)">click me</button>

From MDN Webdocs about the button type they say:

The type of the button. Possible values are: submit: The button submits the form data to the server. This is the default if the attribute is not specified, or if the attribute is dynamically changed to an empty or invalid value.

That's means, you click the button which then submit's data and depending on the setup it refreshes the page. This is why you don't see the alert. The alert happens after the submit. Now the event.preventDefault()

method tells the user agent that if the event goes unhandled, its default action should not be taken as it normally would be.

So with that you stop it from doing the default stuff. Because now you want your function to work, which in first place has to stop the default behaviour to move on whith whatever you want. In this case alert something.

Upvotes: 3

Related Questions