JavaScript entry events, cookies, timing, etc.

Source: Internet
Author: User

An article on "getting started with JavaScript" covers many of the most basic content in JavaScript, from creating SCRIPT tags to using annotations, including JavaScript files in HTML documents, defining variables, using operators, defining arrays, using conditional statements, defining functions, and using loops. This article starts from the end of the previous article, explains some other basic JavaScript language concepts, and continues to provide beginners with a basic understanding of the language. The basic content mentioned in this article allows you to better understand the database you are using and decide whether to use the database or not, it may even give you the courage to write your own database. The document provides examples from beginning to end to illustrate how the language is implemented.

Event

An event is a catalyst that uses JavaScript to add any type of interaction to a webpage. Each HTML element has an event that can be used to trigger JavaScript code. For example, there are many possible events in the input field: You can associate the focus event to trigger JavaScript code when someone clicks or jumps to the input field, alternatively, you can associate a blur (defocus) event to trigger JavaScript code when someone clicks the outside of an input field that has received the focus or jumps out of the field. After an event is associated, there will be infinite possibilities. For example, the blur event triggers JavaScript code that checks whether the data in the input field is valid. If it is invalid, an inline message is displayed as an automatic feedback. The following code provides an example to illustrate 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 has a default value. Therefore, 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 Domain value to an empty string to make the default value disappear. If someone clicks or jumps to the external field of the input field, the blur event is used to display the default text again. If you do not do this, the text they entered is left behind.

Each HTML element has its own related events. Table 1 lists some of the most common HTML elements and related events.

Table 1. common elements and related events

Element event

Body onload, onunload

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

Form onsubmit

Img onmouseover, onmouseout, onclick

Try... catch and throw

Try... catch statements provide a way to detect code errors, so that you do not need to send errors to the browser or give a custom error. If a JavaScript error is not included in a try... if the catch statement is internal, no subsequent JavaScript code can be executed, and the browser has to handle and display the error in its own way. The try part of this statement is used to execute JavaScript code, while the catch part is used to handle errors that may occur in the try part. You can use this statement to construct code that can work normally in Some browsers. If the code is placed inside the try... catch statement, it is ignored and not executed when an error is returned. The catch part will handle the error. This error may indeed give an error message or do nothing, depending on whether the user needs to know the error.

Use try... catch to handle errors

The catch part of the statement can also contain a default error object parameter, which returns information related to the error in the try part of the statement. The error object has two attributes: message and line. The text provided by message describes the exact error, and line provides the exact number of lines of code for the error. Listing 1 provides an example of a try... catch statement. In this example, an error object is used to notify the error message and the number of rows. Of course, this kind of information is useful only in the debugging status, but it is intended to provide users with feedback about an error without relying on browser processing, these attributes become very useful.

Listing 1. Using Error objects in try... catch statements to adjust errors
Copy codeThe Code is as follows:
Try
{
// Try to execute the code that produces the error here
}
Catch (err)
{
Var txt = err. message + '\ n ';
Txt + = err. line;
Alert (txt );
}

An error occurs when the throw statement is used to create an error.

Try... catch constructs provide excellent error handling functions, but you can also take a further approach, that is, using throw statements. Throw statements allow you to create error exceptions based on certain conditions. This method provides the best opportunity to create more user-friendly error information, these error messages are accurate and described in easy-to-understand languages. Listing 2 provides a simple example to illustrate how to use the throw statement to create a condition-based error exception in the try part of the try... catch statement.

Listing 2. Using throw statements to create error exceptions
Copy codeThe Code is 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>

Note that try, catch, and throw are both in lowercase: Using uppercase produces a JavaScript error.

Create dialog box

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

Warning box

Warning boxes are not often used for their initial purpose. They are a way to quickly and conveniently display page errors, warnings, or other important messages. Currently, warning boxes are most commonly used to debug JavaScript code. To be fair, they still have their own location-but this best practice is not intended for the purpose at the beginning. In addition, if you use Mozilla Firefox, Apple Safari, or Google Chrome, you can use only console. log for debugging. So the bottom line is that when all other practices fail, the warning box is a feasible alternative to complete the task. It is very easy to create a warning box: as long as the alert function is input as a line of code and a parameter is passed to it, it will open a window using any value you pass to it. For example, you can enter a simple string or use a warning box to display the value of the variable passed to it as a parameter, this is an example of how the warning box is used for debugging. The following is a basic example to illustrate how to use the alert function to generate a warning box.

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

The confirmation box is used to verify your selection on the website. For example, if you are a web application developer and a user chooses to delete his or her user account, therefore, it is a good consideration to confirm the selection before allowing the user to continue to submit the request.

Usually, the confirm function is written inside a Condition Statement. First, check whether the user intends to continue the selection. Then, based on this decision, determine whether to execute JavaScript code. The following example uses the confirm function in the condition to determine the JavaScript code to be executed:
Copy codeThe Code is as follows:
If (confirm ("Click for a response "))
{
Alert ('You clicked OK ');
}
Else
{
Alert ('You clicked cancel ');
}

Prompt box

