Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Wednesday, 14 February 2018

What is Object.assign()? and how to use Object.assign()?

What is Object.assign()? and how to use Object.assign()?

Question: What is Object.assign()?
The Object.assign() is used to copy the values of all properties from one or more source objects to a target object.



Question: What is syntax for Object.assign()?
Object.assign(target, ...sources);



Example 1
const object1 = {
  a: 1,
  b: 2,
  c: 3
};
const object2 = Object.assign(object1,{d:4});
console.log(object2);

Output
Object { a: 1, b: 2, c: 3, d: 4 }



Example 2
const object1 = {
  a: 1,
  b: 2,
  c: 3
};
const object2 = Object.assign(object1,{d:4,e:5, a:11});
console.log(object2);

Output
Object { a: 11, b: 2, c: 3, d: 4, e: 5 }



Example 3
const object1 = {
  a: 1,
  b: 2,
  c: 3
};
const object2 = Object.assign(object1,{d:4,e:5, a:11},{f:5, a:111});
console.log(object2);

Output
Object { a: 111, b: 2, c: 3, d: 4, e: 5, f: 5 }



Example 4
const object1 = {
  a: 1,
  b: 2,
  c: 3
};
const object2 = Object.assign(object1,{d:4,e:5, a:11},{f:5, a:111},null, undefined);
console.log(object2);

Output
Object { a: 111, b: 2, c: 3, d: 4, e: 5, f: 5 }



Example 5
const object1 = {
  a: 1,
  b: 2,
  c: 3
};
const object2 = Object.assign(object1,{d:4,e:5, a:11},{f:5, a:111},null, undefined,{g:6, a:1111});
console.log(object2);



Output
Object { a: 1111, b: 2, c: 3, d: 4, e: 5, f: 5, g: 6 }



Tuesday, 13 February 2018

JSON.stringify - What is JSON.stringify? and how to use?

JSON.stringify - What is JSON.stringify? and how to use?

Question: What is JSON.stringify()?
The JSON.stringify() method converts a JavaScript value to a JSON string.
It can also convert a Object/Array to JSON String.


Question: Give few example of JSON.stringify()?
Following are few example of JSON.stringify()
JSON.stringify({});                  // {} 


JSON.stringify(true);                // 'true'


JSON.stringify('foo');               // '"foo"'


JSON.stringify([1, 'false', false]); // '[1,"false",false]'


JSON.stringify({ x: 5 });            // '{"x":5}'


JSON.stringify({ x: 5, y: 6 });// '{"x":5,"y":6}'


JSON.stringify({ x: 5, y: 6 });// '{"x":5,"y":6}'



Question: What is use of 2nd parameter of JSON.stringify()?
2nd parameter of JSON.stringify() is a replacer.
It can be an array OR can be function.




Question: Give an example of callback function of replacer of JSON.stringify()?
var objectData={}
objectData.a='Apple';
objectData.b=undefined;
objectData.c=';
   
objectData=JSON.stringify(objectData, function(k, v) {                
if (typeof v === 'undefined') {
  return '';
}else{
    return v;
}
});

this replacer function will replace the undefined with empty space.




Question: Give an example of array of replacer of JSON.stringify()?
var foo = {name: 'web tech', week: 350, transport: 'car', month: 7};
JSON.stringify(foo, ['week', 'month']);  //"{"week":350,"month":7}"

IT will return those which match with array




Question: Difference between JSON.stringify and JSON.parse?
JSON.stringify convert a Javascript object into JSON text(JOSN string).
JSON.parse convert a JSON text into into Javascript object.

Both are opposite to each other.

Thursday, 14 July 2016

Callback, Trigger and Event handler in javaScript

what callback, trigger and event handler in javaScript
Callback is a function that is passed to another function as parameter and callback function is called inside another function.
Example:
$("#MyButton").click(function(){
    $("p#hideDiv").hide("slow", function(){
        alert("function() is callback and called.");
    });
});

Here following are callback function.
function(){
        alert("function() is callback and called.");
    }



The trigger is code that is executed automatically on some events.
Example:
<script>
$(document).ready(function(){
    $("input").select(function(){
        $("input").after(" Text marked!");
    });
    $("button").click(function(){
        $("input").trigger("select");
    });
});
</script>
<input type="text" value="Hello World" />
<button>Click on this button</button>



Handler: An event handler executes a part of a code based on certain events occurring within the application such as onClick, onBlur, onLoad etc.
Example:
$(document).ready(function(){
    $("button").click(function(){
        $("input").trigger("select");
    });
});



