JS Life Starting from Zero (2) - Events in BOM, DOM and JS

Posted by ben14 on Tue, 09 Jul 2019 02:27:14 +0200

As mentioned in the last book, variables, operators, branching structures, loops and nested loops are included in JS. This time, Ben K will talk to you about BOM, DOM and events in JS.

I. "Huaxin Big Radish" - BOM

1. Shocked, Why did FFF Group Lift a Torch on BOM--Brief Introduction to BOM

BOM(Browser Object Model) refers to the browser object model. In JS, BOM is a thorough turnip, because it has many objects. Among them, the Windows object representing the browser Window is the "front room" of BOM, that is, the most important one. It is not too bad that other objects are the hands of the front room or the side room. .

2. The Wind Flow of Final BOM-BOM Object Details

2.1 BOM's front room - window object.

Windows object represents the browser window, which is the most commonly used object in JS BOM. Here we introduce the common methods of understanding windows object.

prompt: Bullet window accepts user input;
(2) alert: bullet window warning;
(3) confirm: prompt box with confirmation/cancellation button;
close: close the browser window;
open: open a new window and pass in the parameter URL/window name/window feature.
setTimeout: Set Delay Execution only once (two parameters: function / milliseconds to be executed);
SetInterval: Set the timer, and the loop is executed every N milliseconds (pass-in parameter: return an ID when calling setInterval, accept ID through variable, pass in clearInterval);
Clear Timeout: Clear Delay;
Clear Interval: Clear timer;

Among the nine methods, the four most commonly used and the most troublesome are setTimeout/clearTimeout and setInterval/clearInterval, which correspond to each other and are often used together. Here's a chestnut for everyone.~

(Chestnut: setTimeout/clearTimeout)

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>First of all, setTimeout and clearTimeout</title>
        <!--Remember to open the console first.~-->        
        <script type="text/javascript">
           var timeoutid = setTimeout(function(){
                console.log("setTimeout");
            },5000) ;
            function clearTimeoutBtn(){
                clearTimeout(timeoutid);
            }
        </script>
    </head>
    <body>
        <button onclick="clearTimeoutBtn()">clearTimeout</button>
    </body>
</html>

(Chestnut: setInterval/clearInterval)

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>And then it's setInterval and clearInterval</title>
        <!--Remember to open the console first.~-->
        <script type="text/javascript">
            var num = 10;
            var timeinterval = setInterval(function(){
                num--;
                console.log(num);
                if (num==0){
                clearInterval(timeinterval);
                }
            },1000)
            function clearIntervalBtn(){
                clearInterval(timeinterval);
            }
        </script>
    </head>
    <body>
        <button onclick="clearIntervalBtn()">clearIntervar</button>
    </body>
</html>

2.2 BOM Side Chambers - Brief Description of Other Objects.

