Friday, 8 April 2016

Event bubbling in javascript

Event bubbling and capturing

Event bubbling and capturing are two ways of event propagation in the HTML DOM API, when an event occurs in an element inside another element, and both elements have registered a handle for that event. The event propagation mode determines in which order the elements receive the event.
With bubbling, the event is first captured and handled by the innermost element and then propagated to outer elements.
With capturing, the event is first captured by the outermost element and propagated to the inner elements.
Capturing is also called "trickling", which helps remember the propagation order:
trickle down, bubble up
Back in the old days, Netscape advocated event capturing, while Microsoft promoted event bubbling. Both are part of the W3C Document Object Model Events standard (2000).

Here is the html:

<div id="div1" class="element1">The blue square <div id="div2" class="element2"> The red square </div> </div>

Here is the css:

.element1{
  background-color: blue;
  height: 200px;
  width: 200px;
  position: relative;
  top: 2px;
  left: 20px;
}
.element2{
  background-color: red;
  height: 100px;
  width: 100px;
  position: relative;
  top: 40px;
  left: 50px;
}

Here is the javascript:

/* Event bubbling. */
/* The html used in this js file is given in the html file. */
var div1 = document.getElementById('div1');
var div2 = document.getElementById('div2');
var clickHandler = function divClickHandler(event){
console.log(this.id);
};
div1.addEventListener('click', clickHandler, false);//bubbling
div2.addEventListener('click', clickHandler, false);//bubbling
/* 
The false as the thrid argument in the method call above causes the bubbling. First event is handled
by div2 and then it it is bubbled to its parent div1. If we want it the other way round i.e., we wnat div1
 to handle the event first and then bubble it to div2 then we need to set the boolean value to true as the
 thrid argument in the call to addEventListener().
 */
div1.addEventListener('click', clickHandler, true);//capturing
div2.addEventListener('click', clickHandler, true);//capturing

/* If we wnat the event to be handled by the parent but not by the child then we can stop the propagation of 
the event by using method stopPropgagation() as shown below. In this case the parent will handle the event 
and stop further propagation of the event to the child. 
*/
var div1 = document.getElementById('div1');
var div2 = document.getElementById('div2');
var clickHandler = function divClickHandler(event){
console.log(this.id);
    event.stopPropagation();
    /* 
    If we want to prevent the default action when something is clicked then we include the followin one line of   code also. 
    */
    event.preventDefault();
};
div1.addEventListener('click', clickHandler, true);//capturing
div2.addEventListener('click', clickHandler, true);//capturing

Thursday, 7 April 2016

The Event Object in javascript


The event object in javascript is created by the javascript runtime engine which gets passed to an event handler. Here are some key properties of this object:

1. bubbles - true or false - based upon whether this event bubbles up to their parents or not.

2. cancelable - true or false - will let us know whether we can cancel any kind of propagation of this event.

3. currentTarget - is the DOM (Document Object Model) element that we are currently looking at.

4. defaultPrevented - true or false - tells us if preventDefault() was called.

5. detail - This property holds extra information about the event.

6. eventPhase - 1/2/3 - 1 means that it is the capture phase which is the opposite of bubbling - going in the other direction of bubbling. 2 means that we are currently at the target. 3 means that we are in the process of bubbling.

7. preventDefault() - To prevent the browser from executing any default behavior. An example would be preventing the submit button on a form submit the form. Another example would be preventing the browser following a link in an anchor tag.

8. stopPropagation() - will stop all event-capturing and bubbling.

9. stopImmediatePropagation - will stop all event-capturing and bubbling but will also make sure that no more handlers get called.

10. target - the original target of this event. For example if we click on a button and the event bubbles up from parent to parent to parent, target will be set to that original button.

11. trusted - true or false - true if event comes from the browser. false if event is triggered through the javascript code written by the programmer.

12. type - name of the event. For example it would be the string "click" for a click event.

Query selectors in javascript

Here is the html code that will be used in the javascript on this page.

<article id="article1" class="my-custom-class">
    <h3>
        Title of the page goes here.
    </h3>
    <p>
        This is paragraph one.
    </p>
    <p class="special">
        This is paragraph two.
    </p>
    <p class="special">
        This is paragraph three.
    </p>
</article>

Here is the javascript code that uses the html code above.

//Query selectors
/* 
Use MDN, the Mozilla Developers Network to learn more about other functions and properties.
 */
