Jelajahi Sumber

Intermezzo: events capturing/bubbling, vanilla js and jQuery.

Frederic G. MARAND 8 tahun lalu
induk
melakukan
4a08605090
1 mengubah file dengan 73 tambahan dan 0 penghapusan
  1. 73 0
      Chapter 3/events.html

+ 73 - 0
Chapter 3/events.html

@@ -0,0 +1,73 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+  <meta charset="UTF-8">
+  <title>Title</title>
+  <style type="text/css">
+    div {
+      float: left;
+      height: 300px;
+      width: 400px;
+      margin: 0;
+      background-color: orange;
+    }
+
+    span {
+      display: block;
+      text-align: center;
+      height: 50%;
+      width: 50%;
+      margin: 75px 25% 75px 25%;
+      padding: 10%;
+      box-sizing: border-box;
+      background-color: lightsteelblue;
+    }
+
+    p {
+      float: left;
+      height: 300px;
+      width: 400px;
+      margin: 0;
+      background-color: chartreuse;
+    }
+  </style>
+  <script src="jquery.js"></script>
+  <script>
+    function notify(e) {
+      var current = e.currentTarget;
+      var target = e.target;
+      var join = Array.prototype.join;
+      // Element.classList is not an Array but just an Object
+      var currentClasses = join.call(current.classList || [], ' ');
+      var targetClasses = join.call(target.classList || [], ' ');
+      console.log(current.tagName, currentClasses, 'from', target.tagName, targetClasses);
+
+// Vanilla JS:
+//      e = e || window.event; // Needed for IE, which does not pass the event to handlers.
+//      var target = e.target || e.srcElement; // srcElement for IE, target for every other browser,
+//      // Defeat Safari bug: if an event takes place on an element that contains
+//      // text, this text node, and not the element, becomes the target of the
+//      // event. Therefore we check if the target's nodeType is 3, a text node.
+//      // If it is we move to its parent node, the HTML element.
+//      if (target.nodeType == 3) {
+//        target = target.parentNode;
+//      }
+//      console.log(e, target.tagName, target.classList, target.nodeType);
+    }
+
+    $(function () {
+      $('body').find('*').click(notify);
+    });
+  </script>
+</head>
+
+<body>
+  <div class="foo">
+    Text
+    <span class="bar">
+      <a href="#">The quick brown fox jumps over the lazy dog.</a>
+    </span>
+  </div>
+  <p>How razorback-jumping frogs can level six piqued gymnasts!</p>
+</body>
+</html>