Saturday, February 19, 2011

Event Handler

By Magesh Kumar   Posted at  2:10 AM   Java Scripts No comments



Standalone JavaScript

First, let's look at what a standalone piece of JavaScript looks like.

<script type="text/javascript">
<!--
 alert('Hey, remember to tell your friends!');
-->
</script>
If we place the above JavaScript between the 'head' tags (or 'body' tags), it will run as soon as we load the page.
Now this is fine - as long as you want it to run as soon as the page loads!
But, what if you don't want it to run as soon as the page loads? What if you only want it to run when a user clicks on a button?
Easy! This is where you need to use an "event handler".

What's an Event Handler?

In JavaScript/HTML, an event handler allows you to attach your JavaScript to your HTML elements.
Event handlers allow your web page to detect when a given "event" has occurred, so that it can run some JavaScript code. An example of an "event" could be say, a click on an HTML element.
In your code, an event handler is simply a special attribute that you add to your HTML element. For example, to run some JavaScript when the user clicks on an element, you add the onClick attribute to the element.
The examples below demonstrate this for you.

Adding JavaScript to an HTML Element

Here's a basic example of adding JavaScript to an HTML element. In this case, when the user clicks on our button, a JavaScript alert box is displayed. This is done by adding an onClick attribute and placing the JavaScript alert box code into it.
When you use JavaScript like this, you don't need to use script tags (like we did above). Simply place your JavaScript within the event handler and it will work.
Code:
<input type="button" onClick="alert('Hey, remember to tell your friends !');" value="Click Me!" />

JavaScript "On Double Click"

You could just have easily used another event to trigger the same JavaScript. For example, you could run JavaScript only when the double clicks the HTML element. We can do this using the onDblClick event handler.
Code:
<input type="button" onDblClick="alert('Hey, remember to tell your friends ');" value="Double Click Me!" />


About the Author

Nulla sagittis convallis arcu. Sed sed nunc. Curabitur consequat. Quisque metus enim, venenatis fermentum, mollis in, porta et, nibh. Duis vulputate elit in elit. Mauris dictum libero id justo.
View all posts by: BT9

0 comments:

Back to top ↑
Connect with Us

What they says

© 2013 MaGeSH 2 help. WP Mythemeshop Converted by BloggerTheme9
Blogger templates. Proudly Powered by Blogger.