JS DOM Properties+JS Events

Keywords: Javascript Attribute IE Firefox

DOM Properties

console.log(ele.attributes) Gets the collection of attributes of an ele element

ele.attributes.getNamesItem(attr).nodeValue Gets the specified attribute value

ele.attributes[attr].nodeValue Gets the specified attribute value

ele.attributes.removeNamedItem(attr) Deletes the specified attribute

 

 

Create attributes and assign values:

var attr=document.createAttribute(attr); create attribute object

attr.value=value; assigns a value to an attribute

ele.attributes. setNamedItem (attr) Set attribute values

 

 

getAttribute() can get an element's intrinsic properties as well as its custom properties

Attribute values of a single element node can only be obtained and are not part of a document object, but a single element node object

ele.getAttribute(attr)

ele.setAttribute(attr,value) setting property

ele.removeAttribute(attr) Remove Attribute

 

 

Boolean Attribute-Case:

inputs[i].checked = 1/true/'checked'; checked

inputs[i].checked = 0/false/null; not selected

inputs[i].removeAttribute('checked');

options[i].selected=true;

input[i].readonly=true;

select.multiple=true;

div.hidden=true;

 

 

String properties:

Get data properties

elem.dataset.toggle Gets the data-toggle property

elem.dataset.xxxYyy Gets the data-xxx-yyy property

 

 

Get the class property

elem.className gets all class properties

Custom class operation method:

First post domReady.js, which is often used later. Only post it once here!!!

function myReady(fn){

    //For modern browsers, for DOMContentLoaded Events are handled in a standard event binding manner
    if ( document.addEventListener ) {
        document.addEventListener("DOMContentLoaded", fn, false);
    } else {
        IEContentLoaded(fn);
    }

    //IE simulation DOMContentLoaded
    function IEContentLoaded (fn) {
        var d = window.document;
        var done = false;

        //Execute user's callback function only once init()
        var init = function () {
            if (!done) {
                done = true;
                fn();
            }
        };

        (function () {
            try {
                // DOM Called before the tree is created doScroll Will throw an error
                d.documentElement.doScroll('left');
            } catch (e) {
                //Delay trying again~
                setTimeout(arguments.callee, 50);
                return;
            }
            // Represent without error DOM The tree is created and user callbacks are performed immediately
            init();
        })();

        //Monitor document Load Status
        d.onreadystatechange = function() {
            // If the user is domReady Functions that are then bound execute immediately
            if (d.readyState == 'complete') {
                d.onreadystatechange = null;
                init();
            }
        }
    }
}
<!DOCTYPE html>
<html lang="zh">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>class attributes</title>
    <script src="domReady.js"></script>
    <script>
      var CC = {
        // Obtain class,Return Array
        getClass: function(ele) {
          // Regularly match multiple spaces into a single space
          // The string is then split into arrays by spaces
          return ele.className.replace(/\s+/, " ").split(" ");
        },

        // Determine if there is a class
        hasClass: function(ele, cls) {
          // Query whether a class name appears in all class name collections
          return -1 < (" " + ele.className + " ").indexOf(" " + cls + " ");
        },

        // Add a class to an element
        addClass: function(ele, cls) {
          // Determine if the class name already exists
          if (!this.hasClass(ele, cls))
            ele.className += " " + cls;
        },

        // Remove a class
        removeClass: function(ele, cls) {
          if (this.hasClass(ele, cls)) {
            // Regular: Start with or without spaces
            //       There can be spaces or no spaces at the end
            //       gi Indicates to find the entire string, ignoring case
            var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)', "gi");
            // Replace the matched class name with a space
            ele.className = ele.className.replace(reg, " ");
          }
        },

        // A class: add if it doesn't exist, remove if it exists
        toggleClass: function(ele, cls) {
          if (this.hasClass(ele, cls)) {
            this.removeClass(ele, cls);
          } else {
            this.addClass(ele, cls);
          }
        }
      };

      myReady(function() {
        var body = document.body;
        console.log(CC.getClass(body));
        console.log(CC.hasClass(body, 'bbb'));
        CC.addClass(body, 'ccc');
        CC.removeClass(body, 'aaa');
        CC.toggleClass(body, 'bbb');
      });
    </script>
  </head>
  <body class="aaa bbb aaa">
      TEST
  </body>
