What is a Java script. How can Java be of interest to us, JavaScript developers? Adding an image change


Language Java programming Script is an object-oriented scripting language originally developed by Netscape Communications under the name LiveScript, but later renamed "JavaScript" and in terms of syntax closer to Sun Microsystems' Java. JavaScript was later standardized by ECMA under the name ECMAScript. Microsoft calls its versions JScript.

The change in name from LiveScript to JavaScript occurred around the same time that Netscape included support for Java technologies in the Netscape Navigator browser. This change has created a lot of confusion in the minds of those learning to program for beginners. There is no real connection between Java and JavaScript, their similarities begin and end with similar syntax and the fact that both languages ​​are widely used on the Internet.

JavaScript is an object-oriented scripting language that communicates through an interface called Document Object Model(DOM) with content, can be executed on the server side (web servers) and on the client side in the user's web browser when viewing web pages. Many websites use client-side JavaScript technologies to create powerful dynamic web applications in programming for dummies. It can use Unicode and can use power and strength regular expressions(this was introduced in version 1.2 of Netscape Navigator 4 and Internet Explorer 4). JavaScript expressions contained as a string can be executed using the EVAL function.

One of the main tasks for JavaScript is small functions embedded in HTML pages that allow you to interact with the DOM from the browser to perform certain tasks that are not possible in static HTML: such as opening a new window, validating values ​​entered into a form, changing the image on hover. mice, etc. Unfortunately, creating such functions is quite tedious because browsers are not standardized, different browsers may create different scripting objects or methods, and so you often have to write various options JavaScript functions for various browsers, but this is not very convenient when learning the basics of programming.

JavaScript / ECMAScript is supported by such engines as:

  • Rhino
  • SpiderMonkey

Environment

The markup comment is required to ensure that the code does not display as text in browsers that do not recognize the . tags in XHTM/XML documents, however, will not work if commented out. Modern browsers, which support XHTML and XML are well designed enough to recognize , so in these documents the code remains uncommented.

An HTML element can generate internal events to which a script handler can be connected. To create a valid HTML 4.01 document, you must insert the appropriate default script link statement in the document head section.

Elements of language

Variables

Variables are usually dynamically typed. Variables are defined either by simply assigning a value to them or by using the "var" operator. Variables declared outside a function are in "global" scope, visible throughout the web page; variables declared inside a function are local to that function. To pass variables from one page to another, the developer can set a "cookie" or use a hidden frame or window in background for their storage.

Data structures

The main type is a data structure in the form associative array similar to hashes in the language Perl programming or Python, Postscript and Smalltalk dictionaries.

Elements can be accessed by numbers or associated names (if these have been defined). Thus, the following expressions may all be equivalent:

MyArray,
myArray.north,
myArray["north"].

Declaring Arrays

MyArray = new Array(365);

Arrays are implemented so that only certain (non-empty) elements will use memory, they "discharge the arrays". If we set the set myArray = "something there" and myArray = "something else there", then we have used space only for these two elements.

Objects

JavaScript has several kinds of built-in objects, namely Object, Array, String, Number, Boolean, Function, Date and Math. Other objects belong to DOM objects (windows, forms, links, etc.).

By defining constructor functions, you can define objects. JavaScript is a prototype-based object-oriented language. You can add additional properties and methods to individual objects after they have been created. To do this, you can use a prototype statement for all instances of a particular type of object.

Example: Creating an Object
// Constructor function

Function MyObject(attributeA, attributeB) ( this.attributeA = attributeA this.attributeB = attributeB )
// Create an object
obj = new MyObject("red", 1000)

// Access an object attribute
alert(obj.attributeA)

// Access attribute with associative array designation
alert(obj["attributeA"])

The hierarchy of objects can be reproduced in JavaScript. For example:

Function Base() ( this.Override = _Override; this.BaseFunction = _BaseFunction; function _Override() ( alert("Base::Override()"); ) function _BaseFunction() ( alert("Base::BaseFunction()" ); ) ) function Derive() ( this.Override = _Override; function _Override() ( alert("Derive::Override()"); ) ) Derive.prototype = new Base(); d = new Derive(); d.Override(); d.BaseFunction();

As a result, we get on the screen: Derive::Override() Base::BaseFunction()

Control instructions
If ... else if (condition) ( statements )
Cycles
while (condition) ( statements ) Do ... while do ( statements ) while (condition); For loop for (; ; ) ( statements ) For loop ... in
This loop goes through all the properties of an object (or element in an array)
for (variable in object) ( statement )