Because other BOM objects except window s objects rarely appear in actual JS writing, so this K will give you a brief mention in the form of code.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>BOM Side chambers</title>
        <!--Remember to open the console first.~-->
        
        <script type="text/javascript">
            
            // screen object
            
            console.log(screen);
            console.log(screen.width);//width
            console.log(screen.height);//height
            console.log(screen.availHeight);//Available Height=Screen Height-Bottom taskbar
            console.log(screen.availWidth);//Available Width
            
            // location object
            //   Complete url Route: 
            //   Agreement:// Host name (IP address): port number (default port 80)/file path? Passed parameters (parameter name 0 = parameter value 0 & parameter name 1 = parameter value 1) #anchor
            
            console.log(location);
            console.log(location.href);//Complete Path
            console.log(location.protocol);//Path Protocol http: https: ftp: file: mailto: 
            console.log(location.pathname);//Path section  /start
            console.log(location.port);//Port number
            console.log(location.search);//from?Begin the next part
            console.log(location.hostname);//IP address
            console.log(location.host);//host name+Port number
            console.log(location.hash);//from#The starting anchor
            // Use JS Setting Page Jump
            //    window.location="http://www.baidu.com";
            
            function locationReload(){
                //Reload the current page
                location.reload(true);//reload(true)Represents reloading the current page from the server; reload()Refresh the current page locally
            }
            
            function locationAssign(){
                location.assign("http://www.baidu.com");    //Load a new document, which can be rolled back after replacement
            }
            
            function locationReplace(){
                location.replace("http://www.baidu.com");//Replace the current document with a new document and cannot be rolled back after replacement
            }
            
            // history
            // length : Number of History Lists Browsed
            // history.forward(); :  Go to the previous page
            // history.back(); :  Back to the back page
            // history.go(); : Jump to anywhere in history browsing history; the current page is 0, the previous page is 1, and the latter page is 1.-1 individual
            
            console.log(history.length);
            
            function historyForword(){
                history.forward();
            }
            function historyBack(){
                history.back();
            }
            function historyGo(){
                history.go();
                // 0 
                // 1 = history.forward();
                // -1 = history.back();
            }
            
            // Navigator
            console.log(navigator.appName);//Product Name
            console.log(navigator.appVersion);//Product Version Number
            console.log(navigator.userAgent);//User Agent Information
            console.log(navigator.platform);//System Agent Platform
            
            console.log(navigator.plugins);//Check plug-in information for browser installation
            // Returns an array to detect all plug-ins installed by the browser(↓Main attributes↓)
            // description :  Plug-in Description Information
            // filename :  File name of plug-in on local disk
            // length :  Number of plug-ins
            // name :  file name
        
            console.log(navigator.mimeTypes);//File types supported by browser plug-ins(↓Main attributes↓)
            // description: MIME Type description
            // enabledPlugin: Support for this type of browser plug-in
            // suffixes: Possible suffix names for this type
            // type: MIME Writing of types, for example: image/x-icon text/css
        </script>
        
    </head>
    <body>
        
        <button onclick="locationAssign()">Loading new documents</button>
        <br />
        
        <button onclick="locationReload()">Reload the current document</button>
        <br />
        
        <button onclick="locationReplace()">Replace the current document with a new document</button>
        <br />
        
        <button onclick="historyForword()">This is historyForword</button>
        <br />
        
        <button onclick="historyBack()">This is historyBack</button>
        <br />
        
        <button onclick="historyGo()">This is historyGo</button>
        
    </body>
</html>

2. "N Generations Together" - DOM

1. The people in Chaoyang have made great contributions, and there is such a mysterious "huge organization" in the code - Introduction to DOM

DOM (Document Object Model) refers to the Document Object Model, which is the standard programming interface recommended by W3C organization for processing extensible markup language. On a web page, the object of an organizational page (or document) is organized in a tree structure to represent the standard model of the object in the document. Each branch of the DOM is called a "node". The structure diagram of all nodes and their attributes presents a strong hierarchy (chestnut is shown below, originating from Wan Zi). Du Niang of Energy.

DOM nodes are divided into three categories: element nodes, text nodes and attribute nodes. Text node and attribute node are two sub-nodes of element node. Element node can be obtained by gelElement series method.

2. The truth of such an organization is that the DOM operation is detailed.

DOM operation is a very useful part of JS, so this K is described in the form of code.