Following are few more event handler
Event Description
onchange An HTML element has been changed
onclick The user clicks an HTML element
onmouseover The user moves the mouse over an HTML element
onmouseout The user moves the mouse away from an HTML element
onkeydown The user pushes a keyboard key
onload The browser has finished loading the page



Friday, 15 April 2016

How to apply css in iframe with javaScript?

How to apply css in iframe with javaScript?

See Following Working Example:
Suppose you have Following Iframe
<iframe border="0" cellspacing="0" frameborder="0" id="myIframeWebsite" name="myIframeWebsite" src="http://example.com/mydir/file.html"></iframe>

Now you just need to add a script code which will add the css file in iframe.
For Example:
<iframe border="0" cellspacing="0" frameborder="0" id="myIframeWebsite" name="myIframeWebsite" src="http://example.com/mydir/file.html"></iframe>
<script type="text/javascript">
var iframeCssLink = document.createElement("link") 
iframeCssLink.href = "/css/myiframecss.css"; 
iframeCssLink.rel = "stylesheet"; 
iframeCssLink.type = "text/css"; 
frames['frame1'].document.body.appendChild(iframeCssLink);
</script>

What will do above code
Whenever iframe load in browser, "/css/myiframecss.css" file will will be added in the head of iframe.
You just need to add all the css inside "/css/myiframecss.css"


Note: Iframe and website must have same Domain, Port and protocol.



Sunday, 17 January 2016

How to load disqus when scroll to the bottom of the page?

How to load disqus when scroll to the bottom of the page?

Question: What is Disqus?
It is comment hosting service for web sites and online communities. It provide Services so that you can add comment system in your website.


Question: is Disqus multilingual?
Yes, It is.


Question: When Disqus was Launched?
October 2007


Question: Can we embed disqus in website?
Yes, you can embed.


Question: Does it provides channel for discussion?
Yes, It provides channel to discuss.


Question: What is offical website of Disqus?
http://disqus.com


Question: Can facebook user post comment using their fb account?
Yes, Facebook, twitter and google user can post comment using their account


Question: How to load disqus when scroll to the bottom of the page?
                        
  /*  CONFIGURATION VARIABLES  - MUST SET */
  var disqus_developer = 0;
  var disqus_shortname = 'aboutcity'; // required: replace example with your forum shortname                            
  var disqus_identifier = '/2015/07/ajax-technical-interview-questions-and-answers-for-experienced.html';
  var disqus_url = 'http://www.web-technology-experts-notes.in/2015/07/ajax-technical-interview-questions-and-answers-for-experienced.html';                    
  /*  CONFIGURATION VARIABLES  - MUST SET */
  
  var disqus_loaded = false;

  function load_disqus(){     
    disqus_loaded = true;
    var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
    dsq.src = "http://"+disqus_shortname+".disqus.com/embed.js";       
    (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);

  }

/** check now bottom of page **/
  window.onscroll = function(e) {
   if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
    //hit bottom of page
    if (disqus_loaded==false){ load_disqus() };
   }
  };



Thursday, 13 August 2015

How do you get a timestamp in JavaScript?

How do you get a timestamp in JavaScript?

Question: What is timestamp?
timestamp is the current time of an event that is recorded by a computer. In JavaScript, it gives local time (computer ).


Question: How do you get a timestamp in JavaScript?
Date.now()



Question: How do you get a timestamp in number of seconds?
Math.floor(Date.now() / 1000)



Question: How do handle exception to this is IE8 and other Browser?

if (!Date.now) {
Date.now()
}



Question: How do you get the date from the time object
new Date().getDate()



Question: What are other date-functions in javascript?
getDate(): Get the day as a number (1-31)
getDay(): Get the weekday as a number (0-6)
getFullYear(): Get the four digit year (yyyy)
getHours(): Get the hour (0-23)
getMilliseconds(): Get the milliseconds (0-999)
getMinutes(): Get the minutes (0-59)
getMonth(): Get the month (0-11)
getSeconds(): Get the seconds (0-59)
getTime(): Get the time (milliseconds since January 1, 1970)

Wednesday, 12 August 2015

How do closures work in Javascript

How do closures work in Javascript


Question: What is closures?
Whenever you defined a the function within another function, the inner function has access to variables in the outer function.


Following are Simple example of closure.
function mainFunction(outerData) {
  var mainFuncData = 3;

  function innerFunction(innerFuncData) {
    console.log(outerData + innerFuncData + (++mainFuncData)); // will alert 16
  }

  innerFunction(10);
}

