0% found this document useful (0 votes)
104 views19 pages

UI Dev Int Quest

Widget is a generic term for the part of a GUI that allows the user to interface with an application or operating system. Typical widgets include buttons, dialog boxes, menus, icons, and progress indicators. The term widget refers to either the graphic component or its controlling program, or the combination of both. New HTML5 elements like <header>, <footer>, <article>, and <section> were introduced to provide more semantic structure. New form controls, graphics elements, and multimedia elements were also added. HTML and CSS allow for creating and styling web pages, with HTML providing structure and CSS controlling formatting and layout.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
104 views19 pages

UI Dev Int Quest

Widget is a generic term for the part of a GUI that allows the user to interface with an application or operating system. Typical widgets include buttons, dialog boxes, menus, icons, and progress indicators. The term widget refers to either the graphic component or its controlling program, or the combination of both. New HTML5 elements like <header>, <footer>, <article>, and <section> were introduced to provide more semantic structure. New form controls, graphics elements, and multimedia elements were also added. HTML and CSS allow for creating and styling web pages, with HTML providing structure and CSS controlling formatting and layout.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

Widget is a generic term for the part of a GUI that allows the user to interface with the application

and operating system. Widgets


display information and invite the user to act in a number of ways. Typical widgets include buttons, dialog boxes, pop-up windows,
pull-down menus, icons, scroll bars, resizable window edges, progress indicators, selection boxes, windows, tear-off menus, menu
bars, toggle switches and forms. The term widget is used to refer to either the graphic component or its controlling program or to
refer to the combination of both.

HTML is the standard text formatting language used for creating and displaying pages on the Web.

New HTML5 Elements


The most interesting new elements are: New semantic elements like <header>, <footer>, <article>, and <section>.
New form control attributes like number, date, time, calendar, search, datalist and range.
New graphic elements: <svg> and <canvas>. New multimedia elements: <audio> and <video>.
The most interesting new API's are: HTML Geolocation, HTML Drag and Drop, HTML Local Storage, HTML Application Cache, HTML
Web Workers, HTML SSE

The <header> element is used to contain introductory and navigational information about a section of the page. This can include the
section heading, the author’s name, time and date of publication, table of contents, or other navigational information.

The <article> element is meant to house a self-contained composition that can logically be independently recreated outside of the
page without losing its meaning. Individual blog posts or news stories are good examples.

The <section> element is a flexible container for holding content that shares a common informational theme or purpose.

The <footer> element is used to hold information that should appear at the end of a section of content and contain additional
information about the section. Author’s name, copyright information, and related links are typical examples of such content.

A block-level element always starts on a new line and takes up the full width available. An inline element does not start on a new
line and only takes up as much width as necessary & allows other html elements next to it.

Block & Inline-block: A block element has some whitespace above & below it and does not allow any html elements next to it. A
inline-block element is placed as an inline element (on the same line as adjacent content), but it behaves as a block element

Trigger email in html: <a href="mailto:[email protected]?Subject=Hello%20again" target="_blank">Send Mail</a>


In form, <form action=mailto:[email protected]>

HTML DOM Table cells: alert(document.getElementById("myTable").rows[0].cells[0].innerHTML);

Advantages of HTML5 & CSS3:


 The first benefit you get is that the readable codes are semantically accurate
 Offline browsing
 Audio and video effects are tagged and viewed without the support of third party plug-ins
 Allow you to handle graphics and photos efficiently
 Have full control over the colors in the templates
 Platform Independence

CSS3 features: CSS3 has been split into "modules". It contains the "old CSS specification" (which has been split into smaller pieces).
In addition, new modules are added:
Selectors, Box Model, Backgrounds and Borders, Image Values and Replaced Content, Text Effects, 2D/3D Transformations,
Animations, Multiple Column Layout, User Interface
Other major changes/additions include
New Combinator, New CSS Selectors, New Pseudo-elements, New Style properties
The CSS box model is a rectangular layout paradigm for HTML elements. It is essentially a box that wraps around every HTML
element. It consists of: margins, borders, padding, and the actual content. It provides a structured way to space elements in
relationship to each other.
 Content - The content of the box, where text and images appear
 Padding - A transparent area surrounding the content (i.e., the amount of space between the border & content)
 Border - A border surrounding the padding (if any) and content
 Margin - A transparent area surrounding the border (i.e., the amount of space between the border & any neighboring
elements)
/* top right bottom left */ /* top/bottom padding 25px; right/left padding 50px */
padding: 25px 50px 75px 100px; padding: 25px 50px;

/* same padding on all 4 sides: */ /* top padding 25px; right/left padding 50px; bottom
padding: 25px; padding 75px */
padding: 25px 50px 75px;

1. div, p - Selects all <div> elements and all <p> 4. div + p - Selects all <p> elements that are placed
elements immediately after a <div> element
2. div p - Selects all <p> elements that are anywhere 5. div ~ p - Selects all <p> elements that are anywhere
inside a <div> element preceded by a <div> element
3. div > p - Selects all <p> elements where the
immediate parent is a <div> element
CSS3 border-radius: border-top-left-radius,border-top-right-radius, border-bottom-right-radius and border-bottom-left-radius
Four values - border-radius: 15px 50px 30px 5px; Three values - first value applies to top-left, second value applies to top-right and
bottom-left, and third value applies to bottom-right; Two values - first value applies to top-left and bottom-right corner, and the
second value applies to top-right and bottom-left corner

CSS3 Background: Allows multiple backgrounds. background-size property has contain (image covers content box) and cover(image
covers the border box) values. background-clip property has padding-box (background is clipped to fill till padding box) & content-
box (background is clipped to fill content box) values

An RGBA color value is specified with: rgba(red, green, blue, alpha). The alpha parameter is a number between 0.0 (fully
transparent) and 1.0 (fully opaque). HSL stands for Hue, Saturation and Lightness hsl(0, 100%, 50%); hsla(0, 100%, 30%, 0.3);
1. Hue is a degree on the color wheel (from 0 to 360): 0 (or 360) is red, 120 is green, 240 is blue
2. Saturation is a percentage value: 100% is the full color.
3. Lightness is also a percentage; 0% is dark (black) and 100% is white.