Selection operator
switch (expression) ( case label1: statements; break; case label2: statements; break; default: statements; )

Functions
The body of the function is contained in (the body can be empty), and the list of arguments is indicated inside () following the function name. Functions can return a value after execution.

Function(arg1, arg2, arg3) ( statements; return expression; )

As an example, let's look at a function based on the Euclidean greatest common divisor algorithm:

Function gcd(a, b) ( while (a != b) ( if (a > b) ( a = a - b; ) else ( b = b - a; ) ) return a; )

The number of arguments when calling a given function does not necessarily have to provide as many arguments as were specified when the function was declared. In a function, arguments can also be accessed through an argument array.

Each function is an instance of a function, a base type of object. Functions can be created and assigned like any other objects:

Var myFunc1 = new Function("alert("Hello")"); var myFunc2 = myFunc1; myFunc2();

Result on screen:

User interaction

Most user interaction is done using HTML forms, which can be accessed through the HTML DOM. However, there are also some very simple means of communicating with the user:

Alert dialog box
Confirm dialog box
Dialog lines
Status bar
Consoles

Text elements can be the source of various events, which can trigger actions if an EMCAScript event handler is registered. In HTML, these event handler functions are often defined as anonymous functions directly in the HTML tags.


Java Script made easy. Part 1

The JavaScript scripting language, a scripting language developed by Netscape, has enormous capabilities for developing Internet applications that run on both the client and server sides. The language is very simple, and to work with it you just need to have the concept HTML basics. JavaScript has many interesting features, and one of them is the ability to process not only data, but also events. An event is defined as some action performed in the context of the browser - for example, a mouse click or a page load. In addition, JavaScript integrates perfectly with PHP and complements it with the implementation of those functions that are impossible or labor-intensive to implement in PHP.

First steps in programming in JavaScript

Code JavaScript script(hereinafter referred to as JS) is placed directly in the HTML code. JS has a tag tag. Everything between the and tags is interpreted as code in that language. One of the most important commands used in JS programming is document.write(), which is needed in order to write something in the current document. In order not to be unfounded, I will give simplest example:




document.write("JavaScript is easy!!!")


Type this text in Notepad and save it with HTML extension. The result of executing this code will be the text “JavaScript is easy!!!” displayed in the browser window. You will say: “Maybe it will, but maybe it won’t,” and you will be right. If your browser does not support JS output, you will see full code instead of text. You can avoid displaying the code in such browsers by using the comment tag from HTML -


Another very important part programming in the JS language are events and event handlers. Events are mainly triggered by certain user actions. Each action describes a different type of event. Let's say that when you press the mouse button, an event called "Click" occurs; when the mouse pointer crosses any hypertext link, the MouseOver event occurs. In order for the program to react to these events, we use special programs event processing. For example, a program that handles the mouse button event is called onClick and tells the computer what to do if it happens. this event. For clarity, let's create a simple example again. Let's create a form that will contain a button, when clicked, a drop-down window will appear.



test page




Clicking the Test Button brings up a window with the text “Test completed!” (Fig. 1). Let's look at each command in this code in detail.

Using the command, we create a form with a button. The onClick="alert("Test passed!")" attribute defines what happens when the mouse button is clicked. Thus, if a Click event occurs, the computer will issue a call to alert("Test completed!"). The alert() function creates pop-up windows. When calling it, you need to specify a certain string in parentheses, which will appear in the drop-down window. As you can see in the code, the alert() construct uses single quotes. This is explained by the fact that in most cases it is possible to use both types of quotation marks. Moreover, it does not matter in what order they are used: first double, and then single, or vice versa. In our example, double quotes are used first, and then single quotes, and if we used the construction of two double quotes-onClick="alert("Test passed!")", then the computer would not be able to understand the script, since it is unclear which part of the construct the onClick event handling function relates to and which it does not.

So, the window contains the text that was passed to the JS alert function. This limitation is applied for security reasons. A drop-down window can also be created using the prompt() method (see Fig. 2), but in this case the window will reproduce the text entered by the user, and therefore the script written by an “evil hacker” can take the form system message and ask you to enter a certain password. In our case, it is clear that the window was created by the browser, and not operating system, and you can’t just pick it up and delete it.

