Basics of JavaScript entry events, cookies, timing, etc.

Source: Internet
Author: User
Tags setinterval
An article on "Getting Started with JavaScript language" covers many of the most basic things in the JavaScript language, from creating script tags to using annotations, including JavaScript files in HTML documents, defining variables, using operators, defining arrays, using conditional statements, Define functions and use loops, and so on. Beginning with the end of the previous article, this article explains some of the other basic JavaScript language concepts and continues to provide beginners with a basic understanding of the language. The basics of this article will give you a better understanding of the library you are using, knowing how to make a decision about whether to use the library, or even giving you the courage to write your own library. Throughout the article, examples have been provided to illustrate how language achieves its various aspects.

Events

Event is a catalyst that uses the JavaScript language to add any type of interaction to a Web page, and each HTML element has related events that you can use to trigger JavaScript code. For example, the input domain has many possible events: You can associate focus events, trigger JavaScript code when someone clicks or jumps to the input field, or you can associate a blur event, Triggers JavaScript code when someone clicks outside of an input field that has already been focused or jumps out of the field. After associating an event, there is an infinite possibility. For example, the Blur event triggers a JavaScript code that checks whether the data in the input field is valid, and if it is not, an inline message is displayed as an automatic feedback. The following code provides an example of how the focus and blur events are used to display the default text in the input field.

