js event object event event delegation

Posted by dyip on Mon, 28 Oct 2019 19:31:51 +0100

Event | window.event (for IE)

div.onclick = function(event ){
	var event = event || window.event;
}

Event source object the object that triggered the event

event.target Firefox only has this
Event.srcelement ie only this
Both of them have

Can be used for event delegation

Event delegation

Manage event bubbling and handle with event source objects
Advantage
Performance does not need to loop through all the elements to bind events one by one
Flexible no need to rebind events when there are new child elements

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <ul class="uls">
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5</li>
        <li>6</li>
        <li>7</li>
        <li>8</li>
        <li>9</li>
        <li>10</li>
    </ul>
    <script>
        var ul = document.getElementsByClassName('uls')[0];
        ul.onclick = function(e){
            var e = e || window.event,
                target = e.target || e.srcElement;
            console.log(target.innerText)
        }
        // Bind events directly to li
        // Trouble, low efficiency, no subsequent expansion, etc.
        var lis = document.getElementsByTagName('li'),
            len = lis.length;
        for(var i = 0; i < len; i++){
            lis[i].onclick = function(){
                console.log(this.innerText)
            }
        }
    </script>
</body>
</html>

Compatibility writing

div.onclick = function(event ){
	var event = event || window.event;
	var target = event.target  || event.srcElement;
}

Topics: IE Firefox