2.1 Get Nodes and Style Modifications

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>DOM Code details (1)</title>
        
        <script type="text/javascript">            

            
            window.onload = function(){
                var div1 = document.getElementById("div1");//adopt ID Get a unique node; multiple identical names ID Only take the first one.
                console.log(div1);
                
                console.log(div1.tagName);//View nodes:①Attribute; Gets the label name of the node
                console.log(div1.innerHTML);//②Set or retrieve all within the node HTML Code
                console.log(div1.innerText);//③Set or retrieve all text within the node
                
                console.log(window.getComputedStyle(div1,null));//View all properties (non IE Attributes)
                console.log(div1.currentStyle);//View all properties( IE Attributes)
                
            }
            function getById(){
                //Style attribute nodes fetched to element nodes
                var div1 = document.getElementById("div1").style;//Obtain
                div1.backgroundColor = "#FF00FF";//Row-level style sheet weight 1000;All node attributes, uniform hump naming
                
                //Get the element node
                var divDoc = document.getElementById("div1");//Obtain
                divDoc.innerHTML = "<s>king_land</s>";//Reset modification div Medium HTML Code
            }
            
            //-------Partition line——————————————————
            
            function getByName(){//adopt Name Get an array containing one or more nodes;
                
                var div = document.getElementsByName("div1");
                
                console.log(div.length);
                
                //How to use it: Every node is fetched through a loop, and the number of cycles starts at 0.<array.length
                for(var n = 0 ;n < div.length ; n++){
                    div[n].style.backgroundColor = "#FFFF00";
                }
                
                //div1.backgroundColor = "#FFFF00";
                //div[0].style.backgroundColor = "#FFFF00";//★
                
            }
            
            //-------Partition line——————————————————
            
            //document.getElementsByTagName();//Same Name

            function getByTagName(){
                
                var div = document.getElementsByTagName("div");
                
                div[0].style.backgroundColor = "#00FF00";
                
            }
            
            //-------Partition line——————————————————
            
            //document.getElementsByClassName();//Same Name

            function getByClass(){
                
                var div = document.getElementsByClassName("div1");
                
                div[0].style.backgroundColor = "#00FFFF";
                
            }
            //-------Partition line——————————————————
            
            function getAttr () {
                
                var img1 = document.getElementById("img1");
                alert(img1.getAttribute("src"));
                
            }//View Property Nodes getAttribute("Property name");
            
            //-------Partition line——————————————————
            
            function setAttr () {
                
                var img1 = document.getElementById("img1");
                img1.setAttribute("src","../../2-CSS Basic Grammar/img/bg_flower_multi.gif");
                img1.setAttribute("style","width: 100px;height: 100px;");
                
            }//Setting Property Nodes getAttribute("Property name","Attribute value");
            
            //-------Partition line——————————————————
            
            //JS Summary of Modified Styles
            //1,.className: Set a new one for the element class Names such as: div1.className = "div2";
            //2,.style: Set new styles for elements such as: div1.style.background-color = "blue";
            //3,.style.cssText: Modify multiple styles for elements at the same time, for example: div1.style.cssText = "width:100px;height:200px;";
            

            
            
            
        </script>
        
        <style type="text/css">
            
            .div1{
                height: 100px;
                width: 100px;
                background-color: #000000;
                color: #FFFFFF;
                line-height: 100px;
                text-align: center;
            }
            
        </style>
        
        
    </head>
    <body>
        
        <div id="div1" name="div1" class="div1">
            //This is the test area.
        </div>
        <div id="div1" name="div1" class="div1">
            //This is the test area.
        </div>
        <div id="div1" name="div1" class="div1">
            //This is the test area.
        </div>
        <img src="../../2-CSS Basic Grammar/img/bg_flower_multi.gif" id="img1"/>
        
        
        <br />
        <button onclick="getById()">adopt ID modify divcolor</button>
        <br />
        <button onclick="getByName()">adopt Name modify divcolor</button>
        <br />
        <button onclick="getByTagName()">adopt TagName modify divcolor</button>
        <br />
        <button onclick="getByClass()">adopt ClassName modify divcolor</button>
        <br />
        <button onclick="getAttr()">Fetch img Of src Attribute value</button>
        <br />
        <button onclick="setAttr()">modify img Of src Attribute value</button>
        
    </body>
</html>