When you are looking for a quick way to ask a question and allow users to provide an answer, don't look for anything else. The prompt box is the most suitable. Generally, all web developers choose the custom inline pop-up window. Despite this, the prompt box still exists, and they still have their own place, especially during debugging. The prompt function is used to generate a prompt box with two parameters. The first parameter is a custom text string, which is usually a problem or a prompt with a response statement; the second parameter is a text string used as the default input text displayed in the prompt box. This default value is optional and can be changed at runtime. The following is a column of the prompt function. This function is used to ask a question to the user. Then, the user's response is displayed in a warning box, and the value returned from the prompt function is used.
Copy codeThe Code is as follows:
Var response = prompt ("What is your favorite band? "," Led Zeppelin ");
If (response! = Null & response! = "")
{
Alert ("response:" + response );
}


Use cookie

Cookie exists to store data on the client, so that your JavaScript code can retrieve and reuse the data later. If used properly, storing data on a user's computer has many benefits. You can use cookies to customize user experience and determine how to present information to users based on previous behaviors. Examples of cookie usage include storing the visitor's name or other relevant information, which can then be displayed on the website. A cookie is a text file stored in a visitor's web browser. It contains a pair of name-value, an expiration date, and the domain and path of the server to which it should be sent.

Create cookie

Creating a cookie is simple: you only need to determine the information you want to store, the storage duration, and name the cookie for future reference. However, although it is easy to create, the syntax is somewhat difficult. You need to provide the correct syntax to make it work normally. The following code demonstrates how to create a cookie and store 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, cookiename = cookievalue. A semicolon (;) separates this value pair from the second part. The second part of the string is the expiration date in the correct format, followed by a semicolon to separate it from the third part, that is, the last part, which is the path.

Retrieve data from cookies

It is difficult to store data in cookies. However, it is easy to retrieve the cookie value by name in the future. The following describes how to retrieve cookie values by name.

Alert (document. cookie );
This code retrieves cookies from the current domain. However, the domain may store multiple cookies, document. cookie is an array. Therefore, to retrieve a specific cookie, you need to find the target correctly. You are lucky: the custom function in listing 3 makes this process very easy. You just need to pass the cookie name as a parameter and then you will be able to receive the cookie value.

Listing 3. retrieving data from stored cookies
Copy codeThe Code is 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 have seen, cookies provide powerful functions to create custom experiences for visitors, or store data for future use.

Timing

JavaScript provides several functions for you to control and set the execution time of certain behaviors. The most common of these functions 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. The setInterval function can easily achieve this. SetInterval has two required and one optional parameter. The first required parameter is the code you want to re-execute, and the second parameter is milliseconds ), it defines the interval between each execution of JavaScript code. The third optional parameter is an actual parameter that can be passed to the function call, which is specified by the code parameter. At first, you may think the set interval is a bit strange because it is defined as millisecond. Therefore, if you want to run every second, it will take 1000 milliseconds, two seconds will be 2000 milliseconds, and so on. Table 2 lists each parameter and Its Role in the setInterval function.

Table 2. Available parameters of the setInterval Function

Required or optional descriptions

The JavaScript code that the setInterval function must execute;

This code can be customized or called by a function.

The interval between every two times of code execution required by milliseconds, in milliseconds.

Argument is an optional parameter. When a function is used as a code parameter,

It can be used to pass the actual parameter 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. In this way, the value of argument can be accessed within the execution function. This parameter can be a variable, object, or a simple text string, as shown in this example:
Copy codeThe Code is as follows:
SetInterval (myFunction, 10000, 'sample ');
Function myFunction (myArg)
{
Alert ('myfunction argument value: '+ myArg );
}

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

ClearInterval Function

The clearInterval function is required to terminate the interval, but a variable must be included in the initial creation of the interval behavior so that later clearInterval can reference it. The following code provides an example to illustrate how the clearInterval function references the variable previously set for the initial setInterval:
Copy codeThe Code is as follows:
Var myInterval = setInterval (myFunction, 10000, 'sample ');
Function myFunction (myArg)
{
Alert ('myfunction argument value: '+ myArg );
ClearInterval (myInterval );
}

As you can see, the initial setInterval function is assigned a variable name named myInterval. After that, you can use myInterval to reference setInterval, change this variable, or use the clearInterval function to stop the initial interval execution function. In this example, this function is called only once, because the clearInterval function is executed when the function is called for the first time.

SetTimeout Function

In terms of code execution based on a certain time constraint, the setTimeout function is similar to the setInterval function, and even its parameters are the same as those of setInterval (see table 2 ). However, the biggest difference is that the setTimeout function only executes the code once rather than repeatedly. The example shows how to use the setTimeout Function to execute a function in 10 seconds.
Copy codeThe Code is 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 do not want to execute it immediately. It is essentially a method to delay code execution.

ClearTimeout Function

If, for some reason, you have changed your mind and need to cancel the delay behavior set by setTimeout, The clearInterval function can be used to handle this job. Like the clearInterval function, you need to assign a variable name to the setTimeout function so that clearTimeout can reference it and stop the behavior it sets. The following code provides an example to illustrate how to use clearTimeout to stop the call set by setTimeout:
Copy codeThe Code is 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 initial setTimeout function, which is named myTimeout. Then you can use myTimeout to reference the setTimeout Function and use the clearInterval function to stop it.

Conclusion

The JavaScript language can be said to be one of the most popular languages. Now you understand why. This simple and rich scripting language brings about so many possibilities. It provides a powerful tool that allows website visitors to interact with the Downloaded web page. This article laid the foundation for understanding the basic principles of the JavaScript language: the next thing to do is to put these concepts into practice and start exploring JavaScript objects.

Related Article

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.