Local Storage And Session Storage in JavaScript

Local Storage

The localStorage is a read-only property of the window objects. It stores data in a web browser specifically to the domain and protocol. It doesn’t get sent to the server as it is stored locally in the web browser with no expiration date. The data will not be deleted when the browser is closed and reopened.

Syntax:- window.localStorage

Methods

  • setItem (key, value) – It allows to add a key/value pair to the storage object. If the key already exists, the name value will overwrite the old value.
  • getItem(key) – It returns the value of the item that is set with the given key.
  • key(n) – It returns the key of the item in the storage object at the nth index which can be useful for looping.
  • removeItem(key) – It removes the item in the storage object with the given key.

Session Storage

The sessionStorage is a read-only property of the window object. It stores data in a web browser specifically to the domain and protocol for a particular session. It doesn’t get sent to the server. Data stored in sessionStorage gets cleared when the page session ends. A page session lasts for as long as the browser is open and survives over page reloads and restores.

Syntax:- window.sessionStorage

Methods

  • setItem (key, value) – It allows to add a key/value pair to the storage object. If the key already exists, the name value will overwrite the old value.
  • getItem(key) – It returns the value of the item that is set with the given key.
  • key(n) – It returns the key of the item in the storage object at the nth index which can be useful for looping.
  • removeItem(key) – It removes the item in the storage object with the given key.
Tagged : / / /

History Object and Location Object in javascript?

History Object

The History object is a read-only array of URL strings that shows where the user has been recently.

Syntax: –

window.history.property

window.history.method

Property

  • length – It returns the number of URLs in the history list.

Methods

  • back ( ) – It loads the previous URL in the history list.
  • forward ( ) – It loads the next URL in the history list.
  • go ( ) – It access a particular item in the history list relative to the current position. Using a negative value moves to a history item previous to the current location, while a positive number moves forward in the history list.

Location Object

This is used to access the current location (URL) of the window. The Location object can be both read and replaced, so it is possible to update the location of a page through scripting. Location object is a property of Window.

Syntax:-

window.location.property

window.location.method

Properties

  • hash – The part of the URL including and following the # symbol.
  • host – The hostname and port number.
  • hostname – hostname
  • href – entire URL
  • pathname – Path relative to the host.
  • port – Port Number
  • protocol – Protocol of URL
  • search – The part of the URL including and after the ?

Methods

  • assign(URL) – It changes the location of current page with the passed in URL.
  • reload( ) – Reload the current page.
  • replace (URL) – Replaces the current page with the given URL in history. As it is replaced in history, it won’t be possible to access the current page with back/forward.
Tagged : / / / /

How do I manipulate using DOM Table in JavaScript?

HTMLTableElement

HTMLTableElement interface provides special properties and for manipulating the layout and presentation of tables in an HTML document.

Properties
caption
tHead
tFoot
rows
tBodies

Methods
createCaption()
deleteCaption()
createTHead()
deleteTHead()
createTFoot()
deleteTFoot()
insertRow()
deleteRow()

Properties

  • caption – This property represents the table caption. If no caption element is associated with the table, it can be null.
  • tHead – This property represents  the table’s <thead> element. Its value can be null if there is no such element.
  • tFoot – This property represents the table’s <tfoot> element. Its value can be null if there is no such element.
  • rows – This property rows returns a live HTMLCollection of all the rows in the table, including the rows contained within any <thead>, <tfoot>, and <tbody> elements. Although the property itself is read-only, the returned object is live and allows the modification of its content.
  • tBodies – This read-only property returns a live HTMLCollection of the table bodies. Although the property is read-only, the returned object is live and allows the modification of its content.

Methods

  • createCaption() – This method returns the caption for the table. If no caption element exists on the table, this method creates it, then returns it.
  • deleteCaption() – This method removes the caption from the table. If there is no caption associated with the table, this method does nothing.
  • createTHead( ) – This method returns the <thead> element association with the table, of type HTMLTableSectionElement. If there is no such element associated to the table, this method creates it, then returns it.
  • deleteTHead() – This removes a <thead> element from the table.
  • createTFoot() – This method returns the <tfoot> element associated with the table, of type HTMLTableSectionElement. If there is no footer for this table, this methods creates it, then returns it.
  • deleteTFoot() – This method removes a <tfoot> element from the table.
  • insertRow() method inserts a new row in the table and returns a reference to the new row.

Syntax: – var row = HTMLTableElement.insertRow(index = -1);

