Run code on click

See more about:

Events

Click on the button:

Here’s what happens:

   When the user clicks on an element:
       Do something

“The user clicks on an element” is an event. It’s something that happens. The browser waits for events, then responds to them.

id

Here’s one way to set it up:

<script type="text/javascript">
  $(document).ready(function() {
    $("#ELEMENT_ID").click(function() {
      CODE
    });
  });
</script>
...
<something id="ELEMENT_ID">

Figure 1. Using an id

Line 4 is the code to run when the user clicks ELEMENT_ID. Line 3 attaches that code to the element:

   $("#ELEMENT_ID").click(function() {...

This tells the browser:

   When the element with an id of ELEMENT_ID is clicked, then run this code.

ELEMENT_ID is the id attribute of an element, set in line 9.

Here’s line 3 again:

   $("#ELEMENT_ID").click(function() {...

The browser has to execute this line sometime, to set up the click event. But when should the browser run line 3? Hmmm. It should run line 3 when the page is first loaded.

Here’s line 2:

   $(document).ready(function() {

The ready event happens when the page is loaded. So this line sets up the click event.

Here’s the code for the button you clicked earlier:

<p style="margin-left: 50px;">
  <button id="thing1">Click me</button>
</p>

<script type="text/javascript">
$(document).ready(function () {
  $("#thing1").click(function(){
    alert("Hey! Stop clicking me!");
  })
});
</script>

Figure 2. Code for the button

Lines 7 and 8 say:

When the user clicks on the element with the id of thing1, then do this:
       alert("Hey! Stop clicking me!");

class

The code above used an id. Only one thing on a page can have a particular id. For example, there can be only one thing1.

But what if you want to run the same code when more than one object is clicked? Click on each one of these images:

Renata Renata

Here’s the code:

<p style="margin-left: 50px;">
  <img class="cute_thing" src="renata_puppy.jpg" alt="Renata">
  <img class="cute_thing" src="renata_puppy2.jpg" alt="Renata">
</p>
...
<script type="text/javascript">
$(document).ready(function () {
  $(".cute_thing").click(function(){
    alert("Renata as a tiny puppy.");
  })

});
</script>

Figure 3. Code for the cute

Line 8 sets up the click event:

   $(".cute_thing").click(function(){

Instead of #cute_thing, this one is .cute_thing. # means “look for an id.” . says “look for a class.” Only one element on the page can have a particular id. But many elements can have the same class.

Here are lines 2 and 3:

   <img class="cute_thing" src="renata_puppy.jpg" alt="Renata">
   <img class="cute_thing" src="renata_puppy2.jpg" alt="Renata">

They both have the same class. So the same code is run when the user clicks on either of them.


Lessons

How to...


Dogs