2

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

10
  • 1
    Did you read the console output? My guess is your path to your jstest.js is wrong. Is it in a js folder? Commented Sep 15, 2017 at 21:14
  • Does ist alert "clicked" if you move alert("clicked") outside the function? Commented Sep 15, 2017 at 21:14
  • 1
    Yes it does.Why doesnt the function work then? Commented Sep 15, 2017 at 21:22
  • Can you try change the button to something else. Like try <span onclick="runcode()">click me</span> and let us know if that works Commented Sep 15, 2017 at 21:25
  • 1
    The span also works Commented Sep 15, 2017 at 21:26

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Well... I did not expect this to be the problem. Thanks for the info! Also is this a common problem between elements?
@harambe it is only a problem with elements which submit or try to follow a link like <a>, <submit>, <button>. So if you try the same with a <a> tag which has a href="some-url" the same happens as it did with the <button>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.