1

I'm completely new to javascript and html and my hello world script isn't working. I want to get a button to trigger an alert. Here's the code:

<!DOCTYPE html>
<html>
<head>
    <title>hello world</title>
</head>
<body>
    <button type="button" onclick="click()">
        click me
    </button>   
    <script>
        function click(){
            alert("hello world");
        }
    </script>
</body>
</html>
2
  • It conflicts with default click function of element, but you do nothing for the click function. Commented Mar 23, 2018 at 4:01
  • Possible duplicate of javascript function name cannot set as click? Commented Mar 23, 2018 at 4:04

3 Answers 3

4

This one works, something like "click" name maybe shouldn't be used as function name to be called in html

<!DOCTYPE html>
<html>
<head>
    <title>hello world</title>
</head>
<body>
    <button type="button" onclick="someClick()">
        click me
    </button>   
    <script>
        function someClick(){
            alert("hello world");
        }
    </script>
</body>
</html>

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

Comments

1

Using inline event handlers is bad practice and results in poorly factored, hard-to-manage code. Seriously consider attaching your events with JavaScript, instead, eg: https://developer.mozilla.org/en/DOM/element.addEventListener

Try attaching an event listener instead, like this:

document.querySelector('button').addEventListener('click', function() {
  alert("hello world");
});
<button type="button">
    click me
</button>   

Comments

0

its not work because the click word is reserve word of javascript tyr this

<!DOCTYPE html>
<html>
<head>
<title>hello world</title>
</head>
<body>
<button type="button" onclick="oneclick()">
    click me
</button>   
<script>
    function oneclick(){
        alert("hello world");
    }
</script>

Comments

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.