mainFunction(7); //17


Question: Why it can access to variables in the outer function?
Because It is defined as var , which means it is global variable.

Sunday, 7 June 2015

Load multiple javascript files asynchronously

load multiple javascript files asynchronously



In Every website, We have to include the JavaScript. We need to include multiple JavaScript file in single web page.

It's always prefer to include the javascript at the bottom of the page so that loading of content remain fast. So we should add at the bottom of the page.

We should also load the JavaScript files asynchronously, means load JavaScript file parallel.


There are two ways to load JavaScript file. Newer browsers have async attribute which load JavaScript asynchronously.
<scritp async="true" src="yourscript.js" type="text/javascript"></scritp>

Use custom JavaScript function to load javascript-file asynchronously.


<script type="text/javascript">
function loadScript (scriptpath){
    var s=document.getElementsByTagName('script')[0];
    var ss=document.createElement('script');
    ss.type='text/javascript';
    ss.async=true;
    ss.src= scriptpath;
    s.parentNode.insertBefore(ss,s);
}
</script>

Just call the loadScript function to load javascript file asynchronously. For Example.
<script type="text/javascript">
loadScript('/js/jQueryJSFIle1.js');
loadScript('/js/jQueryJSFIle2.js');
loadScript('/js/jQueryJSFIle3.js');
</script> 

Thursday, 2 April 2015

Javascript Interview Questions and Answers for Experienced 2

Javascript Interview Questions and Answers for Experienced 2



Question: How to set a default parameter value for a JavaScript function?
/** Here email is parameter in which we have set the default value i.e email@domain.com **/
function function1(name, email)
 {
   email = typeof email !== 'undefined' ? email : 'defaultemail@domain.com';
    console.log('name='+name+', Email= '+email);
 }

function1('john','myname@gmail.com');
function1('john');



Queston: How to convert a string to lowercase?
var str='This is testing String';
str = str.toLowerCase();
console.log(str);



Question: How to modify the URL of page without reloading the page?
use pushState javascript function.
For Example:
window.history.pushState('page2', 'This is page Title', '/newpage.php');


Question: How to convert JSON Object to String?
var myobject=['Web','Technology','Experts','Notes']
JSON.stringify(myobject);


Question: How to convert JSON String to Object?
var jsonData = '{"name":"web technology","year":2015}';
var myobject = JSON.parse(jsonData);
console.log(myobject);


Question: How to check an variable is Object OR String OR Array?
Use below function to get Data type of javascript variable.
function checkDataType(someVar){
 result ='String';
    if(someVar instanceof Object){
       result ='Object'
    }
    if($.isArray(someVar)){
      result = 'Array';
    }
return result;
}

var someVar= new Array("Saab", "Volvo", "BMW");
console.log(result);



Question: Can i declare a variable as CONSTANT like in PHP?
No, I think cosntant not exist in javascript.
But you can follow same type convention to declare constant.
var CONSTANT_NAME = "constant value";


Question: How to open URL in new tab in javascript?
use javascript, window.open function.
window.open('http://www.web-technology-experts-notes.in/','_blank');


Question: What is difference between undefined and object?
undefined means some variable's value is not defined yet.
object means variables's value is defined that is either function, object OR array.

With use of below, you can easily determine whether it is object OR NULL.
console.log(typeof(null));      // object
console.log(typeof(undefined)); // undefined


Question: How to get current date in JavaScript?
var today = new Date();
console.log(today);



Question: How do I declare a namespace in JavaScript?
var myNamespace = {

    function1: function() {   },

    function2: function() {    }

    function3: function() {    }
};

myNamespace.function3();


Question: What is the best way to detect a mobile device in jQuery?
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {

}



Question: How to detect mobiles including ipad using navigator.useragent in javascript?
 if(navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/webOS/i) ||  navigator.userAgent.match(/BlackBerry/i) || navigator.userAgent.match(/iPhone/i)){
        console.log('Calling from Mobile');      
    }else{
    console.log('Calling from Web');      
}



Question: How to detect mobiles including ipad using navigator.useragent in javascript?
 if(navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/webOS/i) ||  navigator.userAgent.match(/BlackBerry/i) || navigator.userAgent.match(/iPhone/i)){
        console.log('Calling from Mobile');      
    }else{
    console.log('Calling from Web');      
}






Sunday, 29 March 2015

How do I copy to the clipboard in JavaScript?

How do I copy to the clipboard in JavaScript?

