JavaScript foundation of front end

Posted by abs0lut on Wed, 26 Jan 2022 05:09:27 +0100

JavaScript

JavaScript is a programming language that provides dynamic interaction features for websites.

Bring js file into the page

1. Create a new folder scripts
2. Create a new file main JS file

let myHeading = document.querySelector('h1');
myHeading.textContent='Hello World!';

3. Page import js file
The position is between the label head and the label body, or at the bottom of the body.
Different positions lead to different loading sequences of pages and js, which may lead to different page rendering effects.

    <script src="./scripts/main.js"></script>

querySelector syntax format

Document example.querySelector('Selector string');//The Document instance call is to get the matching elements of the whole page.
Element example.querySelector('Selector string');//The Element instance call is to get the matching elements in the Element subtree.

In short, one is to find in the whole page and the other is to find in the specified range.

window.onload

window.onload() is usually used for elements to execute script code after the page is fully loaded (including images, css files, and so on).

window.οnlοad=function(){
    Func1();
    Func2();
    Func3();
    .....
}

Supplement:
document.ready indicates that the document structure has been loaded (excluding non text media files such as pictures); Native js itself does not provide document Ready method

$(document).ready(function(){.... })This function is used to replace the window.onload;

variable

JavaScript is case sensitive.
1. Declare variables
Keyword let or var, and then enter the appropriate name:

let aVariable;
var AVariable;
const PI = 3.14;

let current scope is valid
var globally valid
const declares a constant. The current scope is valid
let const is a block level scope

2. Variable assignment

let aVariable;
aVariable='abc';

or

let aVariable='abc';

Except constants, other variables can be changed after assignment

data type

JS notes

// Single-Line Comments 

/* 
   multiline comment 
   multiline comment 
   multiline comment 
*/

operator


Expressions and operators

Conditional statement

Commonly used if... else

let iceCream = 'chocolate';
if (iceCream === 'chocolate') {
  alert('I like chocolate ice cream best.');
} else {
  alert('But chocolate is my favorite');
}

Function

Function is used to encapsulate reusable functions.
1. Multiplication example

function multiply(num1, num2) {
  let result = num1 * num2;
  return result;
}

Anonymous function

function () {};
//or
() => {};

Named function

function foo() {};
// or using the ECMAScript 2015 arrow notation
const foo = () => {};

Internal function

Calculate the sum of the areas of two squares

function addSquares(a,b) {
   function square(x) {
      return x * x;
   }//Internal function
   return square(a) + square(b);
};
//Using ECMAScript 2015 arrow notation
const addSquares = (a,b) => {
   const square = x => x*x;
   return square(a) + square(b);
};

Recursive function

function loop(x) {
   if (x >= 10)
      return;
   loop(x + 1);
};
//Using ECMAScript 2015 arrow notation
const loop = x => {
   if (x >= 10)
      return;
   loop(x + 1);
};

Immediate call function expression (IIFE)

A function that executes immediately when defined

(function () {
    statements
})();

Design pattern of self executing anonymous function
An anonymous function in the first (), which has an independent lexical scope. This not only avoids external access to variables in this IIFE, but also does not pollute the global scope.
The second () creates an immediate function expression, and the JavaScript engine will execute the function directly.
example

var result = (function () {
    var name = "Barry";
    return name;
})();
// Results returned after IIFE execution:
result; // "Barry"

event

Events can add real interaction ability to web pages.
Capture browser actions and respond.

Click event:

document.querySelector('html').onclick = function() {
	alert('Don't poke me. I'm afraid of pain.');
};

//Equivalent to

let myHTML = document.querySelector('html');
myHTML.onclick = function() {alert('Don't poke me. I'm afraid of pain.');};

prompt

var sign = prompt("What's your constellation??");
if (sign == "scorpio"){
   alert("wow! I'm also a Scorpio!");
}
// There are many ways to use the prompt method
var sign = window.prompt(); // Open an empty prompt window
var sign = prompt();       // Open an empty prompt window
var sign = window.prompt('Do you feel lucky?'); // Open and display the prompt text as "do you feel lucky?" Prompt window for
var sign = window.prompt('Do you feel lucky?','yes'); // Open and display the prompt text as "do you feel lucky?" And the default value of the input box is "yes"

prompt, alert and similar dialog boxes are modal windows that prevent users from activating the interface of other parts of the program until the dialog box closes.

Continue to improve the basic web page

  1. Switch logo image
  2. Switch users

My code
js:

/**
 * Get dom
 */
let myHeading = document.querySelector('h1');
let myBtn = document.querySelector('button');
let myImg = document.querySelector('img');

/**
 * Read user name
 */
function setUserName(){
    let myName = prompt('Please enter your name.');
    localStorage.setItem('name',myName);
    myHeading.textContent='Mozilla awesome,'+myName;
}

/**
 * User initialization code
 */

if(!localStorage.getItem('name')) {
    setUserName();
} else {
    let storedName = localStorage.getItem('name');
    myHeading.textContent = 'Mozilla awesome,' + storedName;
}

/**
 * Switch Firefox logo image
 */
function changeImage(){
    let mySrc = myImg.getAttribute('src');
    if(mySrc === './images/firefox.png') {
        myImg.setAttribute('src', './images/firefox1.png');
    } else {
        myImg.setAttribute('src', './images/firefox.png');
    }
}

/**
 * Set button click event
 */
myBtn.onclick = function() {
    setUserName();
}


myImg.onclick = function(){
    changeImage();
}

html

<!DOCTYPE html>
<html lang="zh-cmn-Hans">
   <head>
       <meta charset="UTF-8">
       <meta http-equiv="X-UA-Compatible" content="IE=edge">
       <meta name="viewport" content="width=device-width, initial-scale=1.0">
       <title>JavaScript Basics</title>
       <link rel="stylesheet" href="./styles/index.css">
   </head>
   <body>
       <article>
           <h1>Mozilla awesome!</h1>

           <img src="./images/firefox.png" alt="Firefox logo: a red fox circling the earth">

           <p>Mozilla It is a global community, where people from all over the world gather
               <ul>
                   <li>artisan</li>
                   <li>a thinker</li>
                   <li>builder</li>
               </ul>
           </p>

           <p>We are committed to making Internet Maintain vitality and smoothness. Everyone can contribute and create. We firmly believe that open platform collaboration is crucial to human development and determines our common future.</p>
           <p>In order to achieve our common ideals, we follow a series of values and ideas. Please refer to
               <a href="https://www.mozilla. org/zh-CN/about/manifesto/" target="_ Blank "> Mozilla Manifesto</a>
           </p>
           <button>Switch users</button>
       </article>

       <!-- And CSS of <link> Element similar -->
       <script src="./scripts/main.js"></script>

   </body>
</html>


Official code

Topics: Javascript Front-end html