180 likes | 330 Views
Javascript. Events. Some Common Events. onClick () onSubmit () -> discussed in forms lecture onMouseOver () onMouseOut (). How do we use Events. We simply add these to an html element and specify a JavaScript handling function.
E N D
Javascript Events
Some Common Events • onClick() • onSubmit() -> discussed in forms lecture • onMouseOver() • onMouseOut()
How do we use Events • We simply add these to an html element and specify a JavaScript handling function. <input type=“button” name=“myButton” value=“clickMe” onClick=“displayWelcome()”> Calls the displayWelcome function defined in your javaScript
<html> <body> <script type="text/javascript"> function sayHello(name) { alert("hi " + name); } </script> <input type="button" name="clickMe" value="HI EVERYONE" onClick="sayHello('portia')"/> </body> </html>
onMouseOver This will call a JavaScript function when you hover over your element <imgsrc="blue_square.jpg" id="colorSquare" class="red" onmouseover="changeColor()"/>
Changes color of square when you Hover <html> <body> <script type="text/javascript"> function changeColor() { var square = document.getElementById("colorSquare"); square.src = "red_square.jpg"; } </script> <imgsrc="blue_square.jpg" id="colorSquare" class="red" onmouseover="changeColor()"/> </body> </html> Changes picture shown from a blue to a red square
onMouseOut • This will call a JavaScript function when you move away from hovering over your element • <imgsrc="blue_square.jpg" id="colorSquare" class="red" onmouseover="changeColor();“ onmouseout=“changColorBack();”/> You need semicolons when you specify more than one event. e.g. here we specified both onmouseover and onmouseout
Will change color to red on hover and back to blue when you leave <html> <body> <script type="text/javascript"> function changeColor() { var square = document.getElementById("colorSquare"); square.src = "red_square.jpg"; } function changeColorBack() { var square = document.getElementById("colorSquare"); square.src = “blue_square.jpg"; } </script> <imgsrc="blue_square.jpg" id="colorSquare" class="red" onmouseover="changeColor();“ onmouseout=“changeColorBack();”/> </body> </html>
Introduction to jQuery Events
Events • Events in javascript and jQuery are the triggers that you want to invoke an action: • E.g. mouse click, mouse hover…
Binding an Event • Binding an event to a function means that when the event is triggered the function that was bound to it will be executed. $(“img”).bind(event, data, handler)
Let’s bind a function Now everytime a click is executed functionName was exectued. $(function() { $(“#target”).bind(“click”, functionName); });
Binding Multiple Event Handlers • You can tie more than one event handler to the same event!
Shorthand • The shorthands for .bind(click,…) are: • For Click: .click(functionName) • For Hover: .hover(functionName) • For Key Up: .keyup(functionName)
Hover Events • With hover events you can specify both the entry and exit events. .hover(over, out)