index is the row index of the new row.
row is assigned a reference to the new row. A reference to HTMLTableRowElement.
If index is -1 or equal to the number of rows, the row is appended as the last row. If index is greater than the number of rows, an IndexSizeError exception will result. If index is omitted it defaults to -1.
If a table has multiple tbody elements, by default, the new row is inserted into the last tbody.

  • deleteRow() method removes a row from the table. If the number of rows to delete, specified by the parameter, is greater or equal to the number of available rows, or if it is negative and not equal to the special index -1, representing the last row of the table, the exception INDEX_SIZE_ERR is thrown.

Syntax: – HTMLTableElement.deleteRow(index)

an index is an integer representing the row that should be deleted.
However, the special index -1 can be used to remove the very last row of a table.

HTMLTableSectionElement

The HTMLTableSectionElement interface provides special properties and methods for manipulating the layout and presentation of sections, that is headers, footers and bodies, in an HTML table.

Properties
rows

Methods
insertRow()
deleteRow()

  • Rows – This returns a live HTMLCollection containing the rows in the section. The HTMLCollection is live and is automatically updated when rows are added or removed.
  • insertRow() – It inserts a new row just before the given position in the section. If the given position is not given or is -1, it appends the row to the end of section. If the given position is greater (or equal as it starts at zero) than the amount of rows in the section, or is smaller than -1, it raises a DOMException with the IndexSizeError value.
  • deleteRow() – It removes the cell at the given position in the section. If the given position is greater (or equal as it starts at zero) than the amount of rows in the section, or is smaller than 0, it raises a DOMException with the IndexSizeError value.

HTMLTableRowElement

The HTMLTableRowElement interface provides special properties and methods for manipulating the layout and presentation of rows in an HTML table.

Properties
cells
rowIndex
sectionRowIndex

Methods
insertCell()
deleteCell()

Properties

  • cells – It returns a live HTMLCollection containing the cells in the row. The HTMLCollection is live and is automatically updated when cells are added or removed.
  • rowIndex – It returns a long value which gives the logical position of the row within the entire table. If the row is not part of a table, returns -1.
  • sectionRowIndex – It returns a long value which gives the logical position of the row within the table section it belongs to. If the row is not part of a section, returns -1.

Methods

  • insertCell() – This method inserts a new cell into a table row and returns a reference to the cell.

Syntax: – var cell = HTMLTableRowElement.insertCell(index = -1);

HTMLTableRowElement is a reference to an HTML table row element.
index is the cell index of the new cell.
cell, is assigned a reference to the new cell.
If index is -1 or equal to the number of cells, the cell is appended as the last cell in the row. If index is greater than the number of cells, an IndexSizeError exception will result. If index is omitted it defaults to -1.

Methods

  • deleteCell() – It removes the cell at the given position in the row. If the given position is greater (or equal as it starts at zero) than the amount of cells in the row, or is smaller than 0, it raises a DOMException with the IndexSizeError value.
Tagged : / / /

CSS manipulation in JavaScript

CSSStyleDeclaration Object

The CSSStyleDeclaration object represents a collection of CSS property-value pairs.

It is used in API :

HTMLElement.style
window.getComputedStyle( )

Properties

  • cssText
  • length
  • parentRule

Methods

getPropertyValue(property)
getPropertyPriority(property)
removeProperty(property)
setProperty(property, value, priority)
item(index)

Style Property

The style property is used to get or set the inline style of an element. While getting, it returns a CSSStyleDeclaration object that contains a list of all styles properties for that element with values assigned for the attributes that are defined in the element’s inline style attribute.

Style Property represents only the CSS declarations set in the element’s inline style attribute, not those that come from style rules elsewhere, such as style rules in the <head> section, or external style sheets or browser default.

Syntax:-

Return
element.style.property

Set
element.style.property = “value”

A style declaration is reset by setting it to null or an empty string, e.g. element.style.property = null

Inline Style Manipulation

The most direct way to modify CSS value with JavaScript is through the style property that corresponding to the inline style sheet specification for a particular HTML element. To perform a manipulation of the CSS with a JavaScript DOM interface, you would access the style object of the element.

Style Property

Example: –

Dynamic Style Manipulation

As we know The most direct way to modify CSS value with JavaScript is through the style property that corresponding to the inline style sheet specification for a particular HTML element, This has performance considerations since you need to change a single property at a time. We might manipulate style rules using CSS class Selector. The element’s class attribute is represented as className property in DOM.

DOMTokenList

