ivapopova

event_delegation_task.html

Oct 26th, 2018
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
HTML 5 1.58 KB | None | 0 0
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4.     <title>Demo1</title>
  5. </head>
  6. <body>
  7.     <p>Output</p>
  8.     <button class="test1">Test1</button>
  9.     <button class="test2">Test2</button>
  10.     <script type="text/javascript">
  11.         let outNode = document.querySelector('p');
  12.         let ulNode = document.createElement("ul");
  13.         let btnTest1 = document.querySelector('.test1');
  14.         let btnTest2 = document.querySelector('.test2');
  15.  
  16.         btnTest1.addEventListener('click', test1);
  17.         btnTest2.addEventListener('click', test2);
  18.  
  19.         let list_items = 10000;
  20.  
  21.         function createList(list_items){
  22.             for(let i = 0; i < list_items; i++){
  23.                 let liNode = document.createElement("li");
  24.                 liNode.innerHTML = `Item ${i}`
  25.                 ulNode.appendChild(liNode)
  26.             }
  27.  
  28.             document.body.appendChild(ulNode);
  29.         }
  30.         createList(list_items);
  31.         outNode.innerHTML = `Created ${list_items} items!`;
  32.  
  33.         function test1(){
  34.             // SLOW: attach event to each child:
  35.             if(ulNode){
  36.                 let liNodes = ulNode.children;
  37.  
  38.                 for(let i = 0, length1 = liNodes.length; i < length1; i++){
  39.                     liNodes[i].addEventListener("click", function(){
  40.                         outNode.innerHTML = liNodes[i].innerHTML;
  41.                         outNode.style.backgroundColor = "red"
  42.                     },false)
  43.                 }
  44.             }
  45.         }
  46.  
  47.  
  48.         function test2(){
  49.             /* TASK:
  50.                 1. Implement the same functionality as 'Test1', but this time using
  51.                 the "Event Delegation" approach. But lets this time the output node
  52.                 background to be 'green'
  53.  
  54.                 2. Measure the performance between two approaches.
  55.                 3. Use the Performance Tab in dev Tools
  56.                 4. Also use the console.profile methods
  57.             */
  58.         }
  59.     </script>
  60. </body>
  61. </html>
Advertisement
Add Comment
Please, Sign In to add comment