JavaScript is a programming language commonly used in websites to perform functions that the HTML cannot do. It can be used for validating forms, detecting browsers, adding dynamic functionality, and more! It is beyond the scope of this guide to teach you JavaScript, but below you can learn how to embed or integrate JavaScripts into your website using the <script> tag. Embedding Scripts; External Files Probably the most common way, and often preferred way, is to define the scripts in a separate file and link to them using the src attribute of the script tag. The type must be set totext\javascript, and optionally the language attribute set to JavaScript1.2 or the version of JavaScript required for you script. <script type="text/javascript" src="scriptName.js"></script> Between SCRIPT Tags Instead of specifying a src attribute, you can write javascript between the <script> and </script>tags. The type and language attributes are still used the same as when specifying external scripts. <script type="text/javascript"> var myVar="hello"; function showAlert() { alert('You triggered an alert!'); } </script> Inline in the HTML Normally the HTML event attributes are used to call functions specified elsewhere in script tags. In rare cases you may wish to add the javascript code directly to these onClick or onMouseOver event tags, but this is not consdered good design. <p><a href="#" onClick="alert('Hello');">Click Me</a></p> EventsSome html elements have event attributes, that can be used to call javascript functions when an event is triggered. There are many events available, but these are the ones you are most likely to use: OnClick As the name suggests, the onClick attribute is executed when an element, such as a link or image, is clicked on. OnMouseOver Use the OnMouseOver attribute to call javascript functions that you want to run when a user moves the mouse onto and hovers over an element. OnMouseOut Another mouse event handler, except OnMouseOut is the opposite to OnMouseOver, and will be called when the users' mouse is moved back off an element. Example:The following example has two JavaScript functions defined in the header, which are activated by clicking on the links. Note that each link shows a different way of calling the function, you would only need to pick the one that suits you. <html> <head> <script type="text/javascript"> function functionOne() { alert('You clicked the top text'); } function functionTwo() { alert('You clicked the bottom text'); } </script> </head> <body> <p><a href="#" onClick="functionOne();">Top Text</a></p> <p><a href="javascript:functionTwo();">Bottom Text</a></p> </body> </html>
0 Comments
Leave a Reply. |