CSS3 gradients let you display smooth transitions between two or more specified colors. Linear, radial, repeating-linear, repeating-
radial.
background: -moz-linear-gradient(red, yellow); /* For Firefox 3.6 to 15 */
background: linear-gradient(red, yellow); /* Standard syntax */

text-shadow: 2px 2px 4px #000000; box-shadow: 1px 2px 4px rgba(0, 0, 0, .5); values: horizontal shadow, vertical, blur effect, color

CSS3 Text: text-overflow has clip (crops the overflowed text) & ellipsis values (add … for overflow). Word-wrap has break-work
value. word-break has keep-all (line will break at hyphens) & break-all (lines will break at any character) values

CSS3 Font: Allows to define our "own" fonts are defined within the CSS3 @font-face rule.
@font-face {
font-family: myFirstFont;
src: url(sansation_light.woff);
}
CSS3 UI: resize (specifies whether or not an element should be resizable by the user) property & outline-offset (line drawn around
elements, outside the border edge)
The CSS3 box-sizing property allows us to include the padding and border in an element's total width and height. When you set the
width/height of an element, the element often appear bigger than you have set (because the element's border and padding are
added to the element's specified width/height). This can be overcome using box-sizing.
CSS3 flex property specifies the length of the item, relative to the rest of the flexible items inside the same flexible container.

border-image: url(border.png) 20% round; border-image: url(border.png) 30 stretch; (repeat or stretch the image as border)

CSS Border: shorthand property is border: width style color radius;


border can be applied to border-right, left, top & bottom. radius property is used to add rounded borders to an element

CSS Background: shorthand property: background: color url repeat position;

Color Code - Black: #000000 or rgb(0,0,0) White: #ffffff or rgb(255,255,255)

CSS preprocessor: A scripting language that extends CSS by allowing developers to write code in one language and then compile it
into CSS. Some examples of CSS preprocessor include: Sass (Syntactically Awesome StyleSheets), LESS and Stylus. The main
difference between LESS and Sass is the way in which they are processed. LESS is a JavaScript library and is, therefore, processed
client-side. Sass, on the other hand, runs on Ruby and is processed server-side.
Adv: nested syntax, Mathematical functions, Joining of multiple files, Ability to define variables (@col-red: #f00;), write less & code
more.

CSS
body {
.header { LESS/SASS
h1 { body .header h1 {
font-size: 28px; font-size: 28px;
} }
h2 { body .header h2 {
font-size: 21px; font-size: 21px;
} }
}
reset.css is used to normalize browser's default styles (remove browser built-in styles).

In CSS, selectors are patterns used to select the element(s) you want to style.
 type selectors—matching a specific element
 class selectors—matching elements with a specific class
 ID selectors—matching the element with a specific ID
 child selectors—matching elements that are a child of the specific element
 universal selectors—matching any element(using *)
 adjacent sibling selectors—matching elements immediately preceded by a specific element
 attribute selectors—matching elements with a specific attribute or attribute value
 pseudo-class selectors—matching elements with a specific pseudo class
 pseudo-element selectors—matching elements with specific pseudo-element properties
Property Description

Specifies on which sides of an element where floating elements are not allowed to float. It controls the behavior of
clear
floating elements

float Specifies whether or not an element should float


overflow Specifies what happens if content overflows an element's box

A CSS pseudo-element is used to style specified parts of an element: ::first-line, ::first-letter

The ::after selector inserts something after the content of each selected element(s). Use the content property to specify the content
to insert. Use the ::before selector to insert something before the content.
p::after {
content: " - Remember this";
}

The z-index property specifies the stack order of an element. The z-index property in CSS controls the vertical stacking order of
elements that overlap. An element with greater stack order is always in front of an element with a lower stack order. It works on
positioned elements (position:absolute, position:relative, or position:fixed). z-index: auto|number|initial|inherit;

svg defines the graphics in xml format. svg images are scalable, zoomable, can be printed with high quality at any resolution. Canvas
draws 2D graphics, on the fly (with a js)

The purpose of responsive design is to have one site, but with different elements that respond differently when viewed on devices
of different sizes. Responsive web design (RWD) is an approach to web design aimed at allowing desktop webpages to be viewed in
response to the size of the device one is viewing with.

Bootstrap: Popular framework which uses HTML, CSS and jQuery to make responsive, mobile-first web sites. Other frameworks are
foundation, skeleton, zebra. Bootstrap (free) is the most popular HTML, CSS, and JavaScript framework for developing responsive,
mobile-first web sites

Without framework: Meta Tag - The viewport (user's visible area of a web page) tag below tells the browser to use the device width
as the viewport width and disable the initial scale. Grid-View- page is divided into columns which makes it easier to place elements
on the page. A responsive grid-view often has 12 columns, and has a total width of 100% (divide it to menu, main, sidebar, etc in %),
and will shrink and expand as you resize the browser window. Media Queries - CSS3 media query is the trick for responsive design. It
is like writing if conditions to tell the browser how to render the page for specified viewport width. Media query is a CSS technique
introduced in CSS3. It uses the @media rule to include a block of CSS properties only if a certain condition is true.

<meta name="viewport" content="width=device-width, initial-scale=1.0">

Include padding and border in the total width and height of *{


the elements box-sizing: border-box;
}
@media only screen and (max-width: 500px) {
body {
background-color: lightblue;}}

Namespacing is a technique employed to avoid collisions with other objects or variables in the global namespace. They're also
extremely useful for helping organize blocks of functionality in your application into easily manageable groups that can be uniquely
identified.

The CSS display property specifies the type of box used for an HTML element. Values: inline,block,none,inherit,initial….
p.inline { p.inline { p.inline {
display: inline; display: block; display: none;
} } }

CSS Position property


Static: Default value. Elements render in order, as they appear in the document flow
Absolute: The element is positioned relative to the nearest positioned ancestor
Fixed: The element is positioned relative to the browser window
Relative: The element is positioned relative to its original/normal position, so "left: 20" adds 20 pixels to the element's LEFT position
Inherit: The value of the position property is inherited from the parent element
Initial: Sets this property to its default value

Overflow: visible (default-overflow is visible), hidden - The overflow is clipped, and the rest of the content will be invisible
scroll - The overflow is clipped, but a scrollbar is added to see the rest of the content, auto - If overflow is clipped, a scrollbar should
be added to see the rest of the content
Inline-block: Used to create a grid of boxes that fills the browser width and wraps nicely

A combinator is something that explains the relationship between the selectors.


 descendant selector (space)
 child selector (>)
 adjacent sibling selector (+)
 general sibling selector (~)

Align properties: To horizontally center a block element (like <div>), use margin: auto; vertically center use padding
Left and Right Align use position: absolute; or use float property. Align to center of the screen:
#div{ width: 100px; height: 100px; position: absolute; top:0; bottom: 0; left: 0; right: 0; margin: auto;}

The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to
dynamically access and update the content, structure, and style of a document. In the DOM, all HTML elements are defined as
objects. The Document Object Model (DOM) is a programming API for HTML and XML documents. It defines the logical structure of
documents and the way a document is accessed and manipulated.

How to Convert from HTML to XHTML


1. Add an XHTML <!DOCTYPE> to the first line of every page
2. Add an xmlns attribute to the html element of every page
3. Change all element names to lowercase
4. Close all empty elements
5. Change all attribute names to lowercase
6. Quote all attribute values

HTML vs XHTML

Document Structure  <html>, <head>, <title>, and  XHTML elements must be


 XHTML DOCTYPE is <body> are mandatory properly nested
mandatory  XHTML elements must
 The xmlns attribute in always be closed
<html> is mandatory XHTML Elements  XHTML elements must be in
lowercase
 XHTML documents must  Attribute names must be in  Attribute minimization is
have one root element lower case forbidden
 Attribute values must be
XHTML Attributes quoted
XML (Extensible Markup language): It is designed to store & transport data. It is bothy human & machine readable. It does not use
predefined tags.

The <!DOCTYPE> declaration must be the very first thing in your HTML document, before the <html> tag. It is not an HTML tag; it is
an instruction to the web browser about what version of HTML the page is written in. In HTML 4.01, the <!DOCTYPE> declaration
refers to a DTD (references to a DTD in the form of a URL), because HTML 4.01 was based on SGML(Standard Generalized Markup
Language). The DTD specifies the rules for the markup language, so that the browsers render the content correctly. HTML5 is not
based on SGML, and therefore does not require a reference to a DTD.

HTML5 - <!DOCTYPE html>

HTML4 - <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

HTML5 introduces application cache, which means that a web application is cached, and accessible without an internet connection.

Application cache gives an application three advantages:


1. Offline browsing - users can use the application when they're offline
2. Speed - cached resources load faster
3. Reduced server load - the browser will only download updated/changed resources from the server
<!DOCTYPE HTML> <html manifest="demo.appcache"> ... </html>

Synchronous: A synchronous request blocks the client until operation completes. In such case, javascript engine of the browser is
blocked. Asynchronous An asynchronous request doesn’t block the client i.e. browser is responsive. At that time, user can perform
another operation also. In such case, javascript engine of the browser is not blocked. Most functions in Javascript are synchronous.
To make functions execute asynchronously use callbacks and timeouts (setInterval, setTimeout, Worker, animation in jQuery -
uses setInterval)

TypeScript is a free and open source programming language developed and maintained by Microsoft. TypeScript is a superset of
JavaScript which primarily provides optional static typing, classes and interfaces. One of the big benefits is to enable IDEs to provide
a richer environment for spotting common errors as you type the code.

React is a open source JavaScript library for creating user interfaces by Facebook and Instagram. Many people choose to think of
React as the V in MVC.

JavaScript (It is Multi-paradigm: scripting, object-oriented (prototype-based), imperative, functional) is the programming language
of HTML and the Web which programs the behavior of web pages. Other names for JS are ECMAScript or LiveScript.

JS doesn’t support overloading as it is weakly typed lang. However it supports overriding, so if you define two functions with the
same name, the last one defined will override the previously defined function.

In computer science, functional programming is a programming paradigm—a style of building the structure and elements of
computer programs—that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable
data.

Diff b/w object & constructor: Object holds instance of a class. Constructor initializes the Object while creation

Design patterns in js: Prototypal, singleton

How to extended built in objects: String.prototype.reverse : reverse is extended method


Why extending array is bad
When you extend an object, you change its behavior. Changing the behavior of an object that will only be used by your own code is
fine. But when you change the behavior of something that is also used by other code there is a risk you will break that other code.

1)for..in might not work properly


2)Someone else might also want to extend Array with the same function name
3)It might not work properly in every browser, even with the shim.

Browser Detection: The window.navigator object contains information about the visitor's browser. navigator.appName &
navigator.appCodeName returns name of the browser, navigator.platform returns platform name. navigator.product – engine name,
navigator.appVersion, navigator.language

IE11, Chrome, Firefox, and Safari return appName "Netscape". Chrome, Firefox, IE, Safari, and Opera all return appCodeName
"Mozilla".

3 types of errors in JS: Loadtime error/syntax errors, Runtime (misuse of commands or calling a non-existing method), Logical errors:
occurs due to bad logic & cannot be caught as the logic depends on business requirement. Loadtime & runtime Exceptions can be
caught using try…catch…finally statements

The onerror() method: The onerror event handler was the first feature to facilitate error handling in JavaScript. The error event is
fired on the window object whenever an unhandled exception occurs on the page(exception which is not handled by try catch). It
provides 3pieces of info:
 Error message − The same message that the browser would display for the given error
 URL − The file in which the error occurred
 Line number− The line number in the given URL that caused the error

window.onerror = function () { window.onerror = function (msg, url, line) {


alert("An error occurred."); alert("Message : " + msg );
} alert("url : " + url );
alert("Line number : " + line );
}
Reading value from Javascript Prompt & Confirm pop up:
Var txt = prompt(“sometext”, “defaultText”);
Var r = confirm(“Press a button”);
If(r==true)
alert(“You pressed OK!”);
else
alert(“You pressed Cancel!”);

jQuery: The purpose of jQuery is to make it much easier to use JavaScript on your website. It simplifies HTML/DOM
manipulation,CSS manipulation,HTML event methods,Effects and animations,AJAX & Utilities. jQuery pages load faster. jQuery
elements display even when JavaScript is disabled

Ajax is a client-side script that communicates to and from a server/database without the need for a postback or a complete page
refresh. The best definition I've read for Ajax is “the method of exchanging data with a server, and updating parts of a web page -
without reloading the entire page

When executing scripts in an HTML page, the page becomes unresponsive until the script is finished. A web worker is a JavaScript
that runs in the background, independently of other scripts, without affecting the performance of the page. You can continue to do
whatever you want: clicking, selecting things, etc., while the web worker runs in the background. Web workers at long last bring
multi-threading to JavaScript.
The event.preventDefault() jQuery method stops the default action of an element from happening (Prevent a submit button from
submitting a form or Prevent a link from following the URL).

The event.stopPropagation() stops the click event from bubbling to the parent elements.

Append() jQuery method inserts specified content at the end of the selected element. Prepend() inserts at beginning. appendTo()
inserts HTML elements at the end of selected elements. $("p").append("<b>Appended text</b>")
$("<span>Hello World!</span>").appendTo("p")

jQuery selectors

#id $("#lastname") The element with id="lastname"

.class $(".intro") All elements with class="intro"

.class,.class $(".intro,.demo") All elements with the class "intro" or "demo"

element $("p") All <p> elements

Select id starts vt $("[id^='txtTitle']"), Ends vt $("[id$='txtTitle']") &


Contains $("[id*='txtTitle']"

noConflict() – allows to include 2 versions of jquery files or include other JS frameworks in one document. It releases the hold on the
$ shortcut identifier, so that other JS frameworks can use it

jQuery UI is a jQuery library built on top of jQuery which provides set of user interface interactions, effects, widgets, and themes.

jQuery Methods: ready()-Specifies a function to execute when the DOM is fully loaded, blur() -Attaches/Triggers the blur event,
change() - Attaches/Triggers the change event, click() - Attaches/Triggers the click event,
dblclick(),focus(),mouseup(),mousedown(),mouseover()

jQuery Chaining allows us to run multiple jQuery methods (on the same element) within a single statement. In this way browsers do
not have to find the same element(s) more than once.
$("#p1").css("color", "red").slideUp(2000).slideDown(2000);

remove() - Removes the selected element (and its child elements). Use to remove the elements and its data and events
empty() - Removes the child elements from the selected element. Use to remove only the content from the selected elements
detach() method removes the selected elements, including all text and child nodes. However, it keeps data and events.
animate() - This method changes an element from one state to another with CSS styles. Only numeric values can be animated (like
"margin:30px")

$(document).ready(function(){
$("button").click(function(){
var div = $("div");
div.animate({left: '100px'}, "slow");
div.animate({fontSize: '3em'}, "slow");
});
});
The prop() method sets or returns properties and values of the selected elements.
Disable form element: $("input").prop('disabled', true);
Event handling: It varies browser vise .addEventListener in mozilla, .attachEvent In IE. Cross-browser event handling is done using
jQuery.

.bind() attaches events to elements that exist or match the selector at the time the call is made, and specifies a function to run
when the event occurs. Any elements created afterwards or that match going forward because the class was changed, will not fire
the bound event. The basic difference between bind and live is bind will not attach the event handler to those elements which are
added/appended after DOM is loaded. bind() only attach events to the current elements not future element.

<script> $("p").bind("click", function(){


$(document).ready(function(){ $( "<p>This is a click Event</p>").appendTo( "body" );
$("p").bind("click", function(){ });
alert("The paragraph was clicked."); $("p").bind("dblclick", function(){
}); $( "<p>This is a double-
}); click Event</p>" ).appendTo( "body" );
</script> });
//adding click & double click event to same element

.live() works for existing and future matching elements.

The delegate() method is quite similar to live() but in this you can control on which node the events will be added. The delegate()
method attaches one or more event handlers for specified elements that are children of selected elements, and specifies a function
to run when the events occur. $(selector).delegate(childSelector,event,data,function)

All the above three jQuery functions are used to attach events to selectors or elements.

The on() method attaches one or more event handlers for the selected elements and child elements.

closest()

 Begins with the current element


 Travels up the DOM tree and returns the first (single) ancestor that matches the passed expression
 The returned jQuery object contains zero or one element
parents()

 Begins with the parent element


 Travels up the DOM tree and returns all ancestors that matches the passed expression
 The returned jQuery object contains zero or more than one element

$._data( $('.element')[0], 'events' ); // display all the events that are currently assigned to the element.

With local storage, web applications can store data locally within the user's browser. Before HTML5, application data had to be
stored in cookies, included in every server request. With local storage, web applications can store data locally within the user's
browser. Local storage is more secure, and large amounts of data can be stored locally, without affecting website performance.
Unlike cookies, the storage limit is far larger (at least 5MB) and information is never transferred to the server. Local storage is per
domain. All pages, from one domain, can store and access the same data.
HTML local storage provides two objects for storing data on the client:
window.localStorage - stores data with no expiration date
window.sessionStorage - stores data for one session (data is lost when the tab is closed)
Local storage object: The local Storage object stores the data with no expiration date. The data will not be deleted when the browser
is closed, and will be available the next day, week, or year.

Localstorage: To update an existing item we should rewrite the item. That is set the item again with a new value
localStorage.setItem("lastname", "Smith"); // Store
document.getElementById("result").innerHTML = localStorage.getItem("lastname"); // Retrieve
localStorage.removeItem("lastname"); // Remove

In Javascript, if you try to use a variable that doesn't exist and has not been declared, not defined error is thrown. When we try to
use a variable which is declared but not defined, undefined error is thrown

JavaScript does not support arrays with named indexes (Associative arrays). Arrays always use numbered indexes.

Hoisting is JavaScript's default behavior of moving all declarations to the top of the current scope (to the top of the current script or
the current function). JavaScript only hoists declarations, not initializations. A variable can be used before it is declared.
x = 5; // Assign 5 to x
elem = document.getElementById("demo"); // Find an element
elem.innerHTML = x; // Display x in the element O/p is 5
var x; // Declare x

A closure is an inner function that has access to the outer (enclosing) function’s variables (the parent scope) even after the parent
function has closed/returns. The closure has three scope chains: it has access to its own scope (variables defined between its curly
brackets), it has access to the outer function’s variables including the parameters, and it has access to the global variables. It makes
it possible for a function to have "private" variables. In JavaScript, Global and local variables with the same name are different
variables. Modifying one does not modify the other. Encapsulation is achieved in js using closure

Ex: <script>
function celebrityName(firstName) {
var nameIntro="This celebrity is: ";
function lastName(theLastName){
return nameIntro + firstName + " " + theLastName;
}
return lastName;
}
var mjName = celebrityName ("Michael"); //outer func returns
function myFunction(){
document.getElementById("demo").innerHTML = mjName("Jackson");
}
</script>

<input type="button" value="Click Me" onclick="alert(incrementCount())"></input>


<script>
var incrementCount=(function(){ // outer function executes only once
var count=0;
return function(){
return ++count;
}
}
)();

The eval() function evaluates or executes an argument. var b = eval("2 + 2");

The param() method creates a serialized representation of an array or an object. The serialized values can be used in the URL query
string when making an AJAX request.

<script>
$(document).ready(function(){
personObj = new Object();
personObj.firstname = "John";
personObj.lastname = "Doe";
personObj.age = 50;
personObj.eyecolor = "blue";
$("button").click(function(){
$("div").text($.param(personObj));
});
});
</script>
Output: firstname=John&lastname=Doe&age=50&eyecolor=blue

The object is a collection of named value. The named values are called. The object can contain any data types (numbers, arrays,
object etc.). In JavaScript, all values, except primitive values (Undefined, Null, Boolean, Number, or String), are objects. Objects are
mutable: They are addressed by reference, not by value. Javascript variables are not mutable.
The example as given: Var myObject= {empId: “001”, empCode:”X0091”}; empId & empCode are properties

Every JavaScript object has a prototype. The prototype is also an object. All JavaScript objects inherit the properties and methods
from their prototype. Objects created using an object literal, or with new Object(), inherit from a prototype called Object.prototype.
Objects created with new Date() inherit the Date.prototype. The Object.prototype is on the top of the prototype chain.

You cannot add a new property to a prototype the same way as you add a new property to an existing object, because the prototype
is not an existing object. The JavaScript prototype property allows you to add new properties & new methods to an existing
prototype.

function Person(first, last, age, eyecolor) { // constructor


this.firstName = first;
this.lastName = last;
this.age = age;
}
Person.prototype.nationality = "English";
Person.prototype.name = function() {
return this.firstName + " " + this.lastName;
};

var myMother = new Person("Sally", "Rally", 48);

In addition to creating objects using a constructor function, you can create objects using an object initializer. Using object initializers
is sometimes referred to as creating objects with literal notation.

There are different ways to create new objects:


 Define and create a single object, using an object literal. Objects created using literals are singleton & can be accessed
without creating instances. Any change made to the object affects that object across the entire script.
Using an object literal, you both define and create an object in one statement. An object literal is a list of name:value pairs
(like age:50) inside curly braces {}.
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
var man= person; man.firstName=”Jack”; //this changes the firstName of person object as well

 Define and create a single object, with the keyword new.


var person = new Object();
person.firstName = "John";
 Define an object constructor, and then create objects of the constructed type. Objects created with a function constructor
lets us to have multiple instances of that object. Any changes made to one instance will not affect other instances.
function person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
var myFather = new person("John", "Doe", 50, "blue");

Conclusion: If you need multiple instances of the object then use constructor function whereas if you need just one instance of the
object then use literal.

The this Keyword: In JavaScript, the thing called this, is the object that "owns" the JavaScript code. The value of this, when used in a
function, is the object that "owns" the function. The value of this, when used in an object, is the object itself. The this keyword in an
object constructor does not have a value. It is only a substitute for the new object. The value of this will become the new object
when the constructor is used to create an object. "self" is a pattern to maintaining a reference to the original "this" keyword.
var self = this.

Right now, "self" should not be use because modern browsers provide a "self" as global variable (window.self).

JS Array Methods:
The slice() method returns the selected elements in an array, as a new array object. It does not remove any elements from the
source array. array.slice(start,end)

You can use splice() to remove elements without leaving "holes"(undefined value) in the array. array.splice(p,n); p: position where
new elements should be added, how many elements should be removed

var fruits = ["Banana", "Orange", "Apple", "Mango"];


fruits.splice(2, 0, "Lemon", "Kiwi"); //add

fruits.splice(0, 1); //remove

The join() method joins all array elements into a string. toString() method converts an array to a string of (comma separated) array
values. valueOf() can also be used.

var fruits = ["Banana", "Orange", "Apple", "Mango"];


alert(fruits.toString()); //output: alert(fruits.join(“ * “)); //output: Banana * Orange * Apple *
Banana,Orange,Apple,Mango Mango

JS String Methods: concat(), indexOf() [str.indexOf("string")], lastIndexOf(), search(), slice(), substr() [it is similar to slice()],
replace(), toLowerCase(), charAt()[returns the character at a specified index], charCodeAt() [returns the unicode of the character at
a specified index], split() [converts a string to an array]

Call() & apply(): Javascript method to invoke a function. Both methods take an owner object as the first argument. The only
difference is that call() takes the function arguments separately, and apply() takes the function arguments in an array.

Function myFunction(a,b){ myObject = myFunction.call(myObject,10,2); // O/p is 20


return a*b; myArray = [10,2];
} myObject1 = myFunction(myObject1,myArray); // O/p is 20
Inheritance in JS is achieved by:
1. The prototypal pattern of prototypal inheritance.
2. The constructor pattern of prototypal inheritance (pseudo classical inheritance). (refer example in object creation)

var dog={legs:4;}
var beagle =Object.create(dog);
dog’ is the prototype for ‘beagle’. Any properties defined in dog, such as number of legs, will be inherited by Spot the dog.
Adv of Prototypal inheritance (objects inherit from objects) over Classical Inheritance (classes inherit from classes): Prototypal
Inheritance is Simple, powerful, Less Redundant, Dynamic. Dynamic because can add new properties to prototypes after they are
created. This allows you to add new methods to a prototype which will be automatically made available to all the objects which
delegate to that prototype.

Prototype chaining is used to build new types of objects based on existing ones. It has a very similar job to inheritance in a class
based language.
Constructor functions have a property called prototype. Adding properties and methods to the prototype property will automatically
add the method or property to all objects created by the constructor function.
Prototype chaining is an extension of this idea. The prototype property is just a regular javascript object so it’s possible to create a
function’s prototype using another constructor function. When you do this, all of the properties and methods from the constructor
function’s prototype are automatically added to new the prototype object.

Using Asynchronous code, we are able to execute multiple things/JavaScript call at the same-time without locking the DOM or main
thread.

Javascript Parameter Rules


JavaScript function definitions do not specify data types for parameters. JavaScript functions do not perform type checking on the
passed arguments. JavaScript functions do not check the number of arguments received.

JavaScript functions have a built-in object called the arguments object.


The argument object contains an array of the arguments used when the function was called (invoked). If a function is called with too
many arguments (more than declared), these arguments can be reached using the arguments object.

Private, Public & Static variables


1. function Class() {
2. var privateVar = "I am private!"; // private variable
3. this.publicVar = "I am public!"; // public variable
4. this.publicMethod = function(){
5. return privateVar;
6. }
7. }
8. Class.staticVar = “I am static”; //static variable

Promise represents the eventual result of an asynchronous operation. It provides handler for success & failure of an asynchronous
operation

Difference between pageLoad, onload& $(document).ready() The readyevent occurs after the HTML document has been loaded,
while the onload event occurs later, when all content (e.g. images) also has been loaded. The onload event is a standard event in the
DOM, while the readyevent is specific to jQuery.

JavaScript Best Practices: Avoid Global Variables, Always Declare Local Variables, Declarations on Top, Initialize Variables, Use ===
Comparison, End Your Switches with Defaults, Comment as Much as Needed but Not More

Post/Redirect/Get (PRG) is a web development design pattern that prevents some duplicate form submissions, creating a more
intuitive interface for user agents (users). When a web form is submitted to a server through an HTTP POST request, a web user that
attempts to refresh the server response in certain user agents can cause the contents of the original HTTP POST request to be
resubmitted, possibly causing undesired results, such as a duplicate web purchase.

Host: store (a website or other data) on a server or other computer so that it can be accessed over the Internet. A
web hosting service is a type of Internet hosting service that allows individuals and organizations to make their website accessible
via the World Wide Web.
WWW: Collection of internet resources (such as FTP, telnet, Usenet), hyperlinked text, audio, and video files, and remote sites that
can be accessed and searched by browsers based on standards such as HTTP and TCP/IP.

Core JavaScript contains a core set of objects, such as Array, Date, and Math, and a core set of language elements such as operators,
control structures, and statements. Core JavaScript can be extended for a variety of purposes by supplementing it with additional
objects; for example: Client-side JavaScript extends the core language by supplying objects to control a browser (Navigator or
another web browser) and its Document Object Model (DOM). For example, client-side extensions allow an application to place
elements on an HTML form and respond to user events such as mouse clicks, form input, and page navigation.
Server-side JavaScript extends the core language by supplying objects relevant to running JavaScript on a server. For example,
server-side extensions allow an application to communicate with a relational database, provide continuity of information from one
invocation to another of the application, or perform file manipulations on a server.

REST stands for Representational State Transfer. It relies on a stateless, client-server, cacheable communications protocol -- and in
virtually all cases, the HTTP protocol is used.
REST(webservice) is an architecture style for designing networked applications. The idea is that, rather than using complex
mechanisms such as CORBA, RPC or SOAP to connect between machines, simple HTTP is used to make calls between machines.
SOAP is a protocol. REST is an architectural style.
SOAP can't use REST because it is a protocol. REST can use SOAP web services because it is a concept and can use any protocol like
HTTP, SOAP.
SOAP uses services interfaces to expose the business logic. REST uses URI to expose business logic.
SOAP defines standards to be strictly followed. REST does not define too much standards like SOAP.
SOAP requires more bandwidth and resource than REST. REST requires less bandwidth and resource than SOAP.
SOAP defines its own security. RESTful web services inherits security measures from the underlying transport.
SOAP permits XML data format only. REST permits different data format such as Plain text, HTML, XML, JSON etc.
SOAP is less preferred than REST. REST more preferred than SOAP.

A content delivery network (CDN) is a system of distributed servers (network) that deliver webpages and other Web content to a
user based on the geographic locations of the user, the origin of the webpage and a content delivery server.

A content delivery network (CDN) is a collection of global servers that caches and delivers content such as images, videos and
Javascript files. When a user requests a web page, for instance, content on that page is delivered by the closest edge server rather
than the origin server, thereby decreasing page load time.

JSON (JavaScript Object Notation) is a minimal, readable format for structuring data. It is used primarily to transmit data between a
server and web application, as an alternative to XML. Diff: It doesn’t use end tag, it is shorter, quicker to read and write & it can use
arrays. XML has to be parsed with an XML parser. JSON can be parsed by a standard JavaScript function. JSON does not support
Comments & namespaces, XML supports both. JSON is better for webservices & XML for configurations

<p id="demo"></p> JSON Array:


<script> var text = '{"employees":[' +
var text = '{"name":"John Johnson","street":"Oslo West '{"firstName":"John","lastName":"Doe" },' +
16","phone":"555 1234567"}'; '{"firstName":"Anna","lastName":"Smith" },' +
var obj = JSON.parse(text); '{"firstName":"Peter","lastName":"Jones" }]}';
document.getElementById("demo").innerHTML = obj = JSON.parse(text);
obj.name + "<br>" + alert(employees[0].firstName + " " +
obj.street + "<br>" + employees[0]["lastName"])
obj.phone;
</script>

Modernizer is a JavaScript library that detects which HTML5 and CSS3 features your visitor's browser supports. In detecting feature
support, it allows developers to test for some of the new technologies and then provide fallbacks for browsers that do not support
them.
When autocomplete is on, the browser automatically complete values based on values that the user has entered before.

How to reduce load time in front-end: Examples of HTTP requests are:


 loading CSS style sheets;
 loading scripts;
 loading images;
 loading HTML.

Browser Caching: Browser caching stores cached versions of static resources. These speeds up page speed tremendously and
reduces server lag.
Compress images: We can do this by using the default image compressor built into Google’s Page Speed plugin.
Scale images: You can scale images in Photoshop by adjusting them to the same pixel dimensions that they will be in your HTML
code & avoid server lag needed to re-size images.
Combine images into CSS sprites: Images can be combined into CSS sprites in order to cut down the number of images loaded on a
given page. CSS sprites are basically one large image that is made up of a number of smaller images. Combining 5 images into one
CSS sprite is a fast way to speed up a website by allowing a browser to load one image instead of 5 images.
Defer (postpone) the parsing of JavaScript: In order to defer parsing of Javascript, it is best to call these scripts at the end of an
HTML document rather than at the beginning.
Minify HTML, CSS, and JavaScript: HTML, CSS, and JavaScript can all be “minified” or compressed to speed up their loading time.
There are a number of resources on the web that minify these types of files, minifier is an excellent example.

How to reduce image size

We can do this by using the default image compressor built into Google’s Page Speed plugin.
You can scale images in Photoshop by adjusting them to the same pixel dimensions that they will be in your HTML code & avoid
server lag needed to re-size images.

How to limit # of HTTP requests to a server? (Reduces load time): A standard web browser limits the number of concurrent HTTP
requests it is processing at the same time. If a page makes more than 50 HTTP requests you should seriously look into lowering the
amount, unless you have a very large page or you host an image gallery or similar. It depends on the type of page you have. Most of
my own websites (which are almost all informational type websites - article pages with a few images) do not have more than 10
HTTP requests per page.
To make fewer HTTP requests

 Combine & inline your CSS scripts: Most website themes today require multiple CSS files (usually in the header or the footer) to
load to support the theme. You should combine these files to one large file to minimize the amount of HTTP requests. It’s as
simple as opening all the files and copy & pasting their content to one file. Set the TITLE attribute taking one and the same value
to the LINK element. An even better option is not using a file for CSS at all, this will help speed up your pages even more. Just
put all the CSS code in <style></style> tags and paste it inside the <header></header> (also called inlining CSS) HTML tags on
your pages. Can use proxy CSS rewriter
 Inline small Javascripts: The best way to treat Javascripts when it comes to page speed is to inline them. This is usually only
advisable to use with smaller Javascripts though.
 Combine all Javascripts: If you can’t inline your Javascripts and your website requires multiple Javascripts to load you should try
and copy and paste all the Javascripts to one big .js file and call this bigger Javascript file in the <header></header> tag. Also,
keep in mind that it’s always a smart idea to minimize the amount of Javascripts for your site. The more Javascripts your site
needs to load, the slower it usually gets. Only load those scripts you really need for your site. Can use proxy JS rewriter
 CSS image sprites: If you really have to use images for your design you can combine all those images to one bigger file by using
CSS sprites. You can then call these images to use in your design by using X and Y coordinates in a CSS script. This way the
browser only has to make one HTTP request for multiple images.
 Limit the amount of social buttons: Using these buttons add multiple HTTP requests, which can slow your website down
significantly.
 Convert images to Base64 code: If you really want to go hardcore you can encode your design images (like your logo) to a
Base64 string, which basically means you transform an image file into code. One you have the code you replace the original
image tag with this code to display your image. This way you make fewer HTTP requests for the server to handle. You can use
the Base64 File Encoder tool for this.
 If your website has too many HTTP requests coming from the same domain (10+ and above) you should create a subdomain and
place some of your files on this subdomain. Subdomains are seen as seperate domains by browsers. Because of this you can
load more files at a time (assuming the browser can handle 6 parallel connections per domain) which will speed up your
website. Don’t overdo it though, you should never use more as 2 subdomains to serve files as that will actually slow down your
website because of too many parallel connections.

What is mem cache Cache memory is a type of memory used to hold frequently used data to speed up dynamic web apps. Cache
memory is relatively small, but very fast. Most web browsers use a cache to load regularly viewed webpages fast.

One use of a memory cache is to speed up common datastore queries. If many requests make the same query with the same
parameters, and changes to the results do not need to appear on the web site right away, the application can cache the results in
the memcache. Subsequent requests can check the memcache, and only perform the datastore query if the results are absent or
expired. Session data, user preferences, and other data returned by queries for web pages are good candidates for caching.

Memcache can be useful for other temporary values. However, when considering whether to store a value solely in the memcache
and not backed by other persistent storage, be sure that your application behaves acceptably when the value is suddenly not
available. Values can expire from the memcache at any time, and can be expired prior to the expiration deadline set for the value.
For example, if the sudden absence of a user's session data would cause the session to malfunction, that data should probably be
stored in the datastore in addition to the memcache.

App Engine supports two levels of the memcache service:


 Shared memcache is the free default for App Engine applications. It provides cache capacity on a best-effort basis and is subject
to the overall demand of all the App Engine applications using the shared memcache service.
 Dedicated memcache provides a fixed cache capacity assigned exclusively to your application. It's billed by the GB-hour of cache
size and requires billing to be enabled. Having control over cache size means your app can perform more predictably and with
fewer reads from more costly durable storage.

Memcache module provides handy procedural and object oriented interface to memcached, highly effective caching daemon, which
was especially designed to decrease database load in dynamic web applications. The Memcache module also provides a session
handler (memcache). Memcached is Free & open source, in-memory key-value store, high-performance, distributed memory object
caching system.

How will update or know if a cache is updated

 Caching Method 1: Last-Modified - One fix is for the server to tell the browser what version of the file it is sending. A
server can return a Last-modified date along with the file.
 Caching Method 2: ETag - ETags solve the problem of comparing file versions. An ETag is a unique identifier given to every
file. It’s like a hash or fingerprint: every file gets a unique fingerprint, and if you change the file (even by one byte), the
fingerprint changes as well.
 Caching Method 3: Expires – Set an expiration date & use it till then. Once it expires, request server for a fresh copy with
new expiration date.
 Caching Method 4: Max-Age - Expires is great, but it has to be computed for every date. The max-age header lets us say
“This file expires 1 week from today”, which is simpler than setting an explicit date.

Web Caching pros & cons

Pros: Cons:
Faster load times May require high technical expertise to configure it just
Less bandwidth usage right
Less stress on the server Will not work for content that is constantly being
updated
Cross browser issue that I faced was while using chosen (auto complete widget) in jQuery. 1 st select field with chosen always had a
width of 0px in IE<9. Fix was to add width: 190px !important; to the respective container class in chosen css.
The reason being, Chosen calculates and assigns the width when the DOM is ready, before that the initial width for the emulated
drop-down is zero. The !important part is because chosen adds an inline style of width: 0; to the element itself and you need to
override the specificity with !important.

Solutions for cross-browser issues or to have browser compatibility:

 Include DOCTYPE: This simple one-line of code can make all the difference between a cleanly rendered website and
a strange rendering. This is especially true for Internet Explorer as it will fall back to its own Quirksmode where it interprets
quite a few web standards entirely different. So if some browsers acts up in any way check your Doctype first!
 CSS Reset: Every browser comes with a different set of internal, basic CSS styles which apply if the current website does not
override them. Browser will render a page differently even if it lacks any CSS styling of their own. To avoid having any side
effects you can use a so called CSS reset style sheet in your page to make sure that every browsers starts rendering with the
same basic set of rules. Ex: Normalise.css, HTML5Reset
 Use browser detection like Modernizer
 DOM: The tree structure is differently formed in IE & Firefox. JQuery help a lot as they hide the implementation differences
from you.
 Use conditional comments instead of CSS hacks. With conditional comments you can link to separate style sheets for
different browsers.
<link type="text/css" href="style.css" />
<!--[If IE]>
<link type="text/css" href="IEHacks.css" />
<![endif]-->
<!--[if !IE]>
<link type="text/css" href="NonIEHacks.css" />
<![endif]-->
 Validate: The W3C Validation Service validates multiple versions of XHTML and HTML, outputting many useful errors and
warnings to help users create a perfect website.
 Testing: Start with firefox and then move to IE. Use Firebug, a firefox addon and IE Developer Toolbar for IE to set layout. To
test website on different browser, there are some online and offline utilities like adobe browserlab, browsershots, IETester,
browsercam.

CSS Hacks: For something in your CSS file to be considered a “hack” it must apply its styles only to the browser(s) being targeted
while all other browsers ignore it. Let’s consider an example. This is a CSS hack:

* html .sidebar {
margin-left: 5px;
}

Support in IE8 or below: Use Respond.js plug-in to support media queries & for canvas use explorecanvas(excanvas.js)

Can you speak about accessibility in web pages: WAI-ARIA, the Accessible Rich Internet Applications Suite, defines a way to make
Web content and Web applications more accessible to people with disabilities. More specifically, Web accessibility means that
people with disabilities can perceive, understand, navigate, and interact with the Web, and that they can contribute to the Web.

An absolute URL contains all the information necessary to locate a resource. format: scheme://server/path/resource
A relative URL typically consists only of the path, and optionally, the resource, but no scheme or server.

Print specific area on webpage:


var prtContent = document.getElementById("your div id");
var WinPrint = window.open('', '', 'left=0,top=0,width=800,height=900,toolbar=0,scrollbars=0,status=0');
WinPrint.document.write(prtContent.innerHTML);
WinPrint.document.close(); WinPrint.focus(); WinPrint.print(); WinPrint.close();

Add class: CSS Child: .box:nth-child(4n+1)-select every 4th row/element


element.className - JavaScript .box:nth-child(5)- select only the 5th element
$(selector).addClass(classname)) –jquery
Canvas Code: Canvas code to make circle:
<canvas id="myCanvas" width="200" height="100" var c=document.getElementById("myCanvas");
style="border:1px solid #000000;"> var ctx=c.getContext("2d");
Your browser does not support the HTML5 canvas tag. ctx.beginPath();
</canvas> ctx.arc(100,75,50,0,2*Math.PI);
ctx.stroke();
Create element dynamically: We can use DOM createElement()
<script>
function myFunction() {
var btn = document.createElement("BUTTON");
var t = document.createTextNode("CLICK ME");
btn.appendChild(t);
document.body.appendChild(btn);}</script>

Palindrome(\W metacharacter is used to find a word character & g is used for a global replacement)
function isPalindrome(str) { console.log(isPalindrome("level")); // logs 'true'
str = str.replace(/\W/g, '').toLowerCase(); console.log(isPalindrome("levels")); // logs 'false'
return (str == str.split('').reverse().join('')); console.log(isPalindrome("A car, a man, a maraca")); // logs
} 'true'
A word character is a character from a-z, A-Z, 0-9, including the _ (underscore) character.

console.log("A"-"B"); // Output is NaN alert(1+2+undefined) // NaN


console.log("A"-"B"+”50”); // Output is NaN50 console.log("20"-10); // 10

Detect if device used is mobile or not


if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
// some code..}

Merge two arrays & remove duplicates


var array1 = ["Vijendra","Singh"]; var array2 = ["Singh", "Shakya"];
var array3 = array1.concat(array2);
var unique = array3.filter(function(elem,index,self) {
return index==self.indexOf(elem);});

Function Declarations vs. Function Expressions: A Function Declaration defines a named function variable without requiring variable
assignment. Difference is that function expression is defined/loaded only when that line is reached, whereas function declaration is
loaded before any code is executed. (due to hoisting)
function bar() {
return 3;
}
bar() //3
bar //function
A Function Expression defines a function as a part of larger expression syntax (typically a variable assignment).
//anonymous function expression return 3;
var a = function() { }
//named function expression return 3;
var a = function bar() { }
//self invoking function expression alert("hello!");
(function sayHello() { })();

In css, first-child will match 1st child of an element & first-of-type will match the first element of its element type.
<div class="parent">
<h1>Child</h1> <!-- h1:first-child -->
<div>Child</div> <!-- div:nth-child(2), div:first-of-type -->
<div>Child</div>
</div>

function factorial(n){
if(n==0 || n==1)
return 1;
return n*factorial(n-1); //recursive method
}
document.write(factorial(4));

`function factorialNonRecursive(n){
if(n==0 | n==1)
return 1;
var result = n;
while(n>1){
result = result*(n-1);
n=n-1;
}
return result;
}

You might also like