var element = document.querySelector('article');
console.log(element);//prints on the console the complete article tag
var element = document.querySelector('#article1');
console.log(element);
//Getting only the first paragraph
var element = document.querySelector('.special');
console.log(element);
//Getting all the paragraphs in the document
var elements = document.querySelectorAll('.special');
console.log(elements);

Document object in javascript - introduction

Here is the html code that has been used in the javascript code on this page.

<article id="article1" class="my_new_class">
    <h3>
        Demonstrating how to get an element fron an html document in javascript
    </h3>
    <p>
        This is paragraph one.
    </p>
    <p>
        This is paragraph two.
    </p>
    <p class="new_point">
        This is paragraph three.
    </p>
    <p class="new_point">
        This is paragraph four.
    </p>
</article>

Here is the javascript code that uses the html code above.

var element = document.getElementById('article1');
console.log(element);//We get the element in the document that has id=article1
var elements = document.getElementsByTagName('p');
console.log(elements);//We get an array of all the elements that has a tag of p i.e., paragraph
var element = document.getElementsByTagName('h3');
console.log(element);//We get an array of all the elements with heading set to h3
var elements = document.getElementsByClassName('new_point');
console.log(elements);//We get an array of our two paragraph elements with class=new_point

//***************************************************************************
/* 
Once we get an element from a document then we can get access to any of its attributes also. 
*/
var e = document.getElementById('article1');
console.log(e.getAttribute('class'));//my_new_class

//We can dynamically set an attribute also. 
e.setAttribute('class', 'my_old_class');
console.log(e.getAttribute('class'));//my_old_class

//We can get all the child nodes of an element.
console.log(e.childNodes); /* We get on the console
[text, h3, text, p, text, p, text, p.new_point, text, p.new_point, text]
the array has text 6 times because we have spaces before the h3, and all the paragraph elements and white space is represented as text. */

The location object in javascript

/* 
The location object lets us look at the browser's URL location. 
*/

console.log(location.href); // https://fiddle.jshell.net/_display/

console.log(location.host); //fiddle.jshell.net

console.log(location.port); //port number

console.log(location.protocol); // https:


//redirecting to another page/website but it depends on your browsing settings.
location.assign('https://www.google.com');//directs browser tot he page passed as argument.

System Dialogs in javascript - alert, confirm, and prompt

//System dialogs
//1. alert
alert('Hello jsfiddle.net');


//2. confirm - with ok and cancel button ok button for the if is true case and cancel button for the else case 
if(confirm('Do you want to leave this page?')){
 console.log('You chose to leave the page.');
}
else{
 console.log('You chose to stay on the page.');
}

//3. prompt - with an ok and a cancel button
var input = prompt('Enter Your address please!');
if(input != null && input != '')
 console.log(input);
else
{
 console.log('You did not enter any address');
}

timer in javascript

//Timer related code snippets in js
console.log(new Date().getSeconds()); //e.g., 49 seconds
/* function setTimeout() is a global object window and we do not need to prefix it with window.*/
setTimeout(function() {
  console.log(new Date().getSeconds());
 }, 1000
);/* 1000 milliseconds of delay should be observed before calling the function setTimeout after the internal function has been called. */
/* I got 
6
7
because there were 6 seconds in to the minute and then it was 7 seconds into the minute. Note that the 7 appears after an 
interval of 1 second after the 6 appears on the console. If I delete the ', 1000' then I will 
instead get
6
6
as no delay is being observed. 
*/

//*******************************************************
console.log(new Date().getSeconds());
/* Assigning the id of the timer to a variable so that we use that id later on to clear the timer and prevent it from being activated. */
var id = setTimeout(function(){
  console.log(new Date().getSeconds());
 }, 1000
);
clearTimeout(id);
/* After executing the code above we get only one number as our timer is prevented being activated by the clearTimeout() method.
*/
//*******************************************************
/* In the code snippet given below we pass a funciton to method setInterval() and that internal function will be called over and 
over again untill the if condition is true and it is then when the function clearInterval(id) will be called to stop calling the 
internal function.
*/
console.log(new Date().getSeconds());
var id = setInterval(function(){
  var seconds = new Date().getSeconds();
        console.log(seconds);
        if(seconds === 30)//shutting down the timer when there are 30 seconds into the minute
         clearInterval(id);//id exists in the outer function.
 }, 1000
);
//*******************************************************