"Turn" what is JavaScript

Source: Internet
Author: User
Tags event listener

Transfer from MDN Learning site-what is JavaScript

What is JavaScript?

Welcome to MDN JavaScript Beginner's course! In the first article, we will stand at a certain height to look at JavaScript and answer something like "What is it?" "and" What can it do? "The problem. And make sure you're familiar with the use of JavaScript.

A high level of definition

JavaScript is a programming language that allows you to do complex things in a Web page--Each time you browse the Web, not just the static information--Display the instant updates, or the interactive map, or the 2d/3d graphic animation, or the auto-play video, you can be sure that JavaScript Participate in them. This is the three-tier cake standard for Web technology:

    • HTML is a markup language that is used to structure our web content and to give content meaning, such as defining paragraphs, headings, and datasheets, or embedding images and videos in a page.
    • CSS is a style rule language, and we apply styles to our HTML content, such as setting the background color and font, and laying out our content in multiple columns.
    • JavaScript is a programming language that allows you to create dynamically updated content, control multimedia, image animation, and a few other things. Well, not everything, but the magic of it is that you can do it with a few lines of JavaScript code.

These three levels are established in a disciplined manner on top of each other. Let's use a simple text tag as an example. We can tag it with HTML to give it structure and purpose:

<p>Player 1: Chris</p>

Then we can add a little bit of CSS to make it look better:

P{  font-family: ' Helvetica Neue ', Helvetica,Sans-serif;  letter-spacing: 1px;  Text-transform: Uppercase;  text-align: Center;  border: 2px Solid Rgba (0,0, $,0.6);  background: Rgba (0,0, $,0.3);  Color: Rgba (0,0, $,0.6);  Box-shadow: 1px 1px 2px Rgba (0,0, $,0.4);  Border-radius: 10px;  padding: 3px 10px;  Display: Inline-block;  cursor:Pointer;}

And finally, we can add some JavaScript to achieve dynamic behavior:

var=document.querySelector(‘p‘);para.addEventListener(‘click‘, updateName);functionupdateName{  var=prompt(‘Enter a new name‘);  para.textContent=‘Player 1: ‘+ name;}

Try clicking on the Text tab to see what happens (also note that you can find this demo on GitHub-source code, or run it in real time)!

JavaScript can do more than that-let's explore in detail what it can do.

So what does it actually _ can do?

The core of the JavaScript language contains some common programming features so that you can do the following things:

    • Store a useful value in a variable. As an example of the above demo, we ask for a new name and then store that name in a variable called name .
    • Operates on a piece of text (called a "string" in programming). In the example above, we take the string "Player 1:" and then link it to the name variable to create a complete text label, for example: ' Player 1:chris '.
    • Run code in response to specific events that occur in the Web page. In the example above, we used an click event to detect when the button was clicked and then run the code to update the text tag.
    • and more!

More exciting, however, is the ability to build on the core of the JavaScript language. In your JavaScript code, the functionality known as the application programming Interface [application Programming Interfaces (APIs)] provides extra power for you to use.

APIs are an established set of code components that enable developers to implement programs that are difficult or impossible to implement. They act as if the furniture set that has been made has the same effect on home construction--starting from a pile of already cut planks to assemble a bookcase, obviously more than the design itself, looking for the right wood, cutting to the right size and shape, finding the right size of the screw, and then assembling it into a bookcase is much simpler.

They (APIs) are usually divided into two categories.

Browser APIs (Browser APIs) are already installed in your Web browser and can expose data from the surrounding computer environment, or do useful and complex things. As an example:

    • The Document Object Model API [DOM] API allows you to manipulate HTML and CSS, create, remove, and modify HTML, dynamically apply new styles to your pages, and so on. For example, every time you see a pop-up window on a page, or show something new (as we saw in the simple demo above), DOM is working.

    • Geo-Location API [Geolocation API] gets geographic information. That's why Google Maps [Google Maps] can find your location and be labeled on the map.

    • Canvas [canvas] and WebGL APIs allow you to create vivid 2D and 3D images. People are using these web technologies to do something amazing-Chrome experiments and webglsamples, for example.

    • Video and video APIs [audio and video APIs], like HTMLMediaElement and WebRTC allow you to use multimedia to do something very interesting, such as playing audio and video on a Web page, or getting a video from your web cam, Then show it on someone else's computer (try our simple snapshot demo [Snapshot Demo] to understand the concept).

Note: Many of the above demos cannot be run in an old browser-when experimenting, running in a modern browser, like Firefox, Chrome, Edge or Opera, is a good idea. As you approach the delivery of the product code, you will need to take a more in-depth look at cross-platform testing [browser testing] (example: actual code used by real customers).

third-party APIs (third) are not installed in the browser by default, and you usually need to get their code and information from somewhere on the network. As an example:

    • Tweet API [Twitter API] allows you to do things like show your latest push on your website.

    • Google Maps API [Google Maps API] allows you to embed custom maps into your site, and other features.