</html>

elem.classList.add(cls) Add class

elem.classList.remove(cls) Remove class

Is there a class in elem.classList.contains(cls)

elem.classList.toggle(cls) switches a class

Output all classes as an elem.classList.toString() string

 

 

JS Events

 

There are three ways to listen for events:

1. Defined directly in html, not recommended

<button onclick="function(){alert('clicked');}">Button</button>
<body onload="init()"></body>

2. DOM Level 0 Events: Elements can only bind one listener function

Get DOM elements before binding events

var btn = document.getElementById("btn");
btn.onclick = function() {
    alert("DOM0 Level Event Binding ");
}

3. DOM Level 2 Events: Multiple listening functions can be bound, as well as capture and bubble control

var btn = document.getElementById("btn");
btn.addEventListener('click', function() {
    alert("DOM2 Level Event Binding")
}, false);

Remove event:

btn.removeEventListener('click', Dom);

IE event stream:

IE8 and below do not support DOM Level 2

No event capture, bubbles by default

var btn = document.getElementById("myBtn");
var clickme = function() {alert("Clicked");}
btn.attachEvent("onclick", clickme); /*Binding Events*/
btn.detachEvent("onclick", clickme); /*Remove Events*/
//Supplement: IE in this point window
btn.attachEvent("onclick",function(){alert(this === window); })

Cross-browser event handlers: IE compatible

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Cross-browser event handlers</title>
    </head>
    <body>
        <button id="myBtn">Click on me</button>
        <script type="text/javascript">
            var EventUtil = {
                //Binding Events
                addHandler:function(element,type,handler){
                    if(element.addEventListener){
                        //Chrome Firefox IE9 etc.     addEventListener 
                        element.addEventListener(type,handler,false);
                    }else if (element.attachEvent) {
                        //IE8 and IE8 The following browsers     attachEvent 
                        element.attachEvent("on"+ type,handler);
                    } else{
                        // This situation hardly exists
                        element["on"+type] = handler 
                    }
                },
                //Remove Events
                removeHandler: function(element,type,handler){
                    if(element.removeEventListener){
                        //Chrome Firefox IE9 etc. 
                        element.removeEventListener(type,handler,false);
                    }else if (element.detachEvent) {
                        //IE8 and IE8 The following browsers     
                        element.detachEvent("on"+type,handler);
                    } else{
                        // This situation hardly exists
                        element["on"+type] = handler
                    }
                }
            }
            var btn = document.getElementById("myBtn");
            var handler = function(){
                alert("Clicked");
            }
            EventUtil.addHandler(btn,"click",handler);
            EventUtil.removeHandler(btn,"click",handler);
        </script>
    </body>
</html>

Event Delegation and Event Bubble

Event cycle:

1. Event capture: down the DOM tree (direct relatives)

2. Event Execution

3. Event Bubble: Up along DOM Tree (Direct Relatives)

 

 

addEventListener() last parameter: false event bubble true event capture

 

 

Event Delegation: The principle is event bubbling

<!DOCTYPE html>
<html>

    <head>
        <meta charset="UTF-8">
        <title>Event Bubble and Event Capture</title>
    </head>

    <body>

        <div id="parent">
            <div id="child" class="child">Click on your son</div>
        </div>
        <ul id="ul">
            <li id="one">item1</li>
            <li id="two">item2</li>
            <li id="thr">item3</li>
            <li id="four">item4</li>
            <li id="fiv">item5</li>
            <li id="six">item6</li>
        </ul>
        <script type="text/javascript">
            //Event delegation, taking advantage of bubble mechanism
            var ul = document.getElementById("ul");
            ul.addEventListener("click", function(event) {
                
                if(event.target.id == "one") {
                    alert(1)
                } else if(event.target.id == "two") {
                    alert(2)
                } else if(event.target.id == "thr") {
                    alert(3)
                } else if(event.target.id == "four") {
                    alert(4)
                } else if(event.target.id == "fiv") {
                    alert(5)
                } else {
                    alert(6)
                }
            }, false);
        </script>
    </body>

</html>

Event Object Properties and Methods

