Introduction with JQUERY – Handling Events

Guest Posts Paolo Nikko Nuñal

JQUERY is tailor made to response on many events on an HTML page. Such as click events, done with a mouse, form, keyboard and documents just to name a few.

What are Events?


When a visitor visits a page there are many actions that they can do. And these are called events. An event is define as a precise moment when something happens. One of the most common examples is clicking on a button.



Learn HTML5/PHP/AJAX Web Programming from Scratch – An amazing course from Dr. Richard Stibbard. Usually I only promote my own courses, but this course is very impressive, so I cut a deal with Dr. Stibbard … You can also find Richard’s website here



Most of the time you will hear terms like "fire" whichi s often associated with events. For example when a user clicks a button and it will "fire" the code to process.



















Mouse Events Keyboard Events
click keypress
mouseenter keyup
dblclick keydown

 

JQUERY Syntax for Handling Events


In JQUERY DOM elements have an equivalent JQUERY method that you can do. Base from the table above, if you want something to happen when a user clicks on a button, you need to use the appropriate function to that element.

Code:

$("#btn-show").click();


Afterwhich, the next step is to bind it to the event or what should happen when the event fires.

Code:

$("#btn-show").click(function(){
//PUT ACTION HERE
});


The comment "PUT ACTION HERE" defines on what action should do after the mouse is clicked. For example, you may want to hide a specific element or do some addition or mathematical equation.

Code:

$("#btn-show").click(function(){
var a;
var b;
var z;
z = a + b;
});


From the code above you can see that when the user clicks on the button with the id "#btn-show" will add two variables.

Here's another example using the "keyup" with the keyboard.

Code:

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
   $(document).ready(function(){
      $("#input-field").keyup(function(){
       alert("Hello");
    });
 });
</script>
</head>
<body>
<input type=text" id="input-field">
</body>
</html>


Based from the example above, we have bind the input field with the ID "#input-field" with the keyup function. Everytime a user inputs something on the input field it will automatically output a "Hello" message.



Learn HTML5/PHP/AJAX Web Programming from Scratch – An amazing course from Dr. Richard Stibbard. Usually I only promote my own courses, but this course is very impressive, so I cut a deal with Dr. Stibbard … You can also find Richard’s website here