Catch mouse events in DIV using javascript

Posted by Andi Syahputra | 3:51 PM
Suddenly I thought to share you this simple trick. I know its very basic but i'm sure many people out there still don't know about this. So, here we go.... :D

Div (also called layer), made by using <div> tag and </div> close tag. So, any elements between it would be united as one single element. The position of div also can be set using CSS stylesheet that I'll explain to you next time. Now, we are about to catch mouse event by using javascript right?

Here's the trick. For example we made a div like this

<div>
<h1>This is the test</h1>
</div>

To catch the event, you just simply add mouse event listener to opening div tag. So far I know, javascript had many kinds of mouse events such as: onclick, onmouseover, onmouseout, onmousedown, onmouseup, onmousemove, and oncontextmenu.
The final look of the div will be like this:

<div onclick='function()'>
<h1>This is the test</h1>
</div>

where onclick you can replace it with other mouse event and function() can be replace with your javascript function declared in the head section of your webpage.

Full example in your webpage:

<html>
<head>
<script>
function test(){
alert("function test triggered");
}
</script>
</head>
<body>
<div onclick='function()'>
<h1>This is the test</h1>
</div>
</body>
</html>

Hope this help.. :D
hi folks, visit my other tutorial blog at Kumpulan tutorial menarik
0 comments