event.type event type: such as click

event.target event target object (if the event is bound to the parent element and the child element is clicked, then the target object is the child element)

Object bound by event.currentTarget event (if the event is bound to a parent element and the child element is clicked, then the bound object is the parent element)

 

 

event.preventDefault prevents default behavior

<a href="http://Baidu.com "id=" a ">Jump Link</a>
var a = document.getElementById("a");
a.addEventListener("click",function(event){
                event.preventDefault();
                alert(11)
            });

event.stopPropagation prevents event bubbling or capture

var parent = document.getElementById("parent");
            var child = document.getElementById("child");
            parent.addEventListener("click",function(){
                alert("parent")
            })
            child.addEventListener("click",function(event ){
                alert("child");
                //Prevent bubbles
                event.stopPropagation();
            })

event.clientY browser top bottom to mouse position, do not calculate scroll axis distance

event.pageY browser top bottom to mouse position, but it calculates scroll axis distance

From the top of the event.screenY screen to the mouse position (for example, zooming out the browser, but still calculating the computer screen)

 

 

Event Objects and Methods in IE

event.type event type

event.returnValue = false; block default events

event.cancelBubble = true; prevents event bubbles

event.srcElement trigger object (who clicks on it)

 

 

Event Object Cross-Browser Compatible Writing: IE Compatible

<!DOCTYPE html>
<html>

    <head>
        <meta charset="UTF-8">
        <title>Event Object Writing Compatibility across Browsers</title>
    </head>

    <body>
        <div id="parent">
            <div id="child">Click on me</div>
        </div>
        <a href="http://Www.baidu.com "id=" a ">Jump Link</a>
        <script type="text/javascript">
            //Event addEventListener chrome firefox  IE9  event.target   preventDefault    stopPropagation
            //Event attachEvent  IE8 Series     event.srcElement     returnValue    cancelBubble 
            var EventUtil = {
                //Binding Events
                addHandler: function(element, type, handler) {
                    if(element.addEventListener) {
                        //Chrome Firefox IE9 etc.     addEventListener 
                        element.addEventListener(type, handler, false);
                    } else if(element.attachEvent) {
                        //IE8 and IE8 The following browsers     attachEvent 
                        element.attachEvent("on" + type, handler);
                    } else {
                        element["on" + type] = handler
                    }
                },
                //Remove Events
                removeHandler: function(element, type, handler) {          
                    if(element.removeEventListener) {
                        //Chrome Firefox IE9 etc. 
                        element.removeEventListener(type, handler, false);
                    } else if(element.detachEvent) {
                        //IE8 and IE8 The following browsers   
                        element.detachEvent("on" + type, handler);
                    } else {
                        element["on" + type] = handler
                    }
                },
                // Get the clicked element
                getTarget: function(event) {
                    return event.target || event.srcElement;
                },
                // Block default events
                preventDefault: function(event) {
                    if(event.preventDefault) {
                        event.preventDefault();
                    } else {
                        event.returnValue = false;
                    }
                },
                // Prevent bubbles or capture
                stopPropagation: function(event) {
                    if(event.stopPropagation) {
                        event.stopPropagation()
                    } else {
                        event.cancelBubble = true;
                    }
                }
            }
            
            var parent = document.getElementById("parent");
            EventUtil.addHandler(parent, "click", function(event) {
                alert("parent Triggered")    
            })
            
            var child = document.getElementById("child");
            EventUtil.addHandler(child, "click", function(event) {
                alert("child Triggered")    
                var target = EventUtil.getTarget(event);
                console.log(target);
                //Prevent Event Bubbles
                EventUtil.stopPropagation(event)
            })
            var a = document.getElementById("a");
            EventUtil.addHandler(a, "click", function(event) {
                EventUtil.preventDefault(event);    
            })
        </script>
    </body>

</html>

JS event type:

[UI Event Type]

1. load event

Triggered on the window when the page is fully loaded

        EventUtil.addHandler(window, "load", function(e) {
            alert("Loaded!");
        });

Picture preloading (caching pictures in memory)

            var image = new Image();
            EventUtil.addHandler(image, "load", function(event){
                alert("Image loaded!");
            });
            image.src = "smile.png";