2.2 Hierarchical Node Common Operations

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        
        <script type="text/javascript">
            
                window.onload = function (){
                    
                    //Get common attributes of hierarchical nodes
                    
                    var ul1 = document.getElementById("ul1");
                    
//                    var lis = ul1.getElementsByTagName("li");  //Only all li in ul1
//                    var lis = document.getElementsByTagName("li");  //Get all the li in the page

                    console.log(ul1.childNodes);//Get all the child nodes of the element (including element nodes, text nodes)
                    
                    console.log(ul1.firstChild);//Gets the first child node of the element
                    
                    console.log(ul1.lastChild);//Get the last child node of the element
                    
                    console.log(ul1.ownerDocument);//Get the current document root node, in html In the document document node
                    
                    console.log(ul1.parentNode);//Get the parent of the current node
                    
                    console.log(ul1.previousSibling);//Gets the previous sibling node of the current node
                    
                    console.log(ul1.nextSibling);//Get the last sibling node of the current node
                    
                    //All the element nodes and text nodes are obtained from the above attributes. If only element nodes are needed, correspondence is needed. Element Attributes, such as: firstChild→firstElementChild
                    
                    console.log(ul1.attributes);//Gets all attribute nodes of the current node
                    
                }
                
                //-------Create and add new nodes——————————————————
                    
                //Method 1:.creatElement("Label name")To create a new node, you need to cooperate setAttribute()Method to set properties;
                //Method 2:.appendChild(Node name)Adding a new node to the end of the element
                //Method 3:.insertBefore(New Node Name,Target Node Name): Inserting a new node before the target node
                //METHOD IV: Cloning Objects.cloneNode(true/false): The clone node is called by whoever needs to be cloned; the passing parameters can be true/false,true Represents cloning the current node and child node; false Represents that only the current node is cloned and no child node is cloned.
                    
                function appendImg(){
                    
                    //1,Create a Picture Node
                    var img = document.createElement("img");
                    //2,to img Node Settings Properties
                    img.setAttribute("src","../../1-HTML Basic label/ivicon.png");
                    //3,Will be set up img Nodes appended to body Last
                    document.body.appendChild(img)//.setAttribute("src","../../img/2017-02-25_143342.png");
                    
                }
                
                function insertImg(){
                    
                    //1,Create a Picture Node
                    var img = document.createElement("img");
                    //2,to img Node Settings Properties
                    img.setAttribute("src","../../1-HTML Basic label/ivicon.png");
                    //3,In two ul Insert pictures between
                    var ul2 = document.getElementById("ul2");
                    document.body.insertBefore(img,ul2);
                    
                }
                var count = 2;
                function copyUl(){
                    
                    //1,Fetch ul2 node
                    var ul2 = document.getElementById("ul2");
                    //2,Cloning Node
                    var ul2Clon = ul2.cloneNode(true);
                    count ++;
                    ul2Clon.setAttribute("id","ul"+count)
                    //3,In the original ul2 Before a node, insert a new cloned node
                    document.body.insertBefore(ul2Clon,ul2);
                    
                }
                
                //-------Delete and replace nodes——————————————————
                
                //1,.removeChild(Need to delete nodes): Delete the specified node from the parent container;
                //2,.replaceChild(New node, replaced node): Replace the designated node with a new node. If the new node is an existing node in the page, it will be deleted and replaced with the designated node.
                
                function deleteUl1(){
                    
                    //Fetch ul1
                    var ul1 = document.getElementById("ul1");
                    if (ul1){
                        //From parent container body Delete ul1 node
                        document.body.removeChild(ul1);
                    }else{
                        alert("Hang on, it's long gone.");
                    }
                    
                }
                
                function ul1ReplaceUl2(){
                    
                    var div = document.createElement("div");
                    div.setAttribute("style","width: 100px;height: 100px;background-color: #20B2AA;");
                    var ul2 = document.getElementById("ul2");
                    document.body.replaceChild(div,ul2);
                    
                }
                
        </script>
        
        <style type="text/css">
            
            ul{
                width: 600px;
                list-style: none;
                padding: 0;
                background-color: #20B2AA;
                display: flex;
                justify-content: space-around;
                margin-top: 20px;
            }
        
        </style>
        
    </head>
    <body>
        
        <ul id="ul1">
            <li>Item 1</li>
            <li>Item 2</li>
            <li>Item 3</li>
            <li>Item 4</li>
        </ul>
        
        <ul id="ul2">
            <li>Item 1</li>
            <li>Item 2</li>
            <li>Item 3</li>
            <li>Item 4</li>
        </ul>
        
        <button onclick="appendImg()">Insert a picture at the end</button>
        <button onclick="insertImg()">In two ul Insert a picture between</button>
        <button onclick="copyUl()">copy One ul2</button>
        <br />
        
        <button onclick="deleteUl1()">delete ul1</button>
        <button onclick="ul1ReplaceUl2() ">use ul1 replace ul2</button>
        
        
        
        
    </body>
</html>