Step 1: Add Following javascript function in Web page.
    function selectAllData(id) {
    var obj = document.getElementById(id);
        var text_val=eval(obj);
        text_val.focus();
        text_val.select();
        if (!document.all) return; // if IE return;
        r = text_val.createTextRange();
        r.execCommand('copy');
    }

Step 2: call selectAllData('id') function with passing the id of the container. See Example
<input onclick="return selectAllData('textareaId')" type="button" value="Select All" />


Following are consolidate Code:

<script type="text/javascript"> function selectAllData(id) { var obj = document.getElementById(id); var text_val=eval(obj); text_val.focus(); text_val.select(); if (!document.all) return; // if IE return; r = text_val.createTextRange(); r.execCommand('copy'); }</script> <textarea cols="30" id="textareaId" row="50"> javascript interview questions and answers javascript interview questions and answers javascript interview questions and answers javascript interview questions and answers javascript interview questions and answers javascript interview questions and answers javascript interview questions and answers javascript interview questions and answers javascript interview questions and answers javascript interview questions and answers </textarea> <input onclick="return selectAllData('textareaId')" type="button" value="Select All" />


See demo:








Difference between encodeuri and encodeuricomponent in javascript?

Difference between encodeuri and encodeuricomponent in javascript

encodeURI: This javascript function is used to encode a URI (Uniform Resource Identifier). This function encode special characters except the following:
, / ? : @ & = + $ #

We used encodeURI when we want to encode the url parameter.
For Example:
var url=encodeURI('http://www.example.com/mysite.php?name=web technology experts notes&char=*');
console.log(url);
//output will be following
//http://www.example.com/mysite.php?name=web%20technology%20experts%20notes&char=*

decodeURI(): It is used to decode a URL which was encoded with encodeURI.




encodeURIComponent: This javascript function is used to encode a URI component. This function encodes all special characters Except the following:
~!*()'

We used encodeURIComponent when we want to encode the both (URI parameter & URI components). For Example:
var url=encodeURIComponent('http://www.example.com/mysite.php?name=web technology experts notes&char=*');
console.log(url);
//output will be following
//http%3A%2F%2Fwww.example.com%2Fmysite.php%3Fname%3Dweb%20technology%20experts%20notes%26char%3D*
decodeURIComponent() It is used to decode a URL which was encoded with encodeURIComponent.

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);





Monday, 23 March 2015

How to Include a JavaScript file in another JavaScript file?

How to Include a JavaScript file in another JavaScript file?

Including a javascript file in another javascript file is common in web development.
Because many times we include the javascript file at run time on the behalf of some conditions.

So, we can achieve this using javascript as well as using jQuery.


Method 1: Use JavaScript to include another JavaScript file.
Step 1: Add following function in web page.
function loadScript(url)
{    
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;
    head.appendChild(script);
}

Step 2:just call the below loadScript function, Where you want to include the js file.
 loadScript('/js/jquery-1.7.min.js');



Method 2: Use jQuery to include another javasScript file .
Step 1: Add jQuery File in your webpage.
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script> Step 2: Just call the  getScript  function functions.
 jQuery(document).ready(function(){
    $.getScript('/js/jquery-1.7.min.js');
});




Saturday, 21 March 2015

How can I get query string values in JavaScript and jQuery?

How can I get query string values in JavaScript and jQuery?

I want to get the values from the Query String (means from URL), values are dynamic but query string variable is constant.

Suppose, I have following URL:
http://www.example.com/country.php?id=10&c=country

Now, I want to get the value of following query string.
id //currently it is 10, but it is dynamic.
c //currently it is country, but it is dynamic.


Solution 1: Get the value of query string with JavaScript.
Step 1: Add following javaScript function in your page.
   
function getParam(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        result = regex.exec(location.search);
    return result === null ? "" : decodeURIComponent(result[1].replace(/\+/g, " "));
}

Step 2: Use getParam function to get the query string values. See below:
console.log(getParam('id'));
console.log(getParam('c'));



Solution 2: Get the value of query string with jQuery.
Step 1: Add jQuery File in your webpage.
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>

Step 2: Add following jQuery function in web page.
jQuery(document).ready(function(){
  $.getParamJquery = function(name, url) {
      if (!url) {
       url = window.location.href;
      }
      var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(url);
      if (!results) { 
          return undefined;
      }
      return results[1] || undefined;
  }
  
});

Step 3: Use getParamJquery function to get the query String values. See below:
jQuery(document).ready(function(){
  console.log($.getParamJquery('id'));   
  console.log($.getParamJquery('c'));
}