js dynamic load completed

            var script = document.createElement("script");
            EventUtil.addHandler(script, "load", function(event){
            alert("js Loaded");
            });
            script.src = "jquery.js";
            document.body.appendChild(script);

css dynamic load completed

            var link = document.createElement("link");
            link.type = "text/css";
            link.rel = "stylesheet";
            EventUtil.addHandler(link, "load", function(event){
            alert("css Loaded");
            });
            link.href = "example.css";
            document.getElementsByTagName("head")[0].appendChild(link);

2. unload event user switches from one page to another

            EventUtil.addHandler(window, "unload", function(event){
                alert("Unloaded");
            });

3. resize Event

            EventUtil.addHandler(window, "resize", function(event){
                alert("Resized");
            });

4. scroll events. Mainly for old and new browsers

        EventUtil.addHandler(window, "scroll", function(event){
            alert(111)
            });

[Focal Event Type]

1. blur loses focus

2. Focusus does not support bubbling and gets focus

3. Fousin, like focus, supports bubbling

4. Fouout is the same as blur

 

 

[Mouse Events]

1. click Click

2. dblclick double-click

3. mousedown mouse down

4. mouseup mouse release

mousedown+mouseup=click

5. mousemove Mouse Move

6. mouseout leaves the target element or child element

7. mouseover enters the target element or child element

8. mouseenter enters the target element

9. mouseleave leaves the target element

 

 

Mouse Click+Keyboard Key

            var div = document.getElementById("myDiv");
            EventUtil.addHandler(div, "click", function(event) {
                var keys = new Array();
                if(event.shiftKey) {
                    keys.push("shift");
                }
                if(event.ctrlKey) {
                    keys.push("ctrl");
                }
                if(event.altKey) {
                    keys.push("alt");
                }
                if(event.metaKey) {
                    keys.push("meta");
                }
                console.log("keys:" + keys.join(","));
            });

mousedown mouse click subdivision:

event.button == 0 left mouse button

event.button == 1 middle mouse button

event.button == 2 right mouse button

                              

IE8 Family

event.button == 0 button not pressed

event.button == 1 Press the main mouse button

event.button == 2 Press next mouse button

event.button == 3 Press primary and secondary mouse buttons simultaneously

event.button == 4 Press the middle mouse button

            EventUtil.addHandler(myBtn, "mousedown", function(event) {
                console.log("mousedown");
                console.log(event.button) 
            })

[Keyboard Events]

event.keyCode key code

event.charCode ASCII code (for keypress)

1. any key down trigger

2. keyup releases a key

3. keypress character key trigger

4. textInput keyboard input (event.data acquisition)

 

 

[DOM change related]

1. Any element in DOMNodeRemoved document is deleted

2. Any element in DOMNodeInserted document is added

3. Any change in the structure of DOMSubtreeModified document

4. Before DOMNodeRemovedFromDocument is removed from the document

5. Before DOMNodeInsertedIntoDocument is added from the document

 

 

A key:

1,  DOMContentLoaded

Unlike load, this triggers when the DOM tree structure is complete, ignoring the image.Is the javascript file, css file, or other resource already downloaded, so faster than loading

2. readstatechange (not very useful)

Supports IE, firfox, opera, provides documentation or element loading processes, but it is difficult to predict when to use with load events

(1) document.readState == uninitialized is not initialized

(2) The loading object is loading data

(3) interactive can manipulate objects, but it is not fully loaded yet

(4) The object has been loaded

3. Value changes after hashchange #can only be added to window s

            EventUtil.addHandler(window, "hashchange", function(event) {
                console.log(event.oldURL + ":"+event.newURL);
            })

[Mobile Common]

1,  touchstart

            EventUtil.addHandler(mybtn, "touchstart", function(event) {
                console.log("Array of touch points for the current touch screen:"+event.touches)
                console.log("The array contains only touchpoint information that causes the event:"+event.changedTouches)
                console.log("Contains touch information only on elements:"+event.targetTouches)
            });

2. Touch move finger on screen

3. Touch end finger off screen

4. Touch cancel triggers when the system stops tracking touch

Posted by craka on Sun, 05 Jan 2020 11:50:33 -0800