Tuesday, September 18, 2018

JavaScript - Events - Event Listeners

As an alternative to Event handlers, JavaScript has event listeners. This alternative mainly addresses the problem that you cannot have multiple event handlers for the same event on the same element.

Consider the following code snippet

var btn = document.querySelector("button");
btn.addEventListener("click", myListener1);
btn.addEventListener("click", myListener2);

function myListener1(){
  console.log("inside Listener 1");
}

function myListener2(){
  console.log("inside Listener 2");
}

addEventListener is a method available on each HTML element. The first argument is the name of the event. In the above code the event is click. The second argument is the function I want to run when the listener fires when this event is recognized.

It is also possible to remove a listener:

var btn = document.querySelector("button");

btn.addEventListener("click", myListener1);
btn.addEventListener("click", myListener2);

function myListener1(){
  console.log("inside Listener 1");
}

function myListener2(){
  console.log("inside Listener 2");
}

setTimeout(function(){btn.removeEventListener('click',myListener1);
                     console.log("Listener 1 removed.");
                     },2000);


removeEventListener method allows to remove listener. In the above example, Listener 1 is removed after 2 seconds.




JavaScript - Events - Event Handlers



window.onload = function() {
  console.log("Window loaded.");
};


Now, say - I have the following code snippet:
<body>
  <button>Click Here</button>
</body>

Now, let us add an onclick event on this button:

var btn = document.querySelector("button");

btn.onclick = function(){
  console.log("Button Clicked");
};

We have setup the onclick handler. On pressing the button we can see the output on the console. This is a very useful concept.

But, how can we know, which specific functions are available on the HTML element?
Technique 1: Log the element to the console and then check the properties and then we can identify the event handlers by the on* prefix on the event handler variables.
Technique 2: Google for JavaScript <<element name>> <<events >> and we can find the relevant links with information about it.

We can add the onclick event on any HTML element. We can add the onclick event on the document itself:

document.onclick = function(){
  console.log("Clicked");
};

But, there is one major disadvantage of this approach. Now, suppose we have two event handlers associated with the same button element:

var btn = document.querySelector("button");

btn.onclick = function(){
  console.log("Button Clicked");
};

btn.onclick = function(){
  console.log("Button Clicked 2");
};

Now we see only the message:
Button Clicked 2

.. on the console.

This has happened because the first event handler is simply overwritten. Hence, it is no longer available. Hence, this can become a problem as there will be times when you will need multiple listeners!

JavaScript - Events - How does it work?

You have a general event interface which JavaScript offers. Then you have multiple specific events which implement the top level event:

The following link lists the interfaces based on the main event interface:
https://developer.mozilla.org/en-US/docs/Web/API/Event#Introduction

 Therefore all events in JavaScript share certain properties and methods. Also, there are certain events and properties which are important and more frequently used than others.

The following link lists the properties of the general event interface or object and also specific events which you can listen:
https://developer.mozilla.org/en-US/docs/Web/API/Event#Properties




Refer:
https://developer.mozilla.org/en-US/docs/Web/API/Event
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events

Practice at:
http://jsbin.com/?js,console

JavaScript - Document Object Model - Dialogs

There are built in dialogs the window object offers. Dialogs are basically pop-ups the user will see and the one very prominent one which is used for debugging instead of console.log is the Alert.

Alert:
It is a function on the window object. It is used like this:
alert("This is an alert");

I get this window here. We can only click OK.

Confirm:
Apart from alert we have confirm function which will provide the user with two options:

  • Cancel
  • OK


confirm("Are you sure?");


I can also use this with console.log():

console.log(confirm("Are you sure?"));

If the user chooses OK. Then true is returned.
If the user chooses Cancel. Then false is returned.

Prompt:
The prompt dialog will provide the user with a textfield for inputting:
console.log(prompt("What is your Name ?"));



Once the user types in the answer in the textField and presses OK. The answer is returned.
We must really think before using them as there are better ways with modals - as in page pop ups.



Practice at:
http://jsbin.com

Refer:







JavaScript - Document Object Model - Elements and Nodes

Let us first explore the cross browser method of deleting elements. Consider the following body code:

<body>
  <h1 id="firstId">hey there</h1>
<ul>
  <li ><a href="#">Link 1</a></li>
  <li class = "dimple">full</li>
  <li class = "pimple">ness</li>
  </ul>
</body>


Now, instead of the following:

var a = document.querySelectorAll("li")[1];
a.parentElement.removeChild(a);

we can also use:

var a = document.querySelectorAll("li")[1];
a.parentNode.removeChild(a);

In both cases the second list item is removed. Now, when we open in developer tools of chrome. We can see that in the Elements tab - there are numerous nodes. Now, all elements are nodes. But the DOM also contains nodes which are not HTML elements. Hence, we cannot use parentElement and parentNode interchangeably all the time. But, if you are using elements in an HTML then parentElement is the one which we need to use.


Monday, September 17, 2018

JavaScript - Document Object Model - Delete Element

Let us first explore the cross browser method of deleting elements. Consider the following body code:

<body>
  <h1 id="firstId">hey there</h1>
<ul>
  <li ><a href="#">Link 1</a></li>
  <li class = "dimple">full</li>
  <li class = "pimple">ness</li>
  </ul>
</body>


Now, if you want to remove the second list item with text = full . Then we do it in the following manner:

var a = document.querySelectorAll('li')[1];
a.parentElement.removeChild(a);

This looks somewhat inconvinient as we are first selecting the parent and then removing the child. But, this is the only method with is supported by the older browsers.

The better way would be to just call the remove method.
var a = document.querySelectorAll('li')[1];
a.remove();

But use this with caution as it does not work with all the browsers.

JavaScript - Document Object Model - Insert Element

Let us work on the following body code:

<body>
  <h1 id="firstId">hey there</h1>
<ul>
  <li ><a href="#">Link 1</a></li>
  <li class = "dimple">full</li>
  <li class = "pimple">ness</li>
  </ul>
</body>


Consider the following example:

var p = document.createElement("P");
p.textContent = "A new Paragraph!";
p.style.fontSize = "16px";
console.log(p);
// let us decide where we want to add it

var a = document.querySelectorAll("li")[0];
a.appendChild(p);

This will insert the paragraph inside the first list item after the anchor tag. Now, if I want to insert it before the anchor tag.

var p = document.createElement("P");
p.textContent = "A new Paragraph!";
p.style.fontSize = "16px";
console.log(p);
// let us decide where we want to add it

var li = document.querySelectorAll("li")[0];
var a = li.firstElementChild;
li.insertBefore(p,a);


So, this is how we can add the elements at different places of our document.