Showing posts with label Javascript Interview Questions and Answers. Show all posts
Showing posts with label Javascript Interview Questions and Answers. Show all posts

Sunday, 29 March 2020

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:






Question: What is the most efficient way to deep clone an object in JavaScript?
const a = {
  string: 'string',
  number: 123,
  bool: false,
  nul: null,
  date: new Date(), 
}
console.log(a);
console.log(typeof a.date);  // Date object
const clone = JSON.parse(JSON.stringify(a));
console.log(clone);




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 }



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



Monday, 6 June 2016

Core JavaScript Interview Questions

Core JavaScript Interview Questions

Question: How to call a function after page load?
window.onload = function() {
    consol.log('Page loaded successfully');
};



Question: How to detect a mobile device in JavaScript?
var isMobile = false; 
if( /Android|webOS|iPhone|iPod|iPad|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
    isMobile=true;
}

if(isMobile){
    /** Write here code **/

    /** Write here code **/
}



Question: How to get all elements in having same class in JavaScript?
var element = document.getElementsByClassName("className");
for (index = element.length - 1; index >= 0; index--) {
    /** 
    Write your code here
    **/
}



Question: How to add a class to a given element?
var element = document.getElementById("myDivId");
d.className += " anotherClass";  //It will add anotherClass to the #myDivId



Question: How to update a class to a given element?
var element = document.getElementById("myDivId");
d.className = " anotherClass";  //anotherClass will added



Question: How to DELETE a class to a given element?
var element = document.getElementById("myDivId");
d.className = '';  //All exist class will be removed



Question: How to get element object by tag name?
var element = document.getElementsByTagName("h2");



Question: How do I remove a property from a JavaScript object?
var myJSONObject = {"Key1": "value1", "Key2": "value2", "Key3": "value3"};
delete myJSONObject.two;
console.log(myJSONObject); /* Object { Key1="value1",  Key2="value2",  Key3="value3"}*/



Question: How do I add a property from a JavaScript object?
var myJSONObject = {"Key1": "value1", "Key2": "value2", "Key3": "value3"};
myJSONObject.Key4='value4';
console.log(myJSONObject); /* Object { Key1="value1",  Key2="value2",  Key3="value3",  Key4="value4" }*/



Question: How do I update a property from a JavaScript object?
var myJSONObject = {"Key1": "value1", "Key2": "value2", "Key3": "value3", "Key4": "value4"};
myJSONObject.Key4='444444444444';
console.log(myJSONObject); /* Object { Key1="value1",  Key2="value2",  Key3="value3",  Key4="444444444444"}*/



Question: How do I count the size of object?
var myJSONObject = {"Key1": "value1", "Key2": "value2", "Key3": "value3"};
Object.keys(myJSONObject).length; //3



Question: How can I remove a specific item from an array?
Find the index of the array element you want to remove using indexOf, and then remove that index with splice.

const array = [2, 5, 9];
const index = array.indexOf(5);
if (index > -1) {
  array.splice(index, 1);
}
// array = [2, 9]
console.log(array); 




Wednesday, 25 May 2016

JavaScript Interview Questions and Answers for Experienced 2016

JavaScript Interview Questions and Answers for Experienced 2016

Question: How to Get class name using jQuery?
className = $('#IdWhichClassNameWantToGet').attr('class');



Question: How to check a div having class name or Not?
className = $('#IdWhichClassNameWantToCheck').hasClass('hasClass');



Question: How to add a focus on inputbox?
className = $('input#inputBoxId').focus();



Question: How to add X number of days in date?
var dateObject = new Date();
dateObject.setDate(dateObject.getDate()+5); //Add 5 Days



Question: How to add X number of minutes in date?
var dateObject = new Date();
dateObject.setDate(dateObject.getTime()+(30 * 60 * 1000)); //Add 30 Minutes



Question: How to delete an element from Associate Array?
var myArray = new Object();
myArray["firstname"] = "Arun";
myArray["lastname"] = "Kumar";
myArray["age"] = "26";
console.log(myArray); /* Object { firstname="Arun",  lastname="Kumar",  age="26"} */
delete myArray["age"];//Delete an Element
console.log(myArray); /*  Object { firstname="Arun",  lastname="Kumar"} */
Question: How to exit from for loop from JS?
Use return true to exit from loop. For Example:
for (i = 0; i < 5; i++) { 
    if(i>2){
        break;
    }    
}



Question: How to load a noimage.gif, If there we are unable to load images?
Use return true to exit from loop. For Example:
<img onerror="this.onerror=null;this.src=&#39;/images/noimage.gif&#39;;" src="/images/actualimage.jpg" />



Question: How to change the image source with jQuery?
Use return true to exit from loop. For Example:
$("#imageElement").attr("src","/folder/image.jpg");



Question: How to get image Height & Width?
var img = document.getElementById('imageId'); 
var width = img.clientWidth; //this is image width
var height = img.clientHeight; //this is image height



Question: How to Format a number with exactly two decimals in JavaScript?
Use return true to exit from loop. For Example:
var num = 6.42003;
alert(num.toFixed(2)); // "6.42"



Question: How to prevent buttons from submitting forms?
Use return true to exit from loop. For Example:
<form method="post" onsubmit="return saveDatainDb()">
First name:  <input name="firstname" type="text" /><br />
Last name:<br />
<input name="lastname" type="text" />

<input name="submit" type="submit" value="Save Data" />

</form>
<script>
function saveDatainDb(){
    /** Validate , if not valid return false**/
    validation_false=true;
    If(validation_false){
        return false;
    }
    /** Validate , if not valid return false**/


    /** Write here code for AJax call**/
 
    /** Write here code for AJax call**/


}
</script>