Recent JS challenges

Heck, JavaScript is a vast universe, and I always come across some examples that I have never dealt with before. I'll share two now.

Task


I had a TR an element with a BUTTON inside. I attached an eventListener for the TR, and the task is to decide whether someone clicked on the button (inside the TR), or another element... How should I write the listener?

Solution


function(e){
 var parentTr = e.currentTarget.id,
     target = e.target.tagName;

 if(target.toLowerCase() === "button"){
   /* react for the button */
 }
 else{
   /* another element in the tr */
 }
}
This is a very easy task when you know the difference between currentTarget and target. The latter is always the thing you touch on the screen (for a click event listener, the element that you click) or interacting with, and the former is the element what you assigned your listener to. In this case the TR. That's why I emphasized it with a 'parentTr' variable.

You don't even need a DOM traversal/search to perform this task. Okay, next.

What's wrong with this code?


var allDivs = document.getElementsByTagName("div");
 
for(var i = 0; i < allDivs.length; i++){
  allDivs[i].appendChild(document.createElement("div"));
}

Okay, so the intent is to append a DIV in each DIV already on the page. The problem is that allDivs is a DOM reference, so every time we append a new DIV to the page, this reference will update itself, and the length will grow... so yes, we end up in an infinite loop.

That's enough for today :)

No comments :

Post a Comment