Very convenient means in JS are functions that in most cases are used as a way to chain multiple commands together. As clear example Let's say that you need to repeat some sequence many times text strings. Using the JS knowledge we already have, we could use the document.write command and get code like this:




");

");
document.write("Most interactive page
");
document.write("Java Script made easy
");
document.write("Most interactive page
");
document.write("Java Script made easy
");
// -->

The naked eye can see that the structure was built irrationally. Let's rebuild this code using the function:





All script commands that are inside the curly braces belong to the FreeFunc() function we created. Now both document.write() commands are linked and can be executed when the specified function is called. Next, we call FreeFunc() three times immediately after defining the function itself. This will cause the function to be executed three times, i.e. Both lines will be printed three times. The kicker is that the ability to pass variables when calling a function gives scripts real flexibility. Functions can also be used in conjunction with event handling procedures. For example, you can create a function calc() that will have two variables x and y, and the result of the mathematical operation will be stored in the result variable. The last command of the function will be alert(result). Next, the calc() function can be called when the button is clicked with the onClick="calc()" command, resulting in a pop-up window with the calculation result.

Working with Windows

Another opportunity JavaScript language- opening new windows in the browser. In addition, you have the opportunity to control the window creation process itself. For example, you can specify the window size, whether the new window should have a status bar, a toolbar, or a menu. The list of main parameters is given in Table 1.

Table 1. Basic parameters for creating a window in JS

Let's take a practical example of creating a new window in a browser:












As a result of executing this program, we will receive a button in the browser, when clicked, a new window with text is created (see Fig. 3).

The OpenWindow() function we created opens a new browser window. The first argument to the open() function, the empty string (""), means that in this case we do not want to specify a specific URL, and JS is obliged to create additional new document. In the script, we define the variable myWindow, with which we access the new window (it is impossible to use the window name (TestWindow) for this purpose in this case). The created window has dimensions of 300x100 pixels and has no status bar, toolbar, or menu. After opening the window, inside it we open the document object to display the text. This is done using the myWindow.document.open() command. Here we access the open() method of the document object. This command does not open a new window - it only prepares the document for upcoming printing. It is necessary to prefix document.open() with the myWindow prefix to be able to print in a new window. Further in the text of the script, using the document.write() call, the text of the new document and its parameters are formed. To do this, write regular tags into the document HTML language. In this case, you can use absolutely any tags of the hypertext language HTML markup. After finishing working with the document() command, you need to close it, for which we use the myWindow.document.close() command.

When opening a window we must use three arguments:
myWindow= open("page.htm", "TestWindow",
"width=300,height=100,status=no,toolbar=no,menubar=no");

IN in this example we specify a specific URL (page.html) and the second parameter is the window name. Knowing the name of the window, you can load a new page there using the entry

In this case, you need to specify the name of the corresponding window, and if such a window does not exist, then a new one will be created with this name. Make no mistake: the myWin variable is not the name of the window, but only with the help of this variable can you access it. The scope of this variable is limited only by the script in which it is defined. But the window name (TestWindow) is a unique identifier that can be used from any browser window. To close the window, use the close() function, and everything else is identical to working with the open() function.

Status bar

In JS, you can write to the browser status bar - all you need to do is write the desired text to windows.status. Let's look at how to use this function again with an example. Let's create a script that, when you click on a button, will display the specified text in the status bar, and when you click on the second button, erase it:













By running the program in the browser, we get a form with two buttons. When you press the On Statbar Text button, the message “The On button is pressed” appears in the status bar, and when you press the Off Statbar (Clear text) button, the status bar is cleared (see Fig. 4).

So, we have a form with two buttons, which both call the statbar() function. When the On Statbar Text key is pressed, the function is called
as follows: statbar("On button pressed"). The text in quotes is the text that we will see in the status bar. In turn, the statbar() function was declared as follows:

function statbar(txt) (
window.status = txt;)

We put (txt) in the function in parentheses. This means that the string we passed to this function is placed in the txt variable, and the txt string is written to the status bar using the command window.status = txt. Accordingly, removing text from the status bar is done by writing an empty string to window.status: (""). The uses of writing text to the status bar are limitless. You can put an explanation of the link there when you hover over it, create a ticker, or simply use it to display the date and time.

Timer

Using the timeout function, you can execute certain commands after a specified time has elapsed. I will demonstrate this in the following script:




setTimeout("alert("Welcome to the \"MyHome\" ")", 3000);
// -->

Wait 3 seconds. A window will appear

After 3 seconds of opening the page, a pop-up window will appear saying “Welcome to the MyHome page” (see Figure 5).

SetTimeout() is a method of the window object. It is designed to set a time interval. The first argument to the call is the JS code that should be executed after the specified time has elapsed (in our case, alert()). The second argument is used to indicate when this code should be executed. In this case, the time is indicated in milliseconds.

Frames

The browser window can be split into several separate frames. A frame in general terms is a rectangle-shaped field. Each frame displays the contents of its own document. Creating frames is still an HTML task, but we'll briefly cover the basics of the process in JS. Tags and are used to create frames. In the following example, we will create a script that divides the browser page into 5 frames and load a separate page into each of them:













The result of executing this script is shown in Fig. 6.

In the frame, we use the rows and cols properties and set the percentage of space occupied by frames in the browser window. The rows property means that the frames will be located on top of each other, and the cols - opposite each other. You can also set the frame size in pixels, for which it is enough not to put the % symbol after the number. In the tag we indicate a link to the page to be loaded, and with the name attribute we specify a unique name for the frame. It is possible to set the thickness of the border between frames. To do this, you need to use the border parameter in the tag and set it to some value (by default border=0). Let's look at how JavaScript "sees" the frames present in the browser window. To do this, let's turn to the window with frames we created above. JS organizes the frames presented on a web page in the form of a kind of hierarchical structure, at the top of which is the browser window. In our case, it is divided into five frames. Thus, the window as an object is the ancestor of this hierarchy, and frames are, accordingly, its descendants. We assigned unique names to these frames: frame1, frame2... frame5. Using these names, we can exchange information with the specified frames. Let's say you need to activate a certain link in the first frame, but the corresponding page should load not in the same frame, but in another one. An example of such a task would be the creation of menus or so-called navigation bars, where one frame always remains the same, but has several different links for navigation. Without delving into the study of hierarchies, let's create an example of site navigation using frames. We will create several links in one frame. When any of them is activated, the corresponding page will be placed not in the same frame, but in the adjacent one. First, let's create the frames themselves:







Next, let's create a simple HTML page "start.htm":


start page
This is the start page of our site

And the navigation bar menu:








Page 1

Page 2
Site Map

Here we see several download methods new page into the main frame. The first link uses the load() function for this purpose:
Page 1

In this line, instead of explicitly loading a new page, we invite the browser to execute a command in JavaScript - for this we use the javascript parameter instead of the usual href. Next, we pass “1.htm” as an argument to the load() function, and define the load() function itself as follows:

function load(url) (
parent.main.location.href= url;)

The url is written inside the brackets. In our example, this means that the string "1.htm" is entered into the url variable when the function is called. And this new variable can now be used when working inside load() functions.

The second link uses the target parameter. This is no longer JavaScript code, but one of the HTML language constructs. We simply indicate the name of the required frame and are not required to prefix the name of the specified frame with the word parent. If you need to get rid of frames using the load() function, you only need to write parent.location.href= url in it. The result of executing our script is shown in Fig. 7.

Which of the proposed loading options to use depends on your script and the tasks it must implement.
This concludes our first acquaintance with the JavaScript language. In the following materials, we will look at predefined objects and shapes, create a clock on the page, look at working with the Image object, and also touch a little on layers and the event model.

Pavel Kuchinsky, [email protected]

JavaScript is a special type of programming language that is based on browser object representations. It is necessary in order to provide the site with greater interactivity compared to conventional static HTML documents. For example, in the user interface there will be the ability to implement changing pictures, a creeping line from text content, and much more! That's why it's important to know how to enable JavaScript in Firefox and other browsers.

JavaScript differs in that the text of software developments is embedded in HTML documents and parsed by the browsers themselves. JavaScript is a language for programming scripts on web pages.

Types of differences between JavaScript and Java

Knowing the designation of the term JavaScript, many users indiscriminately confuse this type of term with another concept - Java. Although the languages ​​are similar due to their names, they have different types values. The main types of differences are in difficulty and in the number of advanced types of opportunities. Before you learn how to enable JavaScript browser, it is necessary to understand its characteristic features.

The implementation of "JavaScript" is more free compared to Java. For example, data type conversions occur in the simplest way. Also, the programmer will not need to compile the initial code of the software development in the JavaScript language, in other words, it is an interpreted type of language.

How does this happen in JavaScript and in Java? In JavaScript, the program processes one line after another, informing about errors is issued after each line read, if there are any. In Java, the compiler shows these types of information after reading the complete text of the software design.

Before you enable JavaScript, keep in mind that it is not intended to be a replacement for the Java programming language. It is best to use the first type of language as a complement to the second.

Why is JavaScript needed?

WITH JavaScript support It is possible to create dynamic types HTML documents. Static Views HTML pages gone into the past tense. "JavaScript" connects all the building blocks of applications into a single whole. In other words, it serves as a foundation builder, doing field checks HTML forms until they are transmitted to the server. Knowing how to enable JavaScript in Firefox and other browsers is essential for them to work correctly online.

Management software developments in this programming language go through local administrations communication data. Users have the opportunity to observe in various windows the types of warning messages that are displayed with JavaScript support.

What is a JavaScript error and how to run JavaScript

Let's start with the fact that JavaScript makes it possible to add various interactive services to any website, safely add voting (surveys) and similar content without the risk of unnecessary page reloading. In these cases, types of scripts significantly help save user traffic and allow you to copy graphics High Quality, create types of galleries with images and do many other useful functions. But then, in order to run types of scripts, you first need to activate them.

Next, you need to remember about the usual types of problems of network users. In recent times, there has been an increase in situations where a person, having visited his page on a social network, finds error messages at the top of the windows: “JavaScript error”, “JavaScript is not enabled”, “JavaScript must be enabled for the site to function correctly”. In such cases, users have problems uploading photos and videos on the social network.

How to enable JavaScript in Firefox

In fact, the method of running scripts is very simple, it only requires a few basic steps that even the most inexperienced users can do. Step-by-step instruction as follows:

  • First you need to launch your personal browser Mozilla Firefox;
  • after that, open the browser options, then click on the corresponding button in the form of three parallel lines next to the introduction line;
  • now a huge window with many tabs has opened in front of you; the one you need is called “Content”, click on it;
  • then it’s even simpler: find the line “Use JavaScript” and check the box next to it;
  • Click "OK" and restart your personal browser.

At this point, the instructions on how to enable JavaScript in Firefox can be considered complete.

Disabling JavaScript

Accordingly, if the need to use JavaScript is no longer necessary, you can disable it in the same way as written above this type functions. To do this, also go to “Settings” - “Content”, uncheck the box next to “Use JavaScript”. Ready!

In addition, if you have Mozilla browser Firefox updated to latest version, then it would be good to check whether the settings have been lost after updates, as sometimes this happens. It is also worth noting that almost all types of social networks use interactive types of forms, therefore, without the included types of scripts, it will not be possible to fully view pages.

I can be unavailable messages, alerts, discussions. Sometimes failures occur, and if in social networks Some types of sections suddenly became inaccessible, but at the same time there are types of scripts activated in the browser, try turning them off and then turning them on again. Perhaps this method will solve the problem. If not, then there is always the option of resetting the options to standard. How to enable JavaScript in Internet Explorer and other browsers? The same way.


Today, there is probably no website that is not written using javascript.

The use of this script has become so popular that it is now simply impossible to do without it. The only people more popular and famous than javascript today are probably Paris Hilton and McDonalds.

What exactly is he?

Javascript is a scripting language whose purpose is to create interactive web pages. It works as is, without requiring compilation, but simply connecting to the HTML page. It should not be confused with Java - even if the names of these two languages ​​are similar, this does not mean that they are functionally related. In fact, it is much closer, for example, to Ruby or Python, but has its own ECMAScript standard, and therefore is still separate from them.

What Javascript Can Do

Javascript can do a lot - for example, it can be used to easily change element styles, remove tags, or add new ones. In this case, you can set the function in such a way that the script reacts to certain events - either mouse or key clicks, or begins to act on its own after some time has passed after loading. And with AJAX you can get updated data without reopening the page.

Javascript is capable of setting and reading cookies, displaying messages, windows, validating data, and much, much more. Handyman.

Javascript has three main advantages, including, for example, accessibility (by learning the basics of JavaScript, you can easily understand most of them and always improve your skills); universal support (they are supported in almost any computer environment - any modern computer capable of this), as well as full browser integration, making javascript even more convenient and easy to use.

As an example, we can cite technologies like VBScript, XUL and ActiveX - they are not supported in every browser and only work in a certain environment.

And of course, we must not forget about the speed and efficiency of JavaScript, which makes many programming languages ​​pale in comparison.

It would not be amiss to note that even now this technology continues to develop, and at a rapid pace - just have time to keep up! And soon a new interpreter will be created along with javascript 2 technology.

Advantages

JavaScript has many advantages, otherwise it would not be used so actively. It earned the love of users for a reason. One of its main advantages is considered to be interactivity, which is why most sites are written in this language. This is achieved thanks to the AJAX tool, and with its help the data will update itself, without user interaction. This is very convenient, for example, on payment system websites. This will be very useful for not the most experienced users - real help from the script itself that you use. What could be better?

Now I’ll tell you a little about the structure of this language.
  • JavaScript has several features, including the following:
  • Identifiers are case sensitive;
  • Variable names can include the "$" symbol, underscores, numbers (but cannot begin with them), and letters;

JavaScript is a programming language that adds interactivity to your website (for example: games, response when clicking buttons or when entering data into forms, dynamic styles, animation). This article will help you get started with this exciting language and give you an idea of ​​what it can do.

What is JavaScript actually?

Note: The reason we put the element at the bottom HTML file, is that HTML elements are loaded by the browser in the order in which they appear in the file. So if JavaScript is loaded first and needs to interact with the HTML below it, it will fail because the JavaScript will be loaded before the HTML it needs to interact with. Therefore, place JavaScript at the bottom HTML pages considered the best strategy.

What happened?

So your text title has been changed to "Hello world!" With using JavaScript. We did this by calling querySelector(), grabbing a reference to our header and storing it in a variable called myHeading. This is very similar to what we did in CSS with selectors. If you want to do something with an element, you first need to select it.

After this, you set the value of the myHeading variable to the textContent property (which represents the header content) to "Hello world!".

Crash course on language basics

Let's take a look at some basic JavaScript language features to give you a better understanding of how it all works. Moreover, these features are common to all programming languages. If you can understand these basics, you'll be able to start programming like nothing ever happened!

Variables

Note: JavaScript is case sensitive - myVariable is different from myvariable. If you are having problems in your code, check the case!

After declaring a variable, you can assign a value to it:

MyVariable = "Bob";

You can do both of these operations on the same line if you want:

Var myVariable = "Bob";

You can get the value by simply calling the variable by name:

MyVariable;

After setting the value of a variable, you can change it later:

Var myVariable = "Bob"; myVariable = "Steve";

Note that variables have different data types:

Variable Explanation ExampleString Number Boolean Object
A sequence of text called a line. To indicate that this value is a string, you must enclose it in quotes. var myVariable = "Bob";
Numbers. Numbers do not have quotes around them. var myVariable = 10;
The value is True/False. The words true and false are special keywords in JS, and don't need quotes. var myVariable = true;
An array that allows you to store multiple values ​​in a single reference. var myVariable = ;
You can access each element of the array like this:
myVariable, myVariable, etc.
Basically, anything. Everything in JavaScript is an object, and can be stored in a variable. Keep this in mind while you are learning. var myVariable = document.querySelector("h1");
All this is from the above examples.

So why do we need variables? Well, variables were supposed to do something interesting in programming. If the values ​​couldn't change, then you couldn't do anything dynamic, like personalize welcome message or change the image displayed in the image gallery.

Comments

You can put comments in JavaScript code, just like you did in CSS:

/* Everything that is here is a comment. */

If your comment does not contain line breaks, it is often easier to use two forward slashes, like this:

// This is a comment

Operators

Note: Mixing data types can lead to some unexpected results when performing calculations, so be careful to reference your variables correctly to get the expected results. For example, enter "35" + "25" into your console. Why didn't you get the result you expected? Because the quotes turned the numbers into strings, so you ended up with string concatenation rather than number addition. If you enter 35 + 25 you will get the correct result.

Conditions

Conditions are code structures that allow you to test whether an expression is true or false, and then execute other code depending on the result. The most common form of condition is called if ... else . For example:

Var iceCream = "chocolate"; if (iceCream === "chocolate") ( alert("Yay, I love chocolate ice cream!"); ) else ( alert("Awwww, but chocolate is my favorite..."); )

The expression inside if (...) is a test that uses the identity operator (as described above) to compare the variable iceCream with the string chocolate and see if they are equal. If this comparison returns true, the first block of code will be executed. If not, this code will be skipped and the second block of code will be executed, after the else statement.

Functions Events

To create true interactivity on a website, you need events. Events are a framework that listens to what's happening in the browser and then allows you to run code in response to it. The most obvious is the click event, which is fired by the browser when we click on something with the mouse. To demonstrate this event, enter next command into your console, and then click on the current web page:

Document.querySelector("html").onclick = function() ( alert("Ouch! Stop poking me!"); )

There are many ways to attach an event to an element. Here we select the element and set its onclick property handler to an anonymous (i.e. unnamed) function that contains the code we want to run on the click event.

note that

Document.querySelector("html").onclick = function() ();

equivalent

Var myHTML = document.querySelector("html"); myHTML.onclick = function()();

It's just shorter.

Let's upgrade our website example

Now that we've covered some JavaScript basics, let's add some cool, lightweight functionality to our example site to give you some idea of ​​how it works.

Adding an image change

In this section, we will add another image to our site and add some simple JavaScript to switch between the two images when they are clicked.

  • First of all, find another image that you would like to display on your site. Make sure it is the same size as your first image or as close as possible to it.
  • Save the image to your images folder.
  • Rename this image to "firefox2.png" (without the quotes).
  • Go to your main.js file and enter the following JavaScript. (If your "hello world" JavaScript still exists, remove it.) var myImage = document.querySelector("img"); myImage.onclick = function() ( var mySrc = myImage.getAttribute("src"); if(mySrc === "images/firefox-icon.png") ( myImage.setAttribute("src","images/firefox2. png"); ) else ( myImage.setAttribute("src","images/firefox-icon.png"); ) )
  • Save all files and load index.html in your browser. Now when you click on the image it should change to something else!
  • So we save a reference to our element in the myImage variable. Next, we create a handler for this variable onclick events with an anonymous function. Now, every time this image element is clicked:

  • We get the value from the src attribute of the image.
  • We use a condition to check the value of src if the path to original image:
  • If so, we change the src value to the path to the 2nd image, causing the other image to load inside the .
  • If it's not (meaning it must have changed by now), we change the value of src , reverting back to the original image path as it was in the first place.
  • Adding a Personal Welcome Message

    Next, we'll add some other code to change the page title to a personalized welcome message when the user first lands on the site. This welcome message will be saved when the user leaves the site and returns later - we will save it using . We will also include the ability to change the user, and therefore the welcome message, any time this is needed.

  • In index.html , add next line before the element: Change user
  • In main.js , add the following code to the end of the file, exactly as written - it will grab references to new button and title, and save them into variables: var myButton = document.querySelector("button"); var myHeading = document.querySelector("h1");
  • Now add the following function to set the personalized greeting - it won't do anything, but we'll use it later: function setUserName() ( var myName = prompt("Please enter your name."); localStorage.setItem("name", myName ); myHeading.innerHTML = "Mozilla is cool, " + myName; ) This function contains a prompt() function that brings up a dialog box, a bit like alert() except prompt() asks the user to enter some data, and saves this data is in a variable after the user clicks OK. In this case, we ask the user to enter his name. Next, we call an API called localStorage, which allows us to store data in the browser and retrieve it later. We use the setItem() function from localStorage to create and store data in a property called "name", and set this value to the variable myName, which contains the name entered by the user. At the end we set the title's textContent to be a string and the username.
  • Then add an if ... else block - we could call this initialization code since it structures the application when it is first loaded: if(!localStorage.getItem("name")) ( setUserName(); ) else ( var storedName = localStorage .getItem("name"); myHeading.innerHTML = "Mozilla is cool, " + storedName; ) This block first uses the negation operator (logical NOT, represented as!) to check whether the data in the name item exists. If not, then the setUserName() function is run to create them. If the data exists (that is, the user installed it during previous visit), we retrieve the stored name using getItem() and set the title's textContent to be a string plus the username, just like we did inside setUserName() .
  • Finally, set an onclick event handler to the button. When the button is clicked, the setUserName() function is run. This allows the user to set a new name whenever they want by clicking a button: myButton.onclick = function() ( setUserName(); )
  • Now, when you first visit the site, it will ask you for a username and then provide you with a personalized message. You can change the name at any time by clicking the button. As additional bonus, since the name is stored inside localStorage, it persists after the site is closed, while maintaining a personalized message the next time you open the site!

    Conclusion





    

    2024 gtavrl.ru.