Javascript 2

In the first javascript session you learnt how to write some javascript.

Your code ran when you loaded the page.

Usually you will want to control when it runs.

For example, you might want to have a button which runs your code when you click on it.

In this session you will learn how to do that.

Let's start by putting a button on the page:


    <button onclick='hello();'>
    Click Me
    </button>

Do you see the code which says onclick='hello();'? This is the instruction which calls your code when the button is clicked.

Of course, you still need to have the code you wrote before. You could edit the page you did in the first session. Or, I can show you how to copy your code to a new page.

There is one difference: you don't need the call to the hello function. This is because the button will call the hello function when you click on it. So you just need this part of the code:


<script>
  function hello(){
      alert("hello");
  }
</script>

The button which calls the code on this page is here:

Try it out yourself!

On your web page you will need to write:

  1. The button code
  2. <script>, then write your javascript and then write </script>
  3. The function hello(){....}

Your code will look a lot like mine. You can change the same things as before:

Please ask for help if you get stuck.

Good luck! 😄