The DOMTokenList interface represents a set of space-separated tokens. Such a set is returned by Element.classList, HTMLLinkElement.relList, HTMLAnchorElement.relList, HTMLAreaElement.relList, HTMLIframeElement.sandbox, or HTMLOutputElement.htmlFor.  etc. It is indexed beginning with 0 as with JavaScript Array objects. DOMTokenList is always case-sensitive.

Properties
length
value

Methods
item()
add()
remove()
replace()
contains()
toggle()
value()

classList Property

The Element.classList is a read-only property that returns a live DOMTokenList collection of the class attributes of the element.

Syntax: –

var elementClasses = elementNodeReference.classList;

Computed Style

The computed style is the style actually used in displaying the element, after “stylings” from multiple sources have been applied.
Style sources can include: internal style sheets, external style sheets, inherited styles, and browser default styles.
Style Property represents only the CSS declarations set in the element’s inline style attribute, not those that come from style rules elsewhere, such as style rules in the section, or external style sheets or browser default. To get the values of all CSS properties for an element you should use window.getComputedStyle( ) instead.
The returned style is a live CSSStyleDeclaration object ( The CSSStyleDeclaration object represents a collection of CSS property-value pairs.), which updates itself automatically when the element’s style is changed.

Syntax:-
window.getComputedStyle(element, pseudoElement)
Element – Element for which to get the computed style.
pseudoElement – A string specifying the pseudo-element to match. Must be omitted (or null) for regular elements.

Ex: –
var elm = document.getElementById(“myid”);
var allCSSProp = window.getComputedStyle(elm)

Tagged : / / / / /

How do you use a date object in JavaScript?

Date

The Date object provides a sophisticated set of methods for manipulating dates and times.

• It reads client machine date and time so if the client‟s date or time is incorrect, your script will reflect this fact.
• Days of week and months of the year are enumerated beginning with zero.
0 – Sunday, 1 – Monday, and so on
0 – January, 1 – February, and so on
• Days of the month begin with One.

Creating Date Object

Date objects are created with the new Date() constructor. Date Objects created by programmers are static. They do not contain a ticking clock.

Syntax:-

Creating Date Object

  • new Date( ) – new Date() creates a new date object with the current date and time.

Creating Date Object

  • new Date(milliseconds) – It creates a new date object as January 1, 1970, 00:00:00 Universal Time (UTC).

Ex: –

Creating Date Object

  • new Date(year, month, day, hours, minutes, seconds, milliseconds) It creates an object with the date specified by the integer values for the year, month, day, hours, minutes, second, milliseconds. You can omit some of the arguments.

Month and Week Day start with 0
0 – Sunday
0 – January
Month Day starts with 1
1 – 1

Creating Date Object

No. of argumentsDescription (in order)
7year, month, day, hour, minute, second, millisecond
6year, month, day, hour, minute, second
5year, month, day, hour, minute
4year, month, day, hour
3year, month, day
2year and month
1Millisecond

Creating Date Object

  • new Date(dateString) – new Date(dateString) creates a new date object from a date string.

Ex: –
var tarikh = new Date(“May 12, 2018 10:16:05″)

Date TypeFormatExample
ISO DateYYYY-MM-DD“2018-06-21” (The International Standard)
Short DateMM/DD/YYYY“06/21/2018″
Long DateMMM DD YYYY“June 21 2018 or “21 June 2018″

ISO Dates

ISO 8601 is the international standard for the representation of dates and times.

DescriptionFormatExample
Year and MonthYear and Month2018-06
Only YearYYYY2018
Date and TimeYYYY-MM-DDTHH:MM: SSZ2018-06-21T12:00:00Z
Date and TimeYYYY-MM-DDTHH:MM:SS+HH: MM
YYYY-MM-DDTHH:MM:SS-HH: MM
2018-06-21T12:00:00+06:30
2018-06-21T12:00:00-06:30

Date and Time are separated with a capital T.
UTC time is defined with the capital letter Z.
If you want to modify the time relative to UTC, remove the Z and add +HH: MM or -HH: MM instead.

Short Date

  • Short dates are written in an “MM/DD/YYYY” format.
  • In some browsers, months or days with no leading zeroes may produce an error.
  • The behavior of “YYYY/MM/DD” is undefined. Some browsers will try to guess the format. Some will return NaN.
  • The behavior of “DD-MM-YYYY” is also undefined. Some browsers will try to guess the format. Some will return NaN.

Long Date

