Making A Button Do Stuff in JavaScript For Beginners
# Another super step-by-step guide
I remember being confused as hell the first few times I tried this back when I was still learning JavaScript. This articles goes out to new JavaScript learners, and hopefully it makes your journey less painful.
What we want to build
A page with a button that increases a number by 1 when clicked.
And when we click the button once, the number increases.
1) Let’s first write the HTML elements
Our first step would be to ensure that all the HTML elements exist — 1) the Hello
2) the button & 3) the number.
Let’s open your VSCode and create a file named index.html
<h1>Hello</h1>
<button>click me</button>
<h1>1</h1>
2) Open your index.html in your browser
Your browser will process and reflect whatever is written in index.html
. But every time you make a change, you need to refresh your browser.
Note — at this stage, nothing happens when we click on the button. This is normal, and we’ll deal with this later on.
3) Let’s add the JavaScript tag
To make our button do stuff, we need JavaScript. So we first need to add a JavaScript tag — the <script>
and </script>
<h1>Hello</h1>
<button>click me</button>
<h1>1</h1>
<script>
</script>
Whatever that goes between <script>
and </script>
is JavaScript code.
4) Causing an alert to happen (JavaScript)
<h1>Hello</h1>
<button>click me</button>
<h1>1</h1>
<script>
alert('hello world')
</script>
alert()
is a JavaScript function that makes a box containing text appear.
Here, alert('hello world')
makes a box containing the text hello world
appear at the top of our screen. Make sure to refresh your browser for the new change to take effect. You should see
Note that the alert happens whenever we refresh the page.