<input type= "text" name= "email" value= "Enter Your email address"
onfocus= "this.value =" "onblur=" if (this.value = = ")
This.value = ' Enter your email address '; />
The input field here has a default value, so when you view the field in a Web browser, the input field displays the text "Enter your email address." When someone clicks or jumps to the domain, the focus event is used to set the value of the field to an empty string in order for the default to disappear. If someone clicks or jumps to the outside of the input field, the Blur event is used to display the default text again, and if you don't, it leaves the text that they entered.

Each HTML element has events related to itself. Table 1 lists some of the most common HTML elements and their associated events.

table 1. Common Elements and related events

Element events

Body onload, OnUnload

Input onfocus, onblur, onchange, onkeydown, onkeypress, onkeyup

Form onsubmit

IMG onmouseover, onmouseout, onclick

Try...catch and throw

The Try...catch statement provides a way to detect code errors so that you do not have to send an error to the browser or give a custom error. If a JavaScript error is not contained within a Try...catch statement, any subsequent JavaScript code cannot be executed, and the browser has to use its own way to handle and display the error. The try part of this statement is used to execute JavaScript code, and the catch part handles errors that may occur in the try section. You can use this statement to construct code that may not work correctly in some browsers. If this code is placed inside the Try...catch statement, it is ignored and not executed when there is an error, and the catch part handles the error. This error may indeed give an error message, or do nothing, depending on whether the user needs to know the error occurred.

Using Try...catch to handle errors

The catch part of the statement can also contain a default error object parameter that returns information related to an error that appears in the try part of the statement. The Error object has two properties: Message and line. The text provided by the message describes the exact error that occurred; line provides the exact number of lines of code that occurred. Listing 1 shows an example of a try...catch statement that uses an Error object to notify the error message and the number of rows. Of course, this information is only useful in the debug state, but these properties become useful when you are not relying on browser processing and want to provide feedback about an error that has occurred.

Listing 1. Using Error objects in Try...catch statements to tune errors
Copy Code code as follows:

Try
{
Trying to execute the code that generated the error here
}
catch (Err)
{
var txt = err.message + ' \ n ';
TXT + + err.line;
alert (TXT);
}

Use the throw statement to create an error exception

The Try...catch construct provides a great error-handling feature, but you can take a step further by using the throw statement. The throw statement allows you to create error exceptions based on certain conditions that provide the best opportunity to create more user-friendly error messages that are accurate and are described in plain language. Listing 2 shows a simple example of how to use the throw statement to create a conditional error exception in the try part of a try...catch statement.

Listing 2. Use the throw statement to create an error exception
Copy Code code as follows:

<script type= "Text/javascript" >
var x=prompt ("What type of music is Led Zeppelin?", "");
Try
{
if (x!= ' Rock and Roll ')
{
Throw "ERR1";
}
}
catch (er)
{
if (er== "ERR1")
{
Alert ("Sorry, you ' re wrong.");
}
}
</script>

One thing to note is that try, catch, and throw are all lowercase: Using uppercase causes a JavaScript error.

Create a pop-up box

JavaScript allows you to create several types of pop-up boxes, some of the most common types--and the display boxes to be discussed here--are warning boxes, confirmation boxes, and cue boxes.

Warning Box

Warning boxes are not often used for their original purpose, they are a quick and easy way to display page faults, warnings, or other important messages. Currently, warning boxes are most commonly used as a way to debug JavaScript code, so it's fair to say that they still have their place-only this best practice is not intended for the original purpose. And if you use Mozilla Firefox, Apple Safari, or Google Chrome, you can use Console.log to achieve debugging purposes. So the bottom line is that when all else fails, the warning box is a viable alternative to accomplishing the task. It's easy to create a warning box: Just enter the alert function as a line of code and pass it a parameter that opens a window using whatever value you pass to it. For example, you can enter a simple string, or you can use a warning box to display the value of the variable passed to it as a parameter, which is a good example of how the warning box is used for debugging. The following is a very basic example of how to use the alert function to produce a warning box.

Alert ("This can is a variable or a simple text string");
Confirmation box

The confirmation box is used to verify the user's selections on the site. For example, if you are a Web application developer and a user chooses to delete his or her user account, it is a good consideration to confirm this option before allowing the user to continue submitting the request.

Typically, the Confirm function is written inside a conditional statement, first confirming whether the user intends to proceed with the selection, and then based on that decision to determine whether to execute the JavaScript code. The following example uses the Confirm function in a condition to determine which JavaScript code to execute:
Copy Code code as follows:

if (Confirm ("Click for a Response")
{
Alert (' You clicked OK ');
}
Else
{
Alert (' You clicked Cancel ');
}

Prompt box

When looking for a quick way to ask a question and allow the user to provide an answer, don't look for anything else, the cue box is the most appropriate. Typically, today's Web developers choose to customize inline pop-up windows. Although this is the case, the cue boxes still exist, and they still have their own place, especially when debugging. The prompt function is used to produce a prompt box, it has two parameters, the first parameter is a custom text string, which is usually an issue or a statement that prompts for some kind of response; The second argument is a text string that is used as the default input text to display in the prompt box. This default value is optional and you can change it at run time. Here is an prompt function that is used to present a problem to the user, and then displays the user's response in a warning box showing the value returned from the prompt function.
Copy Code code as follows:

var response=prompt ("What is your favorite band", "Led Zeppelin");
if (response!=null && response!= "")
{
Alert ("Response:" + response);
}


Using Cookies

Cookies exist to store data on the client, so your JavaScript code can retrieve and reuse the data later. If used properly, there are many benefits to storing data on a user's computer. You can use cookies to customize the user experience, to determine how to present information to them based on previous behavior, and so on. Examples of cookies used include the name of a stored visitor or other relevant information that can later be displayed on the site. A cookie is a text file stored in a visitor's Web browser that contains a pair of names-values, an expiration date, and the domain and path of the server to which they should be sent.

Creating cookies

Creating cookies is simple: you just need to determine the information you want to keep, the length of time you store, and name the cookie for future references. However, although it is very simple to create, but the syntax is somewhat difficult to complete, you need to give the correct syntax, it can function properly. The following code shows an example of how to create a cookie and store the data in it.

Document.cookie =
' Cookiename=cookievalue; Expires=sat, 3 Nov 2001 12:30:10 UTC; path=/'
The first part of the string stored in the cookie is a pair of name-value, that is, the cookiename=cookievalue part, a semicolon (;) separates this value pair from the second. The second part of the string is the expiration date written in the correct format, followed by a semicolon to separate it from the third part, the last part, which is the path.

retrieving data from a cookie

The syntax required to store data in a cookie is troublesome, but it is easy to retrieve the cookie's value by name later in the day. The following is an approach to retrieving cookie values by name.

alert (Document.cookie);
This code obtains a cookie from the current domain, but there may be more than one cookie,document.cookie in the domain, so to retrieve a particular cookie, you need to find the target correctly. You're lucky: The Custom Function in Listing 3 makes this process easy, as long as you pass the cookie name as an argument, and then you get the value of the cookie.

Listing 3. Retrieving data from stored cookies
Copy Code code as follows:

function GetCookie (c_name)
{
var i,x,y;
var Cookiearray = Document.cookie.split (";");
for (i=0;i
{
x = Cookiearray[i].substr (0,cookiearray[i].indexof ("="));
y = Cookiearray[i].substr (cookiearray[i].indexof ("=") +1);
x = X.replace (/^\s+|\s+$/g, "");
if (x = = C_name)
{
return unescape (y);
}
}
}
Alert (GetCookie (' cookiename '));

As you can see, cookies provide powerful capabilities to create custom experiences for visitors, or just store data for later use.

timed

JavaScript provides several functions that allow you to control and set the execution time of certain behaviors, the most common of which are:

1. SetInterval

2. Clearinterval

3. settimeout

4. Cleartimeout

setinterval function

In some cases, JavaScript code needs to be executed repeatedly without any user interaction, and the SetInterval function makes it easy for you to do this. SetInterval has two required and an optional parameter, the first required parameter is the code that you want to execute repeatedly, and the second parameter is millisecond (milliseconds), which defines the length of time the JavaScript code executes at each interval. The third optional parameter is an actual argument that can be passed to a function call, which is specified by the code parameter. At first you may find it odd to set the interval length, as it is defined as milliseconds. So, if you want to run every second of each interval, it's 1000 milliseconds, two seconds is 2000 milliseconds, and so on. Table 2 lists each parameter and its role in the SetInterval function.

Table 2. Available parameters for the SetInterval function

parameter Required or optional description

Code required the SetInterval function to execute the JavaScript codes;

This code can be customized or a function call.

Milliseconds the length of time, in milliseconds, between the required execution of code for every two times.

Argument Optional is a very useful parameter, when the function is used as the code parameter,

can be used to pass the actual argument to the function.

The following code provides an example of how to use the SetInterval function to execute another function every 10 seconds and pass a parameter to the function. This argument value can be accessed within the execution function, which can be a variable, object, or a simple string of text, as shown in this example:
Copy Code code as follows:

SetInterval (MyFunction, 10000, ' sample ');
function MyFunction (MYARG)
{
Alert (' myfunction argument value: ' + myarg);
}

If you want to terminate such an interval execution, the language also provides a function for this.

clearinterval function

The Clearinterval function is required to terminate the interval behavior, but you must include a variable when the interval behavior is initially created so that clearinterval can reference it later. The following code provides an example of how the Clearinterval function references a variable that was previously set for the original setinterval:
Copy Code code as follows:

var myinterval = setinterval (MyFunction, 10000, ' sample ');
function MyFunction (MYARG)
{
Alert (' myfunction argument value: ' + myarg);
Clearinterval (Myinterval);
}

As you can see, the original SetInterval function was assigned a variable name named Myinterval. After that you can use Myinterval to refer to setinterval, change this variable, or use the Clearinterval function to stop the initial interval execution function. In this example, this function is only invoked once, because the Clearinterval function executes the first time that it is invoked.

settimeout function

The SetTimeout function is similar to the SetInterval function, and even its parameters are the same as setinterval (see table 2), when it is possible to execute code based on a time constraint. However, the biggest difference is that the settimeout function executes only once, rather than repeatedly, the code. The example here illustrates how to use the SetTimeout function to perform a function after 10 seconds.
Copy Code code as follows:

SetTimeout (MyFunction, 10000, ' sample ');
function MyFunction (MYARG)
{
Alert (' myfunction argument value: ' + myarg);
}

SetTimeout is useful when you want to execute some code, but you don't want to execute it immediately, which is essentially a way of delaying code execution.

cleartimeout function

If, for some reason, you change your mind and you need to cancel the deferred behavior of the settimeout setting, the Clearinterval function can be used to handle this work. As with the Clearinterval function, you assign a variable name to the SetTimeout function so that later cleartimeout can reference it and stop the behavior it sets. The following code provides an example that shows how to use Cleartimeout to stop a settimeout set call:
Copy Code code as follows:

var mytimeout = settimeout (MyFunction, 10000, ' sample ');
function MyFunction (MYARG)
{
Alert (' myfunction argument value: ' + myarg);
Cleartimeout (mytimeout);
}

In this example, you assign a variable name to the original settimeout function, which is named Mytimeout. You can then use Mytimeout to refer to the SetTimeout function and use the Clearinterval function to stop it.

Conclusions

The JavaScript language is one of the most popular languages, and now you see why. This simple and rich scripting language offers so many possibilities that it provides the tools to allow site visitors to interact with downloaded Web pages, a powerful feature. This article lays the groundwork for understanding the fundamentals of JavaScript language: The next thing to do is to put these concepts into practice and start exploring JavaScript objects.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.