Tuesday, 24 March 2015

What is difference between event.preventDefault() and return false in Javascript?

What is difference between event.preventDefault() and  return false in Javascript?


e.preventDefault() will prevent the default event from occuring.
Means If this method is called, the default action of the event will not be triggered.

This method does not accept any arguments.
Example:
jQuery(document).ready(function(){
    $('a.link').click(function (e) {
        e.preventDefault();
    });
});



e.stopPropagation() will prevent the event from bubbling.
Means If this method is called, It Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

This method also does not accept any arguments.
Example:
jQuery(document).ready(function(){
    $('a.link').click(function (e) {
        e.stopPropagation();
    });
});



return false: Will do above both that is preventDefault & stopPropagation.
Example:
jQuery(document).ready(function(){
    $('a.link').click(function (e) {
        return false;
    });
});




What is the difference between call and apply in javascript?


What is the difference between call and apply in javascript?


In Javascript, call() and apply() are predefined methods. Both methods can be used to invoke a function & must have the owner object as first parameter. See More detail below:


apply lets you invoke the function with arguments as an array.
View Example:
            function myFunction1(a, b) {
                return a + b;
            }
            var myobj1 = new Object();
            var result1 = myFunction1.call(myobj1, 5, 6);
            console.log('Result with call function: ' + result1);



call requires the parameters be listed explicitly one by one.
View Exmple:
            function myFunction2(a, b) {
                return a + b;
            }
            myArray = [5, 6];
            var myobj2 = new Object();
             var result2 = myFunction2.apply(myobj2, myArray);   
             console.log('Result with Apply function: ' + result2);