Blog

  • JavaScript – Navigator Object

    Window Navigator Object

    The navigator object in JavaScript is used to access the information of the user’s browser. Using the ‘navigator’ object, you can get the browser version and name and check whether the cookie is enabled in the browser.

    The ‘navigator’ object is a property of the window object. The navigator object can be accessed using the read-only window.navigator property.

    Navigator Object Properties

    There are many properties of navigator object that can be used to access the information about the user’s browser.

    Syntax

    Follow the syntax below to use to access a property of navigator object in JavaScript.

    window.navigator.proeprty;OR
    navigator.property;

    You may use the ‘window’ object to access the ‘navigator’ object.

    Here, we have listed all properties of the Navigator object.

    PropertyDescription
    appNameIt gives you a browser name.
    appVersionIt gives you the browser version.
    appCodeNameIt gives you the browser code name.
    cookieEnabledIt returns a boolean value based on whether the cookie is enabled.
    languageIt returns the browser language. It is supported by Firefox and Netscape only.
    pluginsIt returns the browser plugins. It is supported by Firefox and Netscape only.
    mimeTypes[]It gives you an array of Mime types. It is supported by Firefox and Netscape only.
    platformIt gives you a platform or operating system in which the browser is used.
    onlineReturns a boolean value based on whether the browser is online.
    productIt gives you a browser engine.
    userAgentIt gives you a user-agent header of the browser.

    Example: Accessing Navigator Object Properties

    We used the different properties in the below code to get the browser information.

    The appName property returns the browser’s name, appCodeName returns the code name of the browser, appVersion returns the browser’s version, and the cookieEnabled property checks whether the cookies are enabled in the browser.

    <html><body><p> Browser Information</p><p id ="demo"></p><script>
          document.getElementById("demo").innerHTML ="App Name: "+ navigator.appName +"<br>"+"App Code Name: "+ navigator.appCodeName +"<br>"+"App Version: "+ navigator.appVersion +"<br>"+"Cookie Enabled: "+ navigator.cookieEnabled +"<br>"+"Language: "+ navigator.language +"<br>"+"Plugins: "+ navigator.plugins +"<br>"+"mimeTypes[]: "+ navigator.mimeTypes +"<br>"+"platform: "+ navigator.platform +"<br>"+"online: "+ navigator.online +"<br>"+"product: "+ navigator.product +"<br>"+"userAgent: "+ navigator.userAgent;</script><p>Please note you may get different result depending on your browser.</p></body></html>

    Output

    Browser Information
    
    App Name: Netscape
    App Code Name: Mozilla
    App Version: 5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36
    Cookie Enabled: true
    Language: en-US
    Plugins: [object PluginArray]
    mimeTypes[]: [object MimeTypeArray]
    platform: Win32
    online: undefined
    product: Gecko
    userAgent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36
    
    Please note you may get different result depending on your browser.
    

    Example

    In the example below, we accessed the navigator object as a property of the window object. Then we accessed different properties of this navigator object.

    <html><body><p> Browser Information</p><p id ="demo"></p><script>
    	  document.getElementById("demo").innerHTML ="App Name: "+ window.navigator.appName +"<br>"+"App Code Name: "+ window.navigator.appCodeName +"<br>"+"App Version: "+ window.navigator.appVersion +"<br>"+"Cookie Enabled: "+ window.navigator.cookieEnabled +"<br>"+"Language: "+ window.navigator.language +"<br>"+"Plugins: "+ window.navigator.plugins +"<br>"+"mimeTypes[]: "+ window.navigator.mimeTypes +"<br>"+"platform: "+ window.navigator.platform +"<br>"+"online: "+ window.navigator.online +"<br>"+"product: "+ window.navigator.product +"<br>"+"userAgent: "+ window.navigator.userAgent;</script><p>Please note you may get different result depending on your browser.</p></body></html>

    Output

    Browser Information
    
    App Name: Netscape
    App Code Name: Mozilla
    App Version: 5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36
    Cookie Enabled: true
    Language: en-US
    Plugins: [object PluginArray]
    mimeTypes[]: [object MimeTypeArray]
    platform: Win32
    online: undefined
    product: Gecko
    userAgent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36
    
    Please note you may get different result depending on your browser.
    

    JavaScript Navigator Object Methods

    The Navigator object contains only one method.

    MethodDescription
    javaEnabled()It checks whether the Java is enabled in the web browser.

    Example: Navigator javaEnabled() Method

    In the below code, we used the javaEnabled() method of the navigator object to check whether the java is enabled in the browser.

    <html><body><p id ="output"></p><script>const output = document.getElementById("output");if(navigator.javaEnabled()){
             output.innerHTML +="Java is enabled in the browser!";}else{
             output.innerHTML +="Please, enable the Java!";}</script><p>Please note you may get different result depending on your browser.</p></body></html>

    Output

    Please, enable the Java!
    
    Please note you may get different result depending on your browser.
  • JavaScript – History Object

    Window History Object

    In JavaScript, the window ‘history’ object contains information about the browser’s session history. It contains the array of visited URLs in the current session.

    The ‘history’ object is a property of the ‘window’ object. The history property can be accessed with or without referencing its owner object, i.e., window object.

    Using the ‘history’ object’s method, you can go to the browser’s session’s previous, following, or particular URL.

    History Object Methods

    The window history object provides useful methods that allow us to navigate back and forth in the history list.

    Follow the syntax below to use the ‘history’ object in JavaScript.

    window.history.methodName();OR
    history.methodName();

    You may use the ‘window’ object to access the ‘history’ object.

    JavaScript History back() Method

    The JavaScript back() method of the history object loads the previous URL in the history list.

    Syntax

    Follow the syntax below to use the history back() method.

    history.back();

    Example

    In the below code’s output, you can click the ‘go back’ button to go to the previous URL. It works as a back button of the browser.

    <html><body><p> Click "Go Back" button to load previous URL</p><button onclick="goback()"> Go Back </button><p id ="output"></p><script>functiongoback(){
             history.back();
             document.getElementById("output").innerHTML +="You will have gone to previous URL if it exists";}</script></body></html>

    JavaScript History forward() Method

    The forward() method of the history object takes you to the next URL.

    Syntax

    Follow the syntax below to use the forward() method.

    history.forward();

    Example

    In the below code, click the button to go to the next URL. It works as the forward button of the browser.

    <html><body><p> Click "Go Forward" button to load next URL</p><button onclick ="goforward()"> Go Forward </button><p id ="output"></p><script>functiongoforward(){
             history.forward();
             document.getElementById("output").innerHTML ="You will have forwarded to next URL if it exists."}</script></body></html>

    JavaScript History go() Method

    The go() method of the history object takes you to the specific URL of the browser’s session.

    Syntax

    Follow the syntax below to use the go() method.

    history.go(count);

    In the above syntax, ‘count’ is a numeric value representing which page you want to visit.

    Example

    In the below code, we use the go() method to move to the 2nd previous page from the current web page.

    <html><body><p> Click the below button to load 2nd previous URL</p><button onclick ="moveTo()"> Move at 2nd previous URL</button><p id ="output"></p><script>functionmoveTo(){
             history.go(-2);
             document.getElementById("output").innerHTML ="You will have forwarded to 2nd previous URL if it exists.";}</script></body></html>

    Example

    In the below code, we use the go() method to move to the 2nd previous page from the current web page.

    <html><body><p> Click the below button to load 2nd next URL</p><button onclick ="moveTo()"> Move at 2nd next URL</button><p id ="output"></p><script>functionmoveTo(){
             history.go(2);
             document.getElementById("output").innerHTML ="You will have forwarded to 2nd next URL if it exists.";}</script></body></html>

    Following is the complete window history object reference including both properties and methods −

    History Object Property List

    The history object contains only the ‘length’ property.

    PropertyDescription
    lengthIt returns the object’s length, representing the number of URLS present in the object.

    History Object Methods List

    The history object contains the below 3 methods.

    MethodDescription
    back()It takes you to the previous web page.
    forward()It takes you to the next web page.
    go()It can take you to a specific web page.
  • JavaScript – Screen Object

    Window Screen Object

    The screen object in JavaScript is a property of the ‘window’ object. The ‘screen’ object’s properties contain information about the device’s screen. The screen object can be accessed by using the window.screen syntax. We can also access it without using the window object.

    Screen Object Properties

    The screen object has a number of properties that provide information about the screen’s orientation, resolution, and more. These properties can be used to develop applications that are responsive to different screen sizes and orientations.

    Following are some properties of the JavaScript screen object −

    • width − The width of the screen in pixels.
    • height − The height of the screen in pixels.
    • availWidth − The width of the screen, minus the width of the window taskbar.
    • availHeight − The height of the screen, minus the height of the window taskbar.
    • colorDepth − The number of bits per pixel that the screen can display.
    • pixelDepth − The number of bits per pixel that the screen is actually using.

    Screen Object Property Syntax

    Follow the syntax below to use the property of the screen object in JavaScript −

    window.screen.property;OR
    screen.property;

    You may or may not use the ‘window’ object to access the screen object.

    Example

    In the example below, we access the various properties of the screen object with referencing the screen as the property of window object.

    <html><body><p> Screen Information </p><div id ="output"></div><script>
          document.getElementById("output").innerHTML ="screen height: "+ window.screen.height +"<br>"+"screen width: "+ window.screen.width +"<br>"+"screen colorDepth: "+ window.screen.colorDepth +"<br>"+"screen pixelDepth: "+ window.screen.pixelDepth +"<br>"+"screen availHeight: "+ window.screen.availHeight +"<br>"+"screen availWidth: "+ window.screen.availWidth;</script></body></html>

    Output

    Screen Information
    screen height: 864
    screen width: 1536
    screen colorDepth: 24
    screen pixelDepth: 24
    screen availHeight: 816
    screen availWidth: 1536
    

    Example

    In the below code, we access the various properties of the screen object and observe their value. In this example we are not referencing the window object to access the screen object.

    <html><body><p> Screen Information </p><div id ="output"></div><script>
          document.getElementById("output").innerHTML ="screen height: "+ screen.height +"<br>"+"screen width: "+ screen.width +"<br>"+"screen colorDepth: "+ screen.colorDepth +"<br>"+"screen pixelDepth: "+ screen.pixelDepth +"<br>"+"screen availHeight: "+ screen.availHeight +"<br>"+"screen availWidth: "+ screen.availWidth;</script></body></html>

    Output

    Screen Information
    screen height: 864
    screen width: 1536
    screen colorDepth: 24
    screen pixelDepth: 24
    screen availHeight: 816
    screen availWidth: 1536
    

    Please note that we get the same information about the screen in the above two examples.

    Screen Object Properties List

    Below, we have covered all properties of the ‘screen’ object with a description. You need to use the ‘screen’ as a reference to access these properties.

    PropertyDescription
    availHeightIt gives the height of the screen without including the taskbar.
    availWidthIt gives the width of the screen without including the taskbar.
    colorDepthIt gives the depth of the color palette to display images.
    heightIt returns the total height of the screen.
    pixelDepthIt is used to get the color resolution of the screen.
    widthTo get the total width of the screen.
  • JavaScript – Document Object

    Window Document Object

    The document object is a JavaScript object that provides the access to all elements of an HTML document. When the HTML document is loaded in the web browser, it creates a document object. It is the root of the HTML document.

    The document object contains the various properties and methods you can use to get details about HTML elements and customize them.

    The JavaScript document object is a property of the window object. It can be accessed using window.document syntax. It can also be accessed without prefixing window object.

    JavaScript Document Object Properties

    The JavaScript Document Object represents the entire HTML document, and it comes with several properties that allow us to interact with and manipulate the document. Some common Document object properties are as follows

    • document.title − Gets or sets the title of the document.
    • document.URL − Returns the URL of the document.
    • document.body − Returns the <body> element of the document.
    • document.head − Returns the <head> element of the document.
    • document.documentElement − Returns the <html> element of the document.
    • document.doctype − Returns the Document Type Declaration (DTD) of the document.

    These properties provide a way to access and modify different parts of the HTML document using JavaScript.

    Example: Accessing the document title

    In the example below, we use the document.title property to access the property odd the document.

    <html><head><title> JavaScript -DOM Object </title></head><body><div id ="output">The title of the document is:</div><script>
          document.getElementById("output").innerHTML += document.title;</script></body></html>

    Output

    The title of the document is: JavaScript - DOM Object
    

    Example: Accessing the document URL

    In the example below, we have used the document.URL property to access the current URL of the page.

    <html><head><title> JavaScript -DOM Object </title></head><body><div id ="output">The URLof the document is:</div><script>
          document.getElementById("output").innerHTML += document.URL;</script></body></html>

    Output

    The URL of the document is: https://www.tutorialspoint.com/javascript/javascript_document_object.htm
    

    JavaScript Document Object Methods

    The JavaScript Document Object provides us with various methods that allow us to interact with and manipulate the HTML document. Some common Document object methods are as follows

    • getElementById(id) − Returns the element with the specified ID.
    • getElementsByClassName(className) − Returns a collection of elements with the specified class name.
    • getElementsByTagName(tagName) − Returns a collection of elements with the specified tag name.
    • createElement(tagName) − Creates a new HTML element with the specified tag name.
    • createTextNode(text) − Creates a new text node with the specified text.
    • appendChild(node) − Appends a node as the last child of a node.
    • removeChild(node) − Removes a child node from the DOM.
    • setAttribute(name, value) − Sets the value of an attribute on the specified element.
    • getAttribute(name) − Returns the value of the specified attribute on the element.

    These methods enable us to dynamically manipulate the structure and content of the HTML document using JavaScript.

    Example: Accessing HTML element using its id

    In the example below, we use document.getElementById() method to access the DIV element with id “output” and then use the innerHTML property of the HTML element to display a message.

    <html><body><div id ="result"></div><script>// accessing the DIV element.
       document.getElementById("result").innerHTML +="Hello User! You have accessed the DIV element using its id.";</script></body></html>

    Output

    Hello User! You have accessed the DIV element using its id.
    

    Example: Adding an event to the document

    In the example below, we use document.addEventListener() method to add a mouseover event to the document.

    <html><body><div id ="result"><h2> Mouseover Event </h2><p> Hover over here to change background color </p></div><script>
          document.addEventListener('mouseover',function(){
             document.getElementById("result").innerHTML ="Mouseover event occurred.";});</script></body></html>

    Document Object Properties List

    Here, we have listed all properties of the document object.

    PropertyDescription
    document.activeElementTo get the currently focused element in the HTML document.
    adoptedStyleSheetsIt sets the array of the newly constructed stylesheets to the document.
    baseURITo get the absolute base URI of the document.
    bodyTo set or get the documents <body> tag.
    characterSetTo get the character encoding for the document.
    childElementCountTo get a count of the number of child elements of the document.
    childrenTo get all children of the document.
    compatModeTo get a boolean value representing whether the document is rendered in the standard modes.
    contentTypeIt returns the MIME type of the document.
    cookieTo get the cookies related to the document.
    currentScriptIt returns the script of the document whose code is currently executing.
    defaultViewTo get the window object associated with the document.
    designModeTo change the editability of the document.
    dirTo get the direction of the text of the document.
    doctypeTo get the document type declaration.
    documentElementTo get the <html> element.
    documentURITo set or get the location of the document.
    embedsTo get all embedded (<embed>) elements of the document.
    firstElementChildTo get the first child element of the document.
    formsIt returns an array of <form> elements of the document.
    fullScreenElementTo get the element that is being presented in the full screen.
    fullScreenEnabledIt returns the boolean value, indicating whether the full screen is enabled in the document.
    headIt returns the <head> tag of the document.
    hiddenIt returns a boolean value, representing whether the document is considered hidden.
    imagesIt returns the collection of the <img> elements.
    lastElementChildIt returns the last child element of the document.
    lastModifiedTo get the last modified date and time of the document.
    linksTo get the collection of all <a> and <area> elements.
    locationTo get the location of the document.
    readyStateTo get the current state of the document.
    referrerTo get the URL of the document, which has opened the current document.
    scriptsTo get the collection of all <script> elements in the document.
    scrollingElementTo get the reference to the element which scrolls the document.
    styleSheetsIt returns the style sheet list of the CSSStyleSheet object.
    timeLineIt represents the default timeline of the document.
    titleTo set or get the title of the document.
    URLTo get the full URL of the HTML document.
    visibilityStateIt returns the boolean value, representing the visibility status of the document.

    Document Object Methods List

    The following is a list of all JavaScript document object methods −

    MethodDescription
    addEventListener()It is used to add an event listener to the document.
    adoptNode()It is used to adopt the node from the other documents.
    append()It appends the new node or HTML after the last child node of the document.
    caretPositionFromPoint()It returns the caretPosition object, containing the DOM node based on the coordinates passed as an argument.
    close()It closes the output stream opened using the document.open() method.
    createAttribute()It creates a new attribute node.
    createAttributeNS()It creates a new attribute node with the particular namespace URI.
    createComment()It creates a new comment node with a specific text message.
    createDocumentFragment()It creates a DocumentFragment node.
    createElement()It creates a new element node to insert into the web page.
    createElementNS()It is used to create a new element node with a particular namespace URI.
    createEvent()It creates a new event node.
    createTextNode()It creates a new text node.
    elementFromPoint()It accesses the element from the specified coordinates.
    elementsFromPoint()It returns the array of elements that are at the specified coordinates.
    getAnimations()It returns the array of all animations applied on the document.
    getElementById()It accesses the HTML element using the id.
    getElementsByClassName()It accesses the HTML element using the class name.
    getElementsByName()It accesses the HTML element using the name.
    getElementsByTagName()It accesses the HTML element using the tag name.
    hasFocus()It returns the boolean value based on whether any element or document itself is in the focus.
    importNode()It is used to import the node from another document.
    normalize()It removes the text nodes, which are empty, and joins other nodes.
    open()It is used to open a new output stream.
    prepand()It is used to insert the particular node before all nodes.
    querySelector()It is used to select the first element that matches the css selector passed as an argument.
    querySelectorAll()It returns the nodelist of the HTML elements, which matches the multiple CSS selectors.
    removeEventListener()It is used to remove the event listener from the document.
    replaceChildren()It replaces the children nodes of the document.
    write()It is used to write text, HTML, etc., into the document.
    writeln()It is similar to the write() method but writes each statement in the new line.
  • JavaScript – Window Object

    The JavaScript window object represents the browser’s window. In JavaScript, a ‘window’ object is a global object. It contains the various methods and properties that we can use to access and manipulate the current browser window. For example, showing an alert, opening a new window, closing the current window, etc.

    All the JavaScript global variables are properties of window object. All global functions are methods of the window object. Furthermore, when the browser renders the content in the ‘iframe, it creates a separate ‘window’ object for the browser and each iframe.

    Here, you will learn to use the ‘window’ object as a global object and use the properties and methods of the window object.

    Window Object as a Global Object

    As ‘window’ is a global object in the web browser, you can access the global variables, functions, objects, etc., using the window object anywhere in the code.

    Let’s understand it via the example below.

    Example

    In the below code, we have defined the ‘num’ global and local variables inside the function. Also, we have defined the ‘car’ global object.

    In the test() function, we access the global num variable’s value using the ‘window’ object.

    <html><body><div id ="output1">The value of the global num variable is:</div><div id ="output2">The value of the local num variable is:</div><div id ="output3">The value of the car object is:</div><script>var num =100;const car ={
             brand:"Honda",
             model:"city",}functiontest(){let num =300;
             document.getElementById("output1").innerHTML += window.num;
             document.getElementById("output2").innerHTML += num;
             document.getElementById("output3").innerHTML += car.brand;}test();</script></body></html>

    Output

    The value of the global num variable is: 100
    The value of the local num variable is: 300
    The value of the car object is: Honda
    

    You may also use the ‘window’ object to make a particular variable global from a particular block.

    Window Object Properties

    The ‘window’ object contains the various properties, returning the status and information about the current window.

    Below, we have covered all properties of the ‘window’ object with a description. You may use the ‘window’ as a reference to access these properties.

    Property NameProperty Description
    closedWhen the particular window is closed, it returns true.
    consoleIt returns the window’s console object.
    customElementsIt is used to define and access the custom elements in the browser window.
    devicePixelRatioIt returns the physical pixel ratio of the device divided by CSS pixel ratio.
    documentIt is used to access the HTML document opened in the current window.
    framesIt is used to get the window items like iframes, which are opened in the current window.
    frameElementIt returns the current frame of the window.
    historyIt is used to get the history object of the window.
    innerHeightIt returns the inner height of the window without including the scroll bar, toolbar, etc.
    innerWidthIt returns the inner width of the window without including the scroll bar, toolbar, etc.
    lengthIt returns the total number of iframes in the current window.
    localStorageIt is used to access the local storage of the current window.
    locationIt is used to access the location object of the current window.
    nameIt is used to get or set the name of the window.
    navigatorIt is used to get the Navigator object of the browser.
    openerIt returns a reference to the window from where the current window is opened.
    outerHeightIt returns the total height of the window.
    outerWidthIt returns the total width of the window.
    pageXOffsetIt returns the number of pixels you have scrolled the web page horizontally.
    pageYOffsetIt returns the number of pixels you have scrolled the web page vertically.
    parentIt contains the reference to the parent window of the current window.
    schedulerIt is entry point for using the prioritized task scheduling.
    screenIt returns the ‘screen’ object of the current window.
    screenLeftIt returns the position of the x-coordinate of the current window relative to the screen in pixels.
    screenTopIt returns the position of the y-coordinate of the current window relative to the screen in pixels.
    screenXIt is similar to the screenLeft property.
    screenYIt is similar to the screenTop property.
    scrollXIt is similar to the pageXOffset.
    scrollYIt is similar to the pageYOffset.
    selfIt is used to get the current state of the window.
    sessionStorageIt lets you access the ‘sessionStorage’ object of the current window.
    speechSynthesisIt allows you to use the web speech API.
    visualViewPortIt returns the object containing the viewport of the current window.
    topIt contains a reference to the topmost window.

    Here, we will cover some properties with examples.

    OuterHeight/OuterWidth Properties of the Window object

    The outerHeight property of the window object returns the window’s height, and the outerWidth property of the window object returns the window’s width.

    Example

    In the code below, we used the outerHeight and outerWidth property to get the dimensions of the window. You can change the size of the window and observe changes in the value of these properties.

    <html><body><p id ="output1">The outer width of the window is:</p><p id ="output2">The outer height of the window is:</p><script>const outerHeight = window.outerHeight;const outerWidth = window.outerWidth;
          document.getElementById("output1").innerHTML += outerWidth;
          document.getElementById("output2").innerHTML += outerHeight;</script></body></html>

    Output

    The outer width of the window is: 1536
    The outer height of the window is: 816
    

    ScreenLeft Property of the Window Object

    The window screenLeft property returns the left position of the current window.

    Example

    In the output of the below code, you can see the left position of the current window in pixels.

    <html><body><div id ="output">Your browser window is left by:</div><script>const screenLeft = window.screenLeft;
          document.getElementById("output").innerHTML += screenLeft +" px.";</script></body></html>

    Output

    Your browser window is left by: 0 px.
    

    Window Object Methods

    The ‘window’ object also contains methods like properties to manipulate the current browser window.

    In the below table, we have covered the methods of the ‘window’ object with their description. You may use ‘window’ as a reference to access and invoke the below methods to make the code readable.

    Method NameMethod Description
    alert()It is used to show the alert message to the visitors.
    atob()It converts the string into the base-64 string.
    blur()It removes the focus from the window.
    btoa()It decodes the base-64 string in the normal string.
    cancelAnimationFrame()It cancels the animation frame scheduled using the requestAnimationFrame() method.
    cancelIdleCallback()It cancels a callback scheduled with the requestIdCallback() method.
    clearImmediate()It is used to clear actions specified using the setImmediate() method.
    clearInterval()It resets the timer you have set using the setInterval() method.
    clearTimeout()It stops the timeout you have set using the setTimeOut() method.
    close()It is used to close the current window.
    confirm()It shows the confirm box to get the confirmation from users.
    focus()It focuses on the current active window.
    getComputedStyle()It returns the current window’s computed CSS style.
    getSelection()It returns the selection object based on the selected text range.
    matchMedia()It returns a new MediaQueryList object, which you can use to check whether the document matches the media queries.
    moveBy()It changes the position of the window relative to the current position.
    moveTo()It changes the position of the window absolutely.
    open()It opens a new window.
    postMessage()It is used to send a message to a window.
    print()It lets you print the window.
    prompt()It allows you to show a prompt box to get user input.
    requestAnimationFrame()It helps you to tell the browser that you want to perform an animation so the browser can update the animation before the next repaint.
    requestIdleCallback()It sets the callback functions to be called when the browser is Idle.
    resizeBy()It resizes the window by a particular number of pixels.
    resizeTo()It changes the size of the window.
    scrollTo()It scrolls the window to the absolute position.
    scrollBy()It scrolls the window relative to the current position.
    setImmediate()It breaks up long-running operations and runs the callback function instantly when the browser completes other operations.
    setInterval()It is used to execute a particular action after every interval.
    setTimeout()It is used to execute a particular action after a particular time.
    stop()It stops the loading of window.

    Here, we will cover some methods with examples.

    JavaScript window.alert() Method

    The window.alert() method allows you to show the pop-up dialog containing the message, warning, etc. It takes the string text as an argument.

    Example

    In the below example, when you click the button, it will invoke the alert_func() function and show the pop-up box at the middle top.

    <html><body><button onclick ="alert_func()"> Execute Alert </button><script>functionalert_func(){
             window.alert("The alert_func funciton is executed!");}</script></body></html>

    JavaScript window.open() Method

    The window.open() method is used to open a new window. It takes a URL as an argument, which you need to open in a new window.

    Example

    In the below code, we used the window.open() method to open a new window in the browser. You can see that the code opens the home page of the ‘tutorialspoint’ website in the new window.

    <html><body><button onclick ="openWindow()"> Open New Window </button><script>functionopenWindow(){
             window.open("https://www.tutorialspoint.com/");}</script></body></html>

    JavaScript window.print() Method

    The window.print() method lets you print the web page.

    Example

    In the below code, click the button to print the web page.

    <html><body><h2> Hello World!</h2><button onclick ="printPage()"> Print Webpage </button><script>functionprintPage(){
             window.print();}</script></body></html>
  • JavaScript – Browser Object Model

    The Browser Object Model (BOM) in JavaScript refers to the objects provided by the browsers to interact with them. By using these objects, you can manipulate the browser’s functionality. For example, you can get the browser history and window size, navigate to different URLs, etc.

    The Browser object model is not standardized. It depends on which browser you are using.

    Here, we have listed all objects of the Browser Object Model with descriptions −

    • Window − The ‘window’ object represents the current browser window. You can use it to manipulate the browser window.
    • Document − The ‘document’ object represents the currently opened web page in the browser window. You can use it to customize the property of the document.
    • Screen − It provides information about the user’s device’s screen.
    • History − It provides the browser’s session history.
    • Navigator − It is used to get the browser’s information like default language, etc.
    • Location − The Location object is used to get the URL information, such as the hostname of the current web page.
    • Console − The console object allows developers to access the browser’s console.

    JavaScript Window Object

    The JavaScript window object represents the browser’s window. We can use different methods and properties of the window object to manipulate current browser window. For example, showing an alert, opening a new window, closing the current window, etc.

    All the JavaScript global variables are properties of window object. All global functions are methods of the window object.

    The other objects listed above such as document, screen, history etc., are the properties of the window object. We can access these objects as properties of the window object. We can also access them with referencing the window object. Look at the below example snippet to access the document object

    window.document.write("Welcome to Tutorials Point");

    or without window object −

    document.write("Welcome to Tutorials Point");

    The innerHeight and innerWidth properties of the window object are used to access the height and width of the browser window. We will learn JavaScript window object in detail in next chapters.

    JavaScript Document Object

    The document object is a property of the JavaScript window object. The whole HTML document is represented as a document object. The document object forms HTML DOM. It is root node of the HTML document.

    The document object can be accessed as window.document or just document.

    The document object provides us with many properties and methods to access the HTML elements and manipulate them. One such method is document.getElementById() to access the HTML element using its id.

    We can access an element with id as “text” using getElementById() method and manipulate it

    Example

    <html><body><div id ="text">This text will be changed.</div><script>// Access the element with id as textconst textDiv = document.getElementById("text");// Change the content of this element
          textDiv.innerHTML ="The text of this DIV is changed.";</script></body></html>

    Output

    The text of this DIV is changed.
    

    JavaScript Screen Object

    In JavaScript, the screen object is a property of window object. It provides us with properties that can be used to get the information about the device window screen. We can access the screen object as window.screen or just screen.

    To get the width and height of the device screen in pixels we can use the screen.width and screen.height properties

    Example

    <html><body><div id ="width">Width of the device screen is </div><div id ="height">Height of the device screen is </div><script>
       document.getElementById("width").innerHTML += screen.width +" px.";
       document.getElementById("height").innerHTML += screen.height +" px.";</script><p> The above result may be different for different device.</p></body></html>

    Output

    Width of the device screen is 1536 px.
    Height of the device screen is 864 px.
    The above result may be different for different device.
    

    JavaScript History Object

    In JavaScript, the history object is also a property of the window object. It contains a list of the visited URLs in the current session. The history object provides an interface to manipulate the browser’s session history.

    The JavaScript history object can be accessed using window.history or just history. We can use the methods of history object to navigate the URLs in the history list. For example to go the previous page/URL in the history list, we can use history.back() method.

    JavaScript Navigator Object

    The JavaScript navigator object is also a property of the window object. Using the ‘navigator’ object, you can get the browser version and name and check whether the cookie is enabled in the browser. We can access the navigator object using window.navigator. We can also access it without using the window prefix.

    JavaScript Location Object

    The JavaScript ‘location‘ object contains various properties and methods to get and manipulate the information of the browser’s location, i.e. URL. It’s also a property of JavaScript window object.

    We can use the properties and methods of the location object to manipulate the URL information. For example, to get the host from the current URL, we can use the window.location.host or just location.host. The host is property of the location object.

    Example

    <html><body><div id ="output"></div><script>
          document.getElementById("output").innerHTML ="The host of the current location is: "+ location.host;</script></body></html>

    Output

    The host of the current location is: www.tutorialspoint.com
    

    JavaScript Console Object

    The JavaScript console object allows us to access the debugging console of the browser. It is a property of the JavaScript window object. It can be accessed using window.console or just console.

    The console object provides us with different methods such as console.log(). The console.log() method is used to display the message in debugging console.

    What’s Next?

    We have provided detailed information about each of the above objects in separate chapters.

  • JavaScript – Deleting Cookies

    In order to delete cookies with JavaScript, we can set the expires date to a past date. We can also delete a cookie using the max-age attribute. We can delete the cookies explicitly from the browser.

    Deleting cookies with JavaScript removes small bits of data that websites store on a user’s computer. Cookies are used to track a user’s browsing activity and preferences.

    It is important to note that deleting cookies can have unintended consequences. For example, if you delete a cookie that is used to authenticate you to a website, you will be logged out of the website. You should only delete cookies if you are sure that you want to do so.

    Different Ways to Delete the Cookies

    There are three different ways to delete the cookies −

    • Set the past expiry date to the ‘expires’ attribute.
    • Use the ‘max-age’ attribute.
    • Delete cookies explicitly from the browser.

    Delete Cookies using ‘expires’ Attribute

    When you set the past expiry date as a value of the ‘expires’ attribute, the browser automatically deletes the cookie.

    Syntax

    Follow the syntax below to delete a cookie by setting up the past expiry date as a value of the ‘expires’ attribute.

    document.cookie ="data1=test1;expires=Tue, 22 Aug 2023 12:00:00 UTC;";

    In the above syntax, we have set the past date as a value of the ‘expires’ attribute. You may set any past date.

    Example

    In the below code, you can click on the set cookies button to set cookies. After that, click on the get cookies button to observe the cookies.

    Next, click the delete cookies button, and again get cookies to check whether the cookies are deleted.

    Here, we delete the data1 cookie only.

    <html><body><button onclick ="setCookies()"> Set Cookie </button><button onclick ="deleteCookies()"> Delete Cookie </button><button onclick="readCookies()"> Read Cookies </button><p id ="output"></p><script>let output = document.getElementById("output");functionsetCookies(){
    		document.cookie ="data1=test1;";
    		document.cookie ="data2=test2;";}functiondeleteCookies(){
    		document.cookie ="data1=test1;expires=Tue, 22 Aug 2023 12:00:00 UTC;";
    		document.cookie ="data2=test2;expires=Mon, 22 Aug 2050 12:00:00 UTC;";}functionreadCookies(){const allCookies = document.cookie.split("; ");
    		output.innerHTML ="The cookie is : <br>";for(const cookie of allCookies){const[key, value]= cookie.split("=");if(key =="data1"|| key =="data2"){
    				output.innerHTML +=`${key} : ${decodeURIComponent(value)} <br>`;}}}</script></body></html>

    Delete Cookies using ‘max-age’ Attribute

    The browser automatically deletes the cookie when you assign 0 or a negative value to the ‘maxAge’ attribute.

    Syntax

    Follow the syntax below to use the max-age attribute to delete the cookie.

    document.cookie ="user1=sam;max-age=-60;";

    In the above syntax, we have set a negative value to the ‘max-age’ attribute to delete the cookies.

    Example

    In the below code, we delete the user1 cookie only in the deleteCookies() function.

    <html><body><button onclick ="setCookies()"> Set Cookie </button><button onclick ="deleteCookies()"> Delete Cookie </button><button onclick ="readCookies()"> Read Cookies </button><p id ="output"></p><script>let output = document.getElementById("output");functionsetCookies(){
    		document.cookie ="user1=sam;";
    		document.cookie ="user2=virat;";}functiondeleteCookies(){
    		document.cookie ="user1=sam;max-age=-60;";
    		document.cookie ="user2=virat;max-age=5000;";}functionreadCookies(){const allCookies = document.cookie.split("; ");
    		output.innerHTML ="The cookie is : <br>";for(const cookie of allCookies){const[key, value]= cookie.split("=");if(key =="user1"|| key =="user2"){
    				output.innerHTML +=`${key} : ${decodeURIComponent(value)} <br>`;}}}</script></body></html>

    Delete Cookies Explicitly from the Browser

    You can manually delete the cookies from the browser by following the steps below.

    Step 1 − In your browser, click on the three verticle dots at the top right corner. After that, hover over the ‘history, and it will open the menu. In the menu, click on the ‘history.

    Delete Cookies Step 1

    Step 2 − Here, click on the ‘clear browsing data’ tab.

    Delete Cookies Step 2

    Step 3 − Check the cookies and other site data check boxes here. After that, click on the ‘clear data’ button.

    Delete Cookies Step 3

    However, the steps might differ based on what browser you are using.

    This way, you can use any way among the three to clear your browser’s cookie.

  • JavaScript – Cookie Attributes

    Cookie Attributes

    The JavaScript cookie attributes are used to set additional information about a cookie such as path, domain, expiry date, etc. In JavaScript, you can specify the cookie attributes while setting up a new cookie or updating the cookie. For example, you can set the cookie’s expiry date using the ‘expires’ attributes.

    In simple terms, cookie attributes are used to control the behavior of the cookies and how the cookie is used in the browser.

    Here, we have listed all cookie attributes in the table below with its description.

    AttributeDescriptionDefault Value
    Name/ValueIt is used to store the cookies in the browser.
    DomainTo specify the domain for whose cookie is valid.Website of domain. For example, tutorialspoint.com
    PathThe path to the directory or web page that sets the cookie./ (entire domain)
    ExpiresIt is used to specify the date and time when the cookie should expire.Current session
    Max-AgeIt is used to specify the time limit after that cookie should expire.Current session
    SecureIf this field contains the word “secure”, then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists.false
    HttpOnlyIt prevents accessing the cookies via JavaScript to make cookies secure.false
    SameSiteIt is used to specify how third-party cookies should be handled.Lax
    PriorityIt defines the priority of the cookies.1000
    Site/ServiceTo get information about the origin site of the cookie.
    SourcePortTo get the port of the source for the cookie.
    StoragePartitionIt defines which storage partition is used to store cookies.
    SizeIt represents the size of the cookies.The size depends on the text length.

    However, above all, attributes are optional.

    Also, you can’t manipulate all attributes of the cookies. The browser sets some attributes.

    Check the Attribute Value in the Browser

    You can set the attributes to the cookie, but you can’t access the attributes. To check whether the attribute is set, you can use the browser console.

    Follow the steps below to check cookies in the browser console.

    Step 1 − Right click in the browser. It will open the menu. You need to select the ‘inspect’ option. It will open the developer tool.

    Cookie Attributes Step 1

    Step 2 − After that, you need to go to the Application/ Storage tab.

    Cookie Attributes Step 2

    Step 3 − In the sidebar, select ‘cookies.

    Cookie Attributes Step 3

    Step 4 − Now, click on any cookies to check their name, value, and other attribute values.

    Cookie Attributes Step 4

    The above steps are only for the Chrome web browser. The step can differ according to what browser you are using.

    Here, you will learn each attribute one by one with examples.

    Cookie’s Name/Value Attribute

    The Name attribute is used to store the cookie data. It takes the data as a value. If you want to use the special characters in the value of the ‘Name’ attribute, you need to encode the text using the encodeURIComponent() method.

    Syntax

    Follow the syntax below to set the Name attribute of the cookie.

    let value =encodeURIComponent(cookieValue);
    document.cookie ="name="+ value +";";

    In the above syntax, we have encoded the ‘cookieValue’ using the encodeURIComponent() method and used the encoded value as a name attribute value.

    Example

    In the below code, we set the ‘subscribed’ cookie with a ‘false’ value. You can click the read cookies button to get the cookies.

    <html><body><p id ="output"></p><button onclick ="setCookies()"> Set Cookie </button><br><br><button onclick ="readCookies()"> Read Cookies </button><script>let output = document.getElementById("output");functionsetCookies(){
    			document.cookie ="subscribed=false";// name-value pair
    			output.innerHTML ="Cookie setting successful!";}functionreadCookies(){const allCookies = document.cookie.split("; ");
    			output.innerHTML ="The subscribed cookie is - <br>";for(const cookie of allCookies){const[name, value]= cookie.split("=");if(name =="subscribed"){
    					output.innerHTML +=`${name} : ${decodeURIComponent(value)} <br>`;}}}</script></body></html>

    Cookie’s Path Attribute

    The Path attribute is used to set the scope of the cookie. It defines where cookies should be accessible on the website. You may set the relative or absolute path as a Path attribute value.

    If you set the relative path, all the cookies can be accessible everywhere in the particular or sub-directory.

    Syntax

    Follow the syntax below to set the Path attribute in the cookie.

    document.cookie ="name=value;path=pathStr";

    In the above syntax, you need to replace the ‘pathStr’ with the actual path string.

    Example

    In the below code, we set the path for the cookie. Here, we set the / (home route). So, cookies can be accessible on each webpage of the website. You may try to get the cookie on the different web pages of the website.

    <html><body><button onclick ="setCookies()"> Set Cookie </button><p id ="output"></p><button onclick ="readCookies()"> Read Cookies </button><script>let output = document.getElementById("output");functionsetCookies(){
    			document.cookie ="signIn=true; path=/";
    			output.innerHTML ="Cookie set successful!";}functionreadCookies(){const allCookies = document.cookie.split("; ");
    			output.innerHTML ="The cookie is : <br>";for(const cookie of allCookies){const[key, value]= cookie.split("=");if(key =="signIn"){
    					output.innerHTML +=`${key} : ${decodeURIComponent(value)} <br>`;}}}</script></body></html>

    Cookie Expires Attribute

    The ‘expires’ attribute is used to set the expiry date for the cookie. It takes the date string as a value.

    If you set 0 or past date as a value of the ‘expires, the browser will automatically delete the cookie.

    Syntax

    Follow the syntax below to set the expires attribute in the cookie.

    document.cookie ="name=value;expires=dateStr";

    In the above syntax, you need to replace the ‘dateStr’ with the date string.

    Example

    In the code below, we set the product cookie. Also, we set the expiry date in 2050.

    You may try to set the past expiry date and try to access the cookie. You won’t be able to find the cookie.

    <html><body><p id ="output"></p><button onclick ="setCookies()"> Set Cookie </button><br><br><button onclick ="readCookies()"> Read Cookies </button><script>let output = document.getElementById("output");functionsetCookies(){
    			document.cookie ="product=mobile;expires=12 Jan 2050 12:00:00 UTC";
    			output.innerHTML ="Cookie Set Successful!";}functionreadCookies(){const allCookies = document.cookie.split("; ");
    			output.innerHTML ="The cookie is : <br>";for(const cookie of allCookies){const[key, value]= cookie.split("=");if(key =="product"){
    					output.innerHTML +=`${key} : ${decodeURIComponent(value)} <br>`;}}}</script></body></html>

    Cookie’s maxAge Attribute

    The ‘maxAge’ attribute is an alternative to the ‘expires’ attribute. It is used to specify the lifetime of the cookie. It takes the seconds as a value.

    When the lifetime of the cookie is finished, it will automatically get deleted.

    Syntax

    Follow the syntax below to pass the ‘maxAge’ attribute to the cookie.

    document.cookie ="name=value;max-ge=age;";

    In the above syntax, you need to replace the ‘age’ with the number of seconds.

    Example

    In the below code, we set the total number of seconds equal to 10 days as a value of the maxAge attribute. You can set the lifetime of 1 second for the cookie and try to access the cookie after 1 second.

    <html><body><button onclick ="setCookies()"> Set Cookie </button><button onclick ="readCookies()"> Read Cookies </button><p id ="output"></p><script>const output = document.getElementById("output");functionsetCookies(){
    			document.cookie ="token=1234wfijdn;max-age=864000";}functionreadCookies(){const allCookies = document.cookie.split("; ");
    			output.innerHTML ="The cookie is : <br>";for(const cookie of allCookies){const[key, value]= cookie.split("=");if(key =="token"){
    					output.innerHTML +=`${key} : ${decodeURIComponent(value)} <br>`;}}}</script></body></html>

    Cookie Domain Attribute

    The domain attribute is used to specify the domain for which the cookie is valid. The default value of the domain from which you are making a request. You may set the domain attribute to set the subdomains.

    Syntax

    Follow the syntax below to set the value of the domain attribute in the cookie.

    document.cookie ="name=value;domain:domain_name ";

    In the above syntax, replace the ‘domain_name’ with the actual domain, like example.com.

    Example

    In the below code, we set the ‘tutorialspoint.com’ domain for the cookie.

    <html><body><p id ="output"></p><button onclick ="setCookies()"> Set Cookie </button><button onclick ="readCookies()"> Read Cookies </button><script>const output = document.getElementById("output");functionsetCookies(){
    			document.cookie ="username=abcd;domain:tutorialspoint.com";}functionreadCookies(){const allCookies = document.cookie.split("; ");
    			output.innerHTML ="The cookie is : <br>";for(const cookie of allCookies){const[key, value]= cookie.split("=");if(key =="username"){
    					output.innerHTML +=`${key} : ${decodeURIComponent(value)} <br>`;}}}</script></body></html>

    Similarly, you can also update the attribute values. For example, you can extend the expiry time of the cookie.

  • JavaScript and Cookies

    What are Cookies ?

    In JavaScript, cookies are piece of data stored in the user’s web browser. The cookies are stored in the key-value pair inside the browser. We can manipulate the cookies using cookie property of document object. We can set or store a cookie in key-value pair using the cookie property. We can read cookies using document’s cookie property and extract the desired information using destructuring.

    Why are Cookies needed?

    Web Browsers and Servers use HTTP protocol to communicate and HTTP is a stateless protocol. But for a commercial website, it is required to maintain session information among different pages.

    For example, you have logged in to a particular website on a particular web page. How do other webpages of the same website know your state that you have already completed the logged-in process? In this case, cookies are used.

    In many situations, using cookies is the most efficient method of remembering and tracking preferences, purchases, commissions, and other information required for better visitor experience or site statistics.

    Sometimes, cookies are also used for caching, increasing the website or application performance.

    How It Works ?

    Your server sends some data to the visitor’s browser in the form of a cookie. The browser may accept the cookie. If it does, it is stored as a plain text record on the visitor’s hard drive. Now, when the visitor arrives at another page on your site, the browser sends the same cookie to the server for retrieval. Once retrieved, your server knows/remembers what was stored earlier.

    Cookies are a plain text data record of 5 variable-length fields −

    • Expires − The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser.
    • Domain − The domain name of your site.
    • Path − The path to the directory or web page that set the cookie. This may be blank if you want to retrieve the cookie from any directory or page.
    • Secure − If this field contains the word “secure”, then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists.
    • Name=Value − Cookies are set and retrieved in the form of key-value pairs

    Cookies were originally designed for CGI programming. The data contained in a cookie is automatically transmitted between the web browser and the web server, so CGI scripts on the server can read and write cookie values that are stored on the client.

    Setting/ Storing Cookies

    JavaScript can manipulate cookies using the cookie property of the Document object. JavaScript can read, create, modify, and delete the cookies that apply to the current web page.

    The simplest way to create a cookie is to assign a string value to the document.cookie object, which looks like this.

    document.cookie ="key1 = value1;key2 = value2;expires = date";

    Here the expires attribute is optional. If you provide this attribute with a valid date or time, then the cookie will expire on a given date or time and thereafter, the cookies’ value will not be accessible.

    The cookie string contains the key-value pairs separated by the semi-colons.

    Note − Cookie values may not include semicolons, commas, or whitespace. For this reason, you may want to use the JavaScript escape() function to encode the value before storing it in the cookie. If you do this, you will also have to use the corresponding unescape() function when you read the cookie value.

    Example

    Try the following. It sets a customer name in an input cookie.

    <html><head><script type ="text/javascript">functionWriteCookie(){if( document.myform.customer.value ==""){alert("Enter some value!");return;}
                cookievalue =escape(document.myform.customer.value)+";";
                document.cookie ="name="+ cookievalue;
                document.write("Setting Cookies : "+"name="+ cookievalue );}</script></head><body><form name ="myform" action ="">
             Enter name:<input type ="text" name ="customer"/><input type ="button" value ="Set Cookie" onclick ="WriteCookie();"/></form></body></html>

    Output

    https://www.tutorialspoint.com/javascript/src/write_cookie.htm

    Now your machine has a cookie called name. You can set multiple cookies using multiple key = value pairs separated by comma.

    Reading Cookies

    Reading a cookie is just as simple as writing one, because the value of the document.cookie object is the cookie. So you can use this string whenever you want to access the cookie. The document.cookie string will keep a list of name=value pairs separated by semicolons, where name is the name of a cookie and value is its string value.

    You can use strings’ split() function to break a string into key and values as follows −

    Example

    Try the following example to get all the cookies.

    <html><head><script type ="text/javascript">functionReadCookie(){var allcookies = document.cookie;
                document.write("All Cookies : "+ allcookies );// Get all the cookies pairs in an array
                cookiearray = allcookies.split(';');// Now take key value pair out of this arrayfor(var i=0; i<cookiearray.length; i++){
                   name = cookiearray[i].split('=')[0];
                   value = cookiearray[i].split('=')[1];
                   document.write("Key is : "+ name +" and Value is : "+ value);}}</script></head><body><form name ="myform" action =""><p> click the following button and see the result:</p><input type ="button" value ="Get Cookie" onclick ="ReadCookie()"/></form></body></html>

    Note − Here length is a method of Array class which returns the length of an array. We will discuss Arrays in a separate chapter. By that time, please try to digest it.https://www.tutorialspoint.com/javascript/src/reading_cookies.htm

    Note − There may be some other cookies already set on your machine. The above code will display all the cookies set on your machine.

    Setting Cookies Expiry Date

    You can extend the life of a cookie beyond the current browser session by setting an expiration date and saving the expiry date within the cookie. This can be done by setting the expires attribute to a date and time.

    Example

    Try the following example. It illustrates how to extend the expiry date of a cookie by 1 Month.

    <html><head><script type ="text/javascript">functionWriteCookie(){var now =newDate();
                now.setMonth( now.getMonth()+1);
                cookievalue =escape(document.myform.customer.value)+";"
                
                document.cookie ="name="+ cookievalue;
                document.cookie ="expires="+ now.toUTCString()+";"
                document.write("Setting Cookies : "+"name="+ cookievalue );}</script></head><body><form name ="myform" action ="">
             Enter name:<input type ="text" name ="customer"/><input type ="button" value ="Set Cookie" onclick ="WriteCookie()"/></form></body></html>

    Output

    https://www.tutorialspoint.com/javascript/src/setting_cookies.htm

    Deleting a Cookie

    Sometimes you will want to delete a cookie so that subsequent attempts to read the cookie return nothing. To do this, you just need to set the expiry date to a time in the past.

    Example

    Try the following example. It illustrates how to delete a cookie by setting its expiry date to one month behind the current date.

    <html><head><script type ="text/javascript">functionWriteCookie(){var now =newDate();
                now.setMonth( now.getMonth()-1);
                cookievalue =escape(document.myform.customer.value)+";"
                   
                document.cookie ="name="+ cookievalue;
                document.cookie ="expires="+ now.toUTCString()+";"
                document.write("Setting Cookies : "+"name="+ cookievalue );}</script></head><body><form name ="myform" action ="">
             Enter name:<input type ="text" name ="customer"/><input type ="button" value ="Set Cookie" onclick ="WriteCookie()"/></form></body></html>

    Output

    https://www.tutorialspoint.com/javascript/src/deleting_cookies.htm

    Updating Cookies

    To update the particular key-value pair in the cookie, you can assign new key-value pair to the document.cookie property. Here, you need to ensure you are using the same key whose value you want to update.

    Syntax

    Follow the syntax below to update the cookies.

    document.cookie="key1=value1";

    In the above syntax, we are updating the value of the key cookie.

    Example

    In the code below, click the set cookies button to set the cookies. It will set the watch value for the cartItem and 10000 for the price.

    After that, you can click the get cookies button to observe the cookies.

    Next, you can click on the update cookies button to update the cookies. It will change the cartItem value to bag and the price to 5000.

    Now, click the get cookies button again to get the updated cookie value.

    <html><body><p id ="output"></p><button onclick ="setCookies()"> Set Cookie </button><br><br><button onclick ="updateCookies()"> Update Cookie </button><br><br><button onclick ="getCookies()"> Get Cookies </button><script>let output = document.getElementById("output");functionsetCookies(){
      document.cookie ="cartItem=watch";
      document.cookie ="price=10000";}functionupdateCookies(){// Updating cookies
      document.cookie ="cartItem=bag"; 
      document.cookie ="price=5000";}functiongetCookies(){//Spliting the cookie stringconst allCookies = document.cookie.split("; "); 
      output.innerHTML ="The cookie data are : <br>";for(const cookie of allCookies){const[key, value]= cookie.split("=");if(key =="cartItem"|| key =="price"){
           output.innerHTML +=`${key} : ${decodeURIComponent(value)} <br>`;}}}</script></body></html>

    Print Page

  • JavaScript – setInterval() Method

    JavaScript setInterval() Method

    In JavaScript, the setInterval() is a window method that is used to execute a function repeatedly at a specific interval. The setTimeout() Method allows you to execute the function only once after the specified time.

    The window object contains the setInterval() method. However, you can execute the setInterval() Method without taking the window object as a reference.

    Syntax

    Following is the syntax to use the setInterval() method in JavaScript

    setInterval(callback,interval, arg1, arg2,..., argN);

    The first two parameters are required others are optional.

    Parameters

    • Callback − It is a callback function that will be executed after every interval.
    • Interval − It is the number of milliseconds after the callback function should be executed.
    • Arg1, arg2, arg3, , argN − They are multiple arguments to pass to the callback function.

    Return Value

    The setInterval() method returns the numeric id.

    Example

    In the code below, the startTimer() function uses the setInterval() method to call the timer() function after every 1000 milliseconds.

    The timer() function increases the value of the second global variable every time it is called by the setInterval() method and prints the counter.

    You can click the button to start a timer in the output.

    <html><body><button onclick ="startTimer()">Start Timer</button><div id ="output"></div><script>let output = document.getElementById('output');var seconds =0;functionstartTimer(){setInterval(timer,1000);// Calls timer() function after every second}functiontimer(){// Callback function
             seconds++;
             output.innerHTML +="Total seconds are: "+ seconds +"<br>";}</script></body></html>

    Output

    JavaScript setInterval() Method

    Arrow Function with setInterval() Method

    The below example contains almost the same code as the above example. Here, we have passed the arrow function as a first argument of the setInterval() method rather than passing the function name only. You can click the button to start the timer.

    Example

    <html><body><button onclick ="startTimer()">Start Timer</button><div id ="output"></div><script>let output = document.getElementById('output');var seconds =0;functionstartTimer(){setInterval(()=>{
                seconds++;
                output.innerHTML +="Total seconds are: "+ seconds +"<br>";},1000);// Calls timer() function after every second}</script></body></html>

    Output

    Arrow Function with setInterval() Method

    Passing More than 2 Arguments to setInterval() Method

    In the code below, we have passed 3 arguments to the setInterval() method. The first argument is a callback function to print the date, the second argument is an interval, and the third argument will be passed to the callback function.

    Example

    <html><body><button onclick ="startTimer()">Start Date Timer</button><div id ="output"></div><script>let output = document.getElementById('output');var seconds =0;functionstartTimer(){let message ="The date and time is: ";setInterval(printDate,1000, message);}functionprintDate(message){let date =newDate();
             output.innerHTML += message + date +"<br>";}</script></body></html>

    Output

    Passing More than 2 Arguments to setInterval() Method

    The clearInterval() Method in JavaScript

    The JavaScript clearInterval() method is used to stop the code execution started using the clearItnerval() method.

    It takes the numeric id returned by the setInterval () method as an argument.

    Syntax

    Follow the syntax below to use the clearInterval() method.

    clearInterval(id);

    Here id is an id returned by the setInterval() method.

    Example

    In the code below, we have used the setInterval() method to show the number after incrementing by 10 and after each second.

    When the number becomes 50, we stop the timer using the clearInterval() method.

    <html><body><div id ="output"></div><script>let output = document.getElementById('output');let number =10;let id =setInterval(()=>{if(number ==50){clearInterval(id);
                output.innerHTML +="The time is stopped."}
             output.innerHTML +="The number is: "+ number +"<br>";
             number +=10;},1000);</script></body></html>

    Output

    The number is: 10
    The number is: 20
    The number is: 30
    The number is: 40
    The time is stopped.The number is: 50
    

    Real-time Use Case of the setInterval() Method

    In the above examples, we have printed the messages using the setInterval() method. In this section, we will see the real-time use cases of the setInterval() method.

    Here, we have listed some of the real-time use cases.

    • To refresh the date
    • For slideshow
    • For animation
    • To show the clock on the webpage
    • To update live cricket score
    • To update weather information
    • To run cron jobs

    Here are the real-time examples of the setInterval() method.

    Flipping the color of the HTML element after each interval

    In the code below, we flip the color of the <div> element after every second.

    We have defined the div element in the HTML body.

    In the <head> section, we have added the red and green classes. Also, we added the background color in the red and green classes.

    In JavaScript, we have passed the callback function as the first argument of the setInterval() method, which will be called after every 1000 milliseconds.

    We access the <div> element in the callback function using its id. After that, we check whether the classList of the <div> element contains the red class. If yes, we remove it and add the green class. Similarly, if classList contains the green class, we remove it and add the red class.

    This is how we are flipping the color of the <div> element using the setInterval() method.

    Example

    <html><head><style>.red {background-color: red;}.green {background-color: green;}
          #square {height:200px; width:200px;}</style></head><body><div>Using setInterval() method to flip the color of the HTML element after each interval</div><div id ="square"class="red"></div><script>let output = document.getElementById('output');setInterval(function(){let square = document.getElementById('square');if(square.classList.contains('red')){
                square.classList.remove('red');
                square.classList.add('green');}else{
                square.classList.remove('green');
                square.classList.add('red');}},1000);</script></body></html>

    Output

    Flipping color of HTML element after each interval

    Moving Animation Using the setInterval() Method

    In the code below, we create moving animation using the setInterval() method.

    We have created the two nested div elements. The outer div has the parent id, and the inner div has the child id. We have set dimensions for both div elements and position to relative.

    In JavaScript, we have initialized the left variable with 0. After that, we invoke the callback function of the setInterval() method after every 50 milliseconds.

    In each interval, we change the position of the <div> element by 5px, and when the left position becomes 450px, we stop the animation.

    Example

    <html><head><style>
          #parent {
             position: relative; 
             height:50px;
             width:500px;
             background-color: yellow;}
          #child {
             position: relative; 
             height:50px;
             width:50px;
             background-color: red;}</style></head><body><div id ="parent"><div id ="child"></div></div><script>let child = document.getElementById('child');let left =0;// Moving animation using the setInterval() methodsetInterval(()=>{if(left <450){
                left +=5;
                child.style.left = left +'px';}},50);</script></body></html>

    Output

    Moving Animation Using setInterval() Method

    You can also use the setInterval() method to run the particular code asynchronously.