Long dates are most often written in a “MMM DD YYYY” format.
Month and day can be in any order.
A month can be written in full (January), or abbreviated (Jan).
If you write “June 21, 2018” Commas are ignored and Names are case insensitive.

Set Date Methods

  • setDate() Set the day as a number (1-31)
  • setFullYear() Set the year (optionally month and day)
  • setHours() Set the hour (0-23)
  • setMilliseconds() Set the milliseconds (0-999)
  • setMinutes() Set the minutes (0-59)
  • setMonth() Set the month (0-11)
  • setSeconds() Set the seconds (0-59)
  • setTime() Set the time (milliseconds since January 1, 1970)

Get Date Methods

  • getFullYear() Get the year as a four digit number (yyyy)
  • getMonth() Get the month as a number (0-11)
  • getDate() Get the day as a number (1-31)
  • getHours() Get the hour (0-23)
  • getMinutes() Get the minute (0-59)
  • getSeconds() Get the second (0-59)
  • getMilliseconds() Get the millisecond (0-999)
  • getTime() Get the time (milliseconds since January 1, 1970)
  • getDay() Get the weekday as a number (0-6)

Converting Dates to String

If you want to create a string in a standard format, Date provides three methods: –

  • toString( )
  • toUTCString( )
  • toGMTString( )

toUTCString ( ) and toGMTString ( ) format the string according
to Internet (GMT) standards, whereas toString ( ) creates the
string according to Local Time.

Date Methods

  • getDate() Returns the day of the month (from 1-31)
  • getDay() Returns the day of the week (from 0-6)
  • getFullYear() Returns the year
  • getHours() Returns the hour (from 0-23)
  • getMilliseconds() Returns the milliseconds (from 0-999)
  • getMinutes() Returns the minutes (from 0-59)
  • getMonth() Returns the month (from 0-11)
  • getSeconds() Returns the seconds (from 0-59)
  • getTime() Returns the number of milliseconds since midnight Jan 1 1970, and a specified date
  • getTimezoneOffset() Returns the time difference between UTC time and local time, in minutes
  • getUTCDate() Returns the day of the month, according to universal time (from 1-31)
  • getUTCDay() Returns the day of the week, according to universal time (from 0-6)
  • getUTCFullYear() Returns the year, according to universal time
  • getUTCHours() Returns the hour, according to universal time (from 0-23)
  • getUTCMilliseconds() Returns the milliseconds, according to universal time (from 0-999)
  • getUTCMinutes() Returns the minutes, according to universal time (from 0-59)
  • getUTCMonth() Returns the month, according to universal time (from 0-11)
  • getUTCSeconds() Returns the seconds, according to universal time (from 0-59)
  • now() Returns the number of milliseconds since midnight Jan 1, 1970
  • parse() Parses a date string and returns the number of milliseconds since January 1, 1970
  • setDate() Sets the day of the month of a date object
  • setFullYear() Sets the year of a date object
  • setHours() Sets the hour of a date object
  • setMilliseconds() Sets the milliseconds of a date object
  • setMinutes() Set the minutes of a date object
  • setMonth() Sets the month of a date object
  • setSeconds() Sets the seconds of a date objec
  • setTime() Sets a date to a specified number of milliseconds after/before January 1, 1970
  • setUTCDate() Sets the day of the month of a date object, according to universal time
  • setUTCFullYear() Sets the year of a date object, according to universal time
  • setUTCHours() Sets the hour of a date object, according to universal time
  • setUTCMilliseconds() Sets the milliseconds of a date object, according to universal time
  • setUTCMinutes() Set the minutes of a date object, according to universal time
  • setUTCMonth() Sets the month of a date object, according to universal time
  • setUTCSeconds() Set the seconds of a date object, according to universal time
  • toDateString() Converts the date portion of a Date object into a readable string
  • toISOString() Returns the date as a string, using the ISO standard
  • toJSON() Returns the date as a string, formatted as a JSON date
  • toLocaleDateString() Returns the date portion of a Date object as a string, using locale conventions
  • toLocaleTimeString() Returns the time portion of a Date object as a string, using locale conventions
  • toLocaleString() Converts a Date object to a string, using locale conventions
  • toString() Converts a Date object to a string
  • toTimeString() Converts the time portion of a Date object to a string
  • toUTCString() Converts a Date object to a string, according to universal time
  • UTC() Returns the number of milliseconds in a date since midnight of January 1, 1970,
    • according to UTC time
  • valueOf() Returns the primitive value of a Date object