2.3 Table Operation

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>DOM Operational Form</title>
        
        <script type="text/javascript">
            
            //Table objects:
            //1,rows Property: Returns all rows, arrays in the table;
            //2,insertRow(index): At the end of the table index+1 Line, insert a new line;
            //3,deleteRow(index): Delete the first part of the table index+1 That's ok;
            
            //Table row objects:
            //1,cells Property: Returns all cells, arrays in the current row;
            //2,rowIndex Property: Returns the index order of the current row in the table, starting at 0.
            //3,insertCell(index): Current index+1 Insert a td;
            //4,deleteCell(index): Delete the first line of the current line index+1 individual td;
            
            //Table cell object:
            //1,cellIndex Property: Returns the index order of cells in that row, starting at 0;
            //2,innerHTML Property: Sets or returns to the current cell HTMl Code;
            //3,align(valign)Property: Set the horizontal alignment of the current cell;
            //4,className Property: Sets the cell's class Name.
            
            function newRow(){
                
                var book = prompt("Title:");
                var price = prompt("Price:");
                
                var table = document.getElementsByTagName("table");
                //Insert a new row in the last row of the table
                var newRow = table[0].insertRow(table[0].rows.length-1);
                //Set cells for new rows
                var cell0 = newRow.insertCell(0);
                cell0.innerHTML = book;
                var cell1 = newRow.insertCell(1);
                cell1.innerHTML = price;
                
                getSum();
                
            }
            
            function deleteRow(){
                
                var table = document.getElementsByTagName("table");
                if(table[0].rows.length>2){
                    table[0].deleteRow(table[0].rows.length-2);
                }else{
                    alert("Delete and delete! Delete your sister!")
                }
                getSum();
            }
            
            function changeTitle(){
                
                var color = prompt("Please enter a 6-bit hexadecimal color value:");
                var table = document.getElementsByTagName("table");
                table[0].rows[0].style = "background-color:#"+color;
                
            }
            
            function copyRow(){
                
                var table = document.getElementsByTagName("table");
                var copyRow = table[0].rows[table[0].rows.length-2].cloneNode(true);
                var heJi = table[0].rows[table[0].rows.length-1];
                //Because of the browser, the table's<tr>Wrapped in<tbody>in
                //therefore<tr>Actually not.<table>The child node, therefore, needs to be fetched<table>Medium<tbody>Insertion;
                
                if(table[0].rows.length>2){
                    table[0].getElementsByTagName("tbody")[0].insertBefore(copyRow,heJi);
                }else{
                    alert("There are no lines that can be duplicated");
                }
                getSum();
            }
            
            function getSum(){
                //Get all rows of the current table
                var table = document.getElementsByTagName("table");
                var rows = table[0].rows;
                //
                if(rows.length<=2){
                    rows[rows.length-1].cells[1].innerText = 0 + "element";
                    alert("There is no computable line!");
                    return;
                }
                //Summation
                var sum = 0 ;
                
                for(var i = 1 ; i <= rows.length-2 ; i++){//Line 0 and the last line discard 1  rows.length-2
                    
                    var cells = rows[i].cells;//Get to the cell
                    sum += parseFloat(cells[cells.length-1].innerText);//The content of the last cell( innerText) Convert to numbers and sum up!
                    
                }
                
                rows[rows.length-1].cells[cells.length-1].innerText = sum.toFixed(2) + "element";
                
            }
            
            window.onload = function(){
                getSum();
            }
            
            
        </script>
        
        <style type="text/css">
            
            table{
                border-collapse: collapse;
                width: 400px;
                text-align: center;
                color: #585858;
            }
            td,th{
                border: 1px solid #8B8A8B;
            }
            table tr:last-child{
                color: #E70014;
            }
            
        </style>
        
    </head>
    <body>
        
        
        <table>
            <tr>
                <th>Title</th>
                <th>Price</th>
            </tr>
            <tr>
                <td>A room with a view</td>
                <td>30.00 element</td>
            </tr>
            <tr>
                <td>Happiness comes from heaven</td>
                <td>18.50 element</td>
            </tr>
            <tr>
                <td>60 A moment</td>
                <td>32.00 element</td>
            </tr>
            <tr>
                <td>Total</td>
                <td></td>
            </tr>
        </table>
        
        <br />
        
        <button onclick="newRow()">Add a line</button>
        <button onclick="deleteRow()">Delete the last line</button>
        <button onclick="changeTitle()">Modify the title style</button>
        <button onclick="copyRow()">Copy the last line</button>
        

    </body>
</html>

3. Mouse and keyboard, things that have to be said - events in JS

1. Tripod Tripod: Event Classification in JS

1.1 Mouse Event

Click to click

dblclick double-click

Mouse over Mouse Input

Moseout Mouse Move Out

Mosemove Mouse Scratch

mousedown mouse press

Mouse up

1.2 Keyboard Events

keydown: triggered when the keyboard is pressed

keypress: The instantaneous trigger when the keyboard is pressed and released

keyup: triggered when the keyboard is raised

[Notes]
(1) Execution order: keydown keypress keyup
(2) The keydown keypress will be executed on a regular basis.
(3) There is a keydown event, not necessarily a Keyup event (in the event triggering process, the mouse moves away, there may be no keyup)
(4) keypress events can only capture letters, numbers and symbols (including carriage return and spaces), but can not capture function keys; keydown keyup can basically capture all function keys, with special exceptions.
keypress is case-sensitive and keydown keyup is not.
keypress does not distinguish between the main keyboard and the keyboard, keydown keyup distinguishes;
[How to determine the keyboard trigger button]
(1) In the trigger function, the trigger parameter e represents the key event;
(2) confirm the case Ascii code value through e.keyCode, and then determine the key;
(3) Compatible with all browsers (generally unnecessary):
var evn = e||event; // fetch the key
var code = evn.keyCode||evn.which||evn.charCode; // fetch key code

1.3 HTML events

2. One shore and the other shore: Event model in JS

