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>
Michael Brown
  • 141
  • 1
  • 3
  • 7
  • It conflicts with default click function of element, but you do nothing for the click function. – Sky Mar 23 '18 at 04:01
  • Possible duplicate of [javascript function name cannot set as click?](https://stackoverflow.com/questions/4388443/javascript-function-name-cannot-set-as-click) – inhaq Mar 23 '18 at 04:04

3 Answers3

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>
Hans Yulian
  • 1,080
  • 8
  • 26
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>   
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
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>

dev_ramiz_1707
  • 671
  • 4
  • 20