Keywords:
Situation:
You want something on the page to change with the user clicks something.
Actions:
Code in an element's click event calls a JS function in your namespace
Explanation:
Add an onclick
event handler to an element. A button, a heading, an image, whatever you like.
In onclick
, call a function in your project's namespace.
For example, suppose you have an app with the namespace DogPack
.
<p>Click the image to give Rosie some love.</p>
<img src="rosie.jpg" alt="Rosie" onclick="DogPack.rosieClicked()">
In your code:
DogPack.rosieClicked = function(){
...
}
A common action is to change a variable, and show its new value. For example:
var rosieLove = 0;
DogPack.rosieClicked = function(){
//Update the variable counting Rosie clicks.
rosieLove++;
//Show the new value.
$("#rosieLove").html(rosieLove);
}
Here's the HTML again, with a place for the output:
<p>Click the image to give Rosie some love.</p>
<img src="rosie.jpg" alt="Rosie" onclick="DogPack.rosieClicked()">
<p>Rosie love: <span id="rosieLove">0</span></p>