2.1 DOM0 Event Model

2.1.1 Inline model: directly use function name as attribute value of an event attribute of HTML tag;
Chestnuts <button onclick="func()"></button>
Disadvantage: It violates W3C's basic principle of separating HTML from JS!

 

2.1.2 script model: bind by event attribute in JS script;
Chestnut window.onload = function() {}
Limitations: The same node can only bind one event of the same type;

 

2.2 DOM2 Event Model (Chestnut behind!)

Advantages: In the same node, multiple listeners for similar events can be added;


(1) Adding event binding:
Before IE10: btn1.attachEvent("onclick", function);
Other browsers: btn1.addEventListener("click", function, true/false);
true: indicates event capture; false (default): indicates event bubbles
Compatible Writing: if(btn1.attackEvent){btn1.attachEvent("onclick", function);} else{btn1.addEventListener("click", function, true/false);}

(2) Cancel event binding:
detachEvent("onclick", function name);
removeEventListener("click", function name);
Note: If the time cap is cancelled, the callback function must use a named function instead of an anonymous function. Because when the event top is cancelled, the function name needs to be passed in.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Here are chestnuts</title>
        
        <script type="text/javascript">
            window.onload = function (){
                
                var btn1 = document.getElementById("btn1");
                function func1(){
                    alert(1);
                }
                function func2(){
                    alert(2);
                }
                btn1.addEventListener("click",func1,false);
                btn1.addEventListener("click",func2,false);
                
                var btn2 = document.getElementById("btn2");
                btn2.addEventListener("click",function(){
                    btn1.removeEventListener("click",func1);
                },false);
                
            }
        </script>
    </head>
    <body>
        
        <button id="btn1">I can play the window at one o'clock!</button>
        
        <br /><br />
        
        <button id="btn2">I will not play the window!</button>
    </body>
</html>

3. Up-down-event flow in JS

3.1 Event Bubble

When a DOM element triggers an event, it starts with the current DOM element and triggers the same type of event of its ancestor element one by one until the DOM root node.
DOM0 event streams are event bubbles.
In IE, attachEvent() events are bubbles.
The event added by other browsers. addEventListener() is bubbling when the third parameter is false.

3.2 Event Capture

When a DOM element triggers an event, it triggers the same type of event of its ancestor element one by one from the DOM root node until it triggers the current DOM element.

Only events added with. addEventListener() are captured when the third parameter is true.

3.3 Prevent Event Bubble

IE browser: Set the e.cancelBubble attribute to true;
Other browsers: call e.stopPropagation(); method

3.4 Cancel Event Default Behavior

IE browser: set the e.returnValue attribute to false;
Other browsers: call e.preventDefault(); method

(Chestnuts here)

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Incidents abound</title>
        <style type="text/css">
            
            #div1{
                width: 200px;
                height: 200px;
                background-color: #20B2AA;
                color: #FFFFFF;
                font-size: 20px;
                font-weight: 700;
            }
            #div2{
                width: 100px;
                height: 100px;
                background-color: #436690;
                color: #FFFFFF;
                font-size: 20px;
                font-weight: 700;
            }
            #div3{
                width: 50px;
                height: 50px;
                background-color: #4E2E83;
                color: #FFFFFF;
                font-size: 20px;
                font-weight: 700;
            }
            
        </style>
        
    </head>
    <body>
        <div id="div1">
            <div id="div2">
                <div id="div3">3</div>
                2
            </div>
            1
        </div>

        <a href="../07 JS Medium DOM/note.html" onclick="stopHref()">Jump pages</a>
    </body>
    
    <script type="text/javascript">
        var div1 = document.getElementById("div1");
        var div2 = document.getElementById("div2");
        var div3 = document.getElementById("div3");
        
        div1.addEventListener("click",function(e){
            handleE();
            console.log("div1 Triggered click Event");
        },false);
        
        div2.addEventListener("click",function(e){
            handleE();
            console.log("div2 Triggered click Event");
        },false);
        
        div3.addEventListener("click",function(e){
            handleE();
            console.log("div3 Triggered click Event");
        },false);

        function handleE(e){
            var evn = e||window.event;
            evn.stopPropagation();    
        }
        function stopHref(e){
            
            e = e||window.event;
            if (e.preventDefault) {
                e.preventDefault(); //IE Outside 
            } else {
                e.returnValue = false; //IE     
            }

            alert("How angry!");
            
        }
        
    </script>
    
</html>

Topics: Javascript Attribute IE Windows