Tagged : / / /

How can I use math Object Properties in JavaScript?

Math

The Math object holds a set of constants and methods that enable more complex mathematical operations than the basic arithmetic operators. We can not instantiate a Math Object. The Math object is static so it‟s properties and methods are accessed directly.

Ex:-
Math.PI
Math.abs( )

Properties

  • E Returns Euler’s number (approx. 2.718)
  • LN2 Returns the natural logarithm of 2 (approx. 0.693)
  • LN10 Returns the natural logarithm of 10 (approx. 2.302)
  • LOG2E Returns the base-2 logarithm of E (approx. 1.442)
  • LOG10E Returns the base-10 logarithm of E (approx. 0.434)
  • PI Returns PI (approx. 3.14)
  • SQRT1_2 Returns the square root of 1/2 (approx. 0.707)
  • SQRT2 Returns the square root of 2 (approx. 1.414)

Methods

  • Math.abs(arg) Returns the absolute value of arg
  • Math.acos(arg) Returns the arccosine of arg, in radians
  • Math.acosh(arg) Returns the hyperbolic arccosine of arg
  • Math.asin(arg) Returns the arcsine of arg, in radians
  • Math.asinh(arg) Returns the hyperbolic arcsine of arg
  • Math.atan(arg) Returns the arctangent of arg as a numeric value between -PI/2 and PI/2 radians
  • Math.atan2(arg1, arg2) Returns the arctangent of the quotient of its arguments
  • Math.atanh(arg) Returns the hyperbolic arctangent of arg

Methods

  • Math.cbrt(arg) Returns the cubic root of arg
  • Math.ceil(arg) Returns arg, rounded upwards to the nearest integer
  • Math.cos(arg) Returns the cosine of arg (arg is in radians)
  • Math.cosh(arg) Returns the hyperbolic cosine of arg
  • Math.exp(arg) Returns the value of Ex
  • Math.floor(arg) Returns arg, rounded downwards to the nearest integer
  • Math.log(arg) Returns the natural logarithm (base E) of arg
  • Math.random() Returns a random number between 0 and 1
  • Math.round(arg) Rounds arg to the nearest integer

Methods

  • Math.max(arg1, arg2, …,arg_n) Returns the number with the highest value
  • Math.min(arg1, arg2, …,arg_n) Returns the number with the lowest value
  • Math.pow(arg1, arg2) Returns the value of arg to the power of arg2
  • Math.sin(arg) Returns the sine of arg (arg is in radians)
  • Math.sinh(arg) Returns the hyperbolic sine of arg
  • Math.sqrt(arg) Returns the square root of arg
  • Math.tan(arg) Returns the tangent of an angle
  • Math.tanh(arg) Returns the hyperbolic tangent of a number
  • Math.trunc(arg) Returns the integer part of a number (arg)

Tagged : / / /

Global JavaScript Methods

Global JS Methods

JavaScript global methods can be used on all JavaScript data types.

  • Number ( )
  • parseFloat ( )
  • parseInt ( )

Number ( )

The Number() function converts the object argument to a number that
represents the object’s value.
If the value cannot be converted to a legal number, NaN is returned.
If the parameter is a Date object, the Number() function returns the number of
milliseconds since midnight January 1, 1970, UTC.

Ex: –

Number(true)
Number(“100”)
Number(100/“Hello”)

parseInt ( )

The parseInt() function parses a string and returns an integer.

Syntax:- parseInt(string, radix)

The radix parameter is used to specify which numeral system to be used, for example, a
the radix of 16 (hexadecimal) indicates that the number in the string should be parsed from
a hexadecimal number to a decimal number.

If the radix parameter is omitted, JavaScript assumes the following:

  • If the string begins with “0x”, the radix is 16 (hexadecimal)
  • If the string begins with any other value, the radix is 10 (decimal)

Only the first number in the string is returned.
Leading and trailing spaces are allowed.
If the first character cannot be converted to a number, parseInt() returns NaN.

parseInt ( )

parseFloat ( )

The parseFloat() function parses a string and returns a floating-point number. This function determines if the first character in the specified string is a number. If it is, it parses the string until it reaches the end of the number, and returns the number as a number, not as a string.

Syntax: – parseFloat(string)

  • Only the first number in the string is returned!
  • Leading and trailing spaces are allowed.
  • If the first character cannot be converted to a number, parseFloat() returns NaN.

parseFloat ( )

Tagged : / / / / /