Note: These APIs are advanced and we do not involve any of these APIs in the course, but if you want to learn more, the above links provide extended documentation for your reference.

There are more things available! However, don't feel too excited about it so soon. You won't be able to build your next Facebook, Google Maps or instagram--with just 24 hours of JavaScript, and there's a lot of basics that need to be covered first. And that's why you're here--let's move on!

What does JavaScript do on your page?

Here we'll start to actually look at some of the code, and in doing so, explore what actually happens when you run JavaScript on your page.

Let's briefly review what happens when you read a webpage in a browser (the first time in the article How CSS works). When you read a Web page in a browser, you run your code (HTML, CSS, and JavaScript) in an implementation environment (browser tab). It's like a factory, get the raw Material (code) and then produce a product (Web page).

After HTML and CSS have been set up and assembled into a Web page, the browser's JavaScript engine executes JavaScript. This ensures that when JavaScript begins to run, the structure and style of the Web page are already in place.

This is a good thing, as JavaScript's general usefulness is to update the user interface by dynamically modifying HTML and CSS through the DOM API, as mentioned earlier. If JavaScript loads and runs before the HTML and CSS loads are complete, an error occurs.

Browser security

Each browser tag itself is a separate container for running code (these containers are called "running environments" in terms of jargon)-which means that in most cases the code in each tag runs completely detached, and the code in one tag does not directly affect the code in another tag-- or in another site. This is a good security measure-if not, pirates can start writing code that steals information from other websites, and other bad things like that.

Note: There's a safe way to transfer code and data across websites/tags, but these are advanced techniques that we won't cover in this course.

JavaScript Run Order

When a browser encounters a piece of JavaScript code, it usually runs this code block sequentially, from the top down. This means that you need to be aware of the order in which you place the code. For example, let's go back to the JavaScript code block we saw in the first example:

var  para =  document . queryselector  ( ' P ' )  para . addeventlistener  ( ' click '   updatename)  function  updatename  () { var  name =  prompt   ( ' Enter a new name ' )  para . textcontent  =   ' Player 1: '  +  name }   

Here we are selecting a text paragraph (line 1) and then attaching an event listener (line 3) so that when the paragraph is clicked, the updateName() code block (lines 5–8) is run. updateName()code blocks (such reusable blocks of code called "functions") request a new name from the user and then insert the name into the paragraph to update the display.

If you swap the order of the first two lines in the code, it will not work-instead, you will get an error in the browser's developer console--typeerror:para is undefined [type error: Para not defined]. This means that the Para object does not yet exist, so we cannot add an event listener to it.

Note: This is a common mistake-you need to be aware that it already exists before attempting to manipulate the object referenced in your code.

Interpreting code vs compiled Code

In the programming environment, you may have heard of these two terms explaining [interpreted] and compiling [compiled]. JavaScript is an interpreted language-code runs from top to bottom, and the results of the run are returned immediately. You don't have to convert it to another form before the browser runs the code.

On the other hand, a compiled language needs to be converted to another form before it is run. For example, C + + will be compiled into assembly language, and then run by the computer.

Both approaches have different advantages, but for the time being, we're not going to talk about that.

Server-side code vs. client code

You may also have heard of the terms server-side [Server-side] and client [client-side] code, especially in the context of web development. Client code is code that runs on a user's computer-when a Web page is browsed, the client code of the page is downloaded and then run and displayed by the browser. In this JavaScript module, we will explicitly explore client- side JavaScript [client-side JavaScript].

On the other hand, server-side code runs on the server, and its results are downloaded and displayed by the browser. The popular server-side Web page language contains the following examples: PHP, Python, Ruby, ASP, and javascript! JavaScript can also be used as a server-side language, for example in a popular node. JS Environment-You can find more information on our Dynamic Web page-server-side programming [Websites–server-side Programming] Topic The knowledge of the server-side JavaScript.

The term dynamic [dynamics] is used to describe client-side JavaScript and server language-it refers to the ability to update the content of a Web page/application to display different things in different contexts, and to generate new content when needed. Server-side code dynamically generates new content on the server, such as extracting information from the database. Instead, client-side JavaScript dynamically generates new content in the user's browser, such as creating a new HTML table from which to insert data from the server, and then displaying the table in a Web page that has been shown to the user. In both contexts, the meaning of the dynamic is slightly different, but connected, and both methods (server side and client) are usually working together.

A webpage that does not dynamically update content is referred to as static [static] -it will only show the same content all the time.

How do I add JavaScript to your page?

JavaScript is applied to your HTML page in a way that is similar to CSS. Although CSS uses <link> elements to apply an external style sheet [stylesheet] and <style> elements to apply an internal stylesheet to the Html,javascript only one element in the HTML world-the element-is needed <script> . Let's learn how it works.

In-house JavaScript
    1. First, copy our sample file apply-javascript.html to local. stored in a directory that can be detected.
<!DOCTYPE html> lang="en-US">      <meta charset="utf-8">    <title>Apply JavaScript example</title>    <body>    <button>Click me</button>  </body>
  1. Open this file in your browser and text editor. You'll see this HTML creates a simple Web page that contains a clickable button.

  2. 然后,在你的文本编辑器里,在你的结束 </body>The tag is followed by the following code:

    <script>  // JavaScript goes here</script>
  3. Now we'll <script> add some JavaScript to our element to make the page do something more interesting--add the following code to the "//JavaScript goes Here" line:

    function Createparagraph(){  varPara= Document.createelement(' P ');  para.textcontent = ' You clicked the button! ';  Document.Body.appendchild(para);}varButtons= Document.Queryselectorall(' button ') for(varI= 0;I< Buttons.length ;I++){Buttons[i].AddEventListener(' click ',Createparagraph);}
  4. Save your files and refresh your browser--now when you click on the button, you should see a new paragraph generated and displayed below.

Note: If your example doesn't seem to work, check all the steps and make sure you're doing the right thing. Have you saved the original code as a .html local copy of the file? Did you just add the element to the </body> label <script> ? Have you entered the JavaScript exactly as shown?

JavaScript is case-sensitive and very fastidious, so you need to enter the syntax exactly as shown, otherwise it might not work.

Note: You can see this version of apply-javascript-internal.html on GitHub (seeing it live too).

External JavaScript

That's a good idea, but what if we want to put our JavaScript in an external file? Now let's explore this.

    1. First, create a new file in the same directory as your simple HTML file. Named script.js --Ensure that it has a. js file extension, because this is how it is considered to be JavaScript.

    2. Then, extract all of the <script> script [scripts] in your current element and paste them into the. js file. Save the file.

    3. Now replace your element with the <script> following:

      <script src="script.js"></script>
    4. Save and then refresh your browser, and then you should see the same thing! It works the same, but now we have JavaScript written in an external file. This is usually a good thing for planning your code, and allows it to be reused in multiple HTML files. In addition to the fact that there are not a lot of scripts in HTML, HTML is easier to read.

Note: You can see this version of as apply-javascript-external.html and script.js on GitHub (seeing it live too).

Inline JavaScript Processors

Note that sometimes you will encounter a hint of real JavaScript code in HTML. It may look like this:

functioncreateParagraph{  var=document.createElement(‘p‘);  para.textContent=‘You clicked the button!‘;  document.body.appendChild(para);}
<button onclick="createParagraph()">Click me!</button>

This demo has the exact same functionality as the previous two sections, except that the <button> element contains an inline onclick processor so that the function runs when the button is pressed.

However, please do not do so. This is a bad practice of using JavaScript to contaminate your HTML, and it's not efficient-you'll need to include attributes on every button you want JavaScript to apply to onclick="createParagraph()" .

Using a pure JAVASCRIPT structure allows you to use a single command to select all the buttons. The code we're doing on top of this looks like this:

< buttons.length ; i++) {  buttons[i].addEventListener(‘click‘, createParagraph);}

This may seem a onclick bit longer than the property, but it will apply to all buttons, no matter how many are on the page, and how many buttons are added or removed. There is no need to make any modifications to JavaScript.

Note: Try to edit your own apply-javascript.html version and add more buttons to the file. When you reload, you should find that all buttons are pressed to create a paragraph. It's simple, isn't it?


As with HTML and CSS, it is possible to write comments that are ignored by the browser in your JavaScript code, and comments are only used to give your developer colleagues guidance on how the code works (including you, if you return to your code after 6 months and forget what you've done). Annotations are useful, and you should use them frequently, especially in larger applications. Here are two types of annotations:

    • A single-line comment is written after a double-slash (//), such as:

      // I am a comment
    • A multiline comment is written between the string/* and/*, for example:

      /*  I am also  a comment*/

So for example, we can use "annotations" to comment on our previous demo's JavaScript:

//Function:creates a new paragraph and append it to the bottom of the HTML body.function Createparagraph(){  varPara= Document.createelement(' P ');  para.textcontent = ' You clicked the button! ';  Document.Body.appendchild(para);}/*1\. Get references to all the buttons on the page and soter them in an array.2\. Loop through all the buttons and add a click event listener to each one.When a button is pressed, the createparagraph () function would be run.*/varButtons= Document.Queryselectorall(' button '); for(varI= 0;I< Buttons.length ;I++){Buttons[i].AddEventListener(' click ',Createparagraph);}

So here you are, your first step in the JavaScript world. We just start with the theory, get you acquainted with why you use JavaScript, and what you can do with it. In the process you see some code examples and learn how JavaScript fits with other code in your site.

JavaScript may seem a bit daunting now, but don't worry-we will lead you gradually in this course. In the next article, we will devote ourselves to practice, allowing you to focus on and build your own JavaScript example.


"Go" what is JavaScript

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.