0% found this document useful (0 votes)
8 views91 pages

Notes

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views91 pages

Notes

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 91

JavaScript Cookie Example

Example 1
Let's see an example to set and get a cookie.
1. <!DOCTYPE html>

2. <html>

3. <head>

4. </head>

5. <body>

6. <input type="button" value="setCookie" onclick="setCookie()">

7. <input type="button" value="getCookie" onclick="getCookie()">

8. <script>

9. function setCookie()
10. {
11. document.cookie="username=Duke Martin";
12. }
13. function getCookie()
14. {
15. if(document.cookie.length!=0)
16. {
17. alert(document.cookie);
18. }
19. else
20. {
21. alert("Cookie not available");
22. }
23. }
24. </script>

25.
26. </body>

27. </html>

Example 2
Here, we display the cookie's name-value pair separately.
1. <!DOCTYPE html>

2. <html>

3. <head>

4. </head>

5. <body>

6. <input type="button" value="setCookie" onclick="setCookie()">

7. <input type="button" value="getCookie" onclick="getCookie()">

8. <script>

9. function setCookie()
10. {
11. document.cookie="username=Duke Martin";
12. }
13. function getCookie()
14. {
15. if(document.cookie.length!=0)
16. {
17. var array=document.cookie.split("=");
18. alert("Name="+array[0]+" "+"Value="+array[1]);
19. }
20. else
21. {
22. alert("Cookie not available");
23. }
24. }
25. </script>

26.
27. </body>

28. </html>

Example 3
In this example, we provide choices of color and pass the selected color value to the cookie.
Now, cookie stores the last choice of a user in a browser. So, on reloading the web page, the
user's last choice will be shown on the screen.
1. <!DOCTYPE html>

2. <html>

3. <head>

4. </head>

5. <body>

6. <select id="color" onchange="display()">

7. <option value="Select Color">Select Color</option>

8. <option value="yellow">Yellow</option>

9. <option value="green">Green</option>

10. <option value="red">Red</option>

11. </select>

12. <script type="text/javascript">

13. function display()


14. {
15. var value = document.getElementById("color").value;
16. if (value != "Select Color")
17. {
18. document.bgColor = value;
19. document.cookie = "color=" + value;
20. }
21. }
22. window.onload = function ()
23. {
24. if (document.cookie.length != 0)
25. {
26. var array = document.cookie.split("=");
27. document.getElementById("color").value = array[1];
28. document.bgColor = array[1];
29. }
30. }
31.
32.
33. </script>

34. </body>

35. </html>

Cookie Attributes
JavaScript provides some optional attributes that enhance the functionality of cookies. Here, is
the list of some attributes with their description.

Attribu Description
tes

expires It maintains the state of a cookie up to the specified date and time.
max-age It maintains the state of a cookie up to the specified time. Here, time is given in
seconds.

path It expands the scope of the cookie to all the pages of a website.

domain It is used to specify the domain for which the cookie is valid.
Cookie expires attribute
The cookie expires attribute provides one of the ways to create a persistent cookie. Here, a date
and time are declared that represents the active period of a cookie. Once the declared time is
passed, a cookie is deleted automatically.
Let's see an example of cookie expires attribute.
1. <!DOCTYPE html>

2. <html>

3. <head>

4. </head>

5. <body>

6. <input type="button" value="setCookie" onclick="setCookie()">

7. <input type="button" value="getCookie" onclick="getCookie()">

8. <script>

9. function setCookie()
10. {
11. document.cookie="username=Duke Martin;expires=Sun, 20 Aug 2030 12:00:00
UTC";
12. }
13. function getCookie()
14. {
15. if(document.cookie.length!=0)
16. {
17. var array=document.cookie.split("=");
18. alert("Name="+array[0]+" "+"Value="+array[1]);
19. }
20. else
21. {
22. alert("Cookie not available");
23. }
24. }
25. </script>

26. </body>

27. </html>

Cookie max-age attribute


The cookie max-age attribute provides another way to create a persistent cookie. Here, time is
declared in seconds. A cookie is valid up to the declared time only.
Let's see an example of cookie max-age attribute.
1. <!DOCTYPE html>

2. <html>

3. <head>

4. </head>

5. <body>

6. <input type="button" value="setCookie" onclick="setCookie()">

7. <input type="button" value="getCookie" onclick="getCookie()">

8. <script>

9. function setCookie()
10. {
11. document.cookie="username=Duke Martin;max-age=" + (60 * 60 * 24 * 365) + ";"
12. }
13. function getCookie()
14. {
15. if(document.cookie.length!=0)
16. {
17. var array=document.cookie.split("=");
18. alert("Name="+array[0]+" "+"Value="+array[1]);
19. }
20. else
21. {
22. alert("Cookie not available");
23. }
24. }
25. </script>

26. </body>

27. </html>

Cookie path attribute


If a cookie is created for a webpage, by default, it is valid only for the current directory and
sub-directory. JavaScript provides a path attribute to expand the scope of cookie up to all the
pages of a website.

Cookie path attribute Example


Let's understand the path attribute with the help of an example.

Here, if we create a cookie for webpage2.html, it is valid only for itself and its sub-directory (i.e.,
webpage3.html). It is not valid for webpage1.html file.
In this example, we use path attribute to enhance the visibility of cookies up to all the pages.
Here, you all just need to do is to maintain the above directory structure and put the below
program in all three web pages. Now, the cookie is valid for each web page.
1. <!DOCTYPE html>

2. <html>

3. <head>

4. </head>

5. <body>

6. <input type="button" value="setCookie" onclick="setCookie()">

7. <input type="button" value="getCookie" onclick="getCookie()">

8. <script>

9. function setCookie()
10. {
11. document.cookie="username=Duke Martin;max-age=" + (60 * 60 * 24 * 365) +
";path=/;"
12. }
13. function getCookie()
14. {
15. if(document.cookie.length!=0)
16. {
17. var array=document.cookie.split("=");
18. alert("Name="+array[0]+" "+"Value="+array[1]);
19. }
20. else
21. {
22. alert("Cookie not available");
23. }
24. }
25. </script>

26. </body>
27. </html>

Cookie domain attribute


A JavaScript domain attribute specifies the domain for which the cookie is valid. Let's suppose if
we provide any domain name to the attribute such like:
1. domain=javatpoint.com
Here, the cookie is valid for the given domain and all its sub-domains.
However, if we provide any sub-domain to the attribute such like:
1. omain=training.javatpoint.com

Cookie with multiple Name-Value pairs


In JavaScript, a cookie can contain only a single name-value pair. However, to store more than
one name-value pair, we can use the following approach: -
ADVERTISEMENT

ADVERTISEMENT

○ Serialize the custom object in a JSON string, parse it and then store in a cookie.

○ For each name-value pair, use a separate cookie.

Examples to Store Name-Value pair in a Cookie


Example 1
Let's see an example to check whether a cookie contains more than one name-value pair.
1. <!DOCTYPE html>

2. <html>

3. <head>

4. </head>

5. <body>

6. Name: <input type="text" id="name"><br>

7. Email: <input type="email" id="email"><br>

8. Course: <input type="text" id="course"><br>


9. <input type="button" value="Set Cookie" onclick="setCookie()">

10. <input type="button" value="Get Cookie" onclick="getCookie()">

11. <script>

12. function setCookie()


13. {
14. //Declaring 3 key-value pairs
15. var info="Name="+
document.getElementById("name").value+";Email="+document.getElementById("email
").value+";Course="+document.getElementById("course").value;
16. //Providing all 3 key-value pairs to a single cookie
17. document.cookie=info;
18. }
19.
20. function getCookie()
21. {
22. if(document.cookie.length!=0)
23. {
24. //Invoking key-value pair stored in a cookie
25. alert(document.cookie);
26. }
27. else
28. {
29. alert("Cookie not available")
30. }
31. }
32. </script>

33. </body>

34. </html>
Output:

Test it Now

On clicking Get Cookie button, the below dialog box appears.

Here, we can see that only a single name-value is displayed.


However, if you click, Get Cookie without filling the form, the below dialog box appears.

Example 2
Let's see an example to store different name-value pairs in a cookie using JSON.
1. <!DOCTYPE html>

2. <html>

3. <head>

4. </head>

5. <body>

6. Name: <input type="text" id="name"><br>

7. Email: <input type="email" id="email"><br>

8. Course: <input type="text" id="course"><br>

9. <input type="button" value="Set Cookie" onclick="setCookie()">

10. <input type="button" value="Get Cookie" onclick="getCookie()">

11.
12. <script>

13. function setCookie()


14. {
15. var obj = {};//Creating custom object
16. obj.name = document.getElementById("name").value;
17. obj.email = document.getElementById("email").value;
18. obj.course = document.getElementById("course").value;
19.
20. //Converting JavaScript object to JSON string
21. var jsonString = JSON.stringify(obj);
22.
23. document.cookie = jsonString;
24. }
25. function getCookie()
26. {
27. if( document.cookie.length!=0)
28. {
29. //Parsing JSON string to JSON object
30. var obj = JSON.parse(document.cookie);
31.
32. alert("Name="+obj.name+" "+"Email="+obj.email+" "+"Course="+obj.course);
33. }
34. else
35. {
36. alert("Cookie not available");
37. }
38. }
39. </script>

40. </body>

41. </html>
Test it Now

Output:

On clicking Get Cookie button, the below dialog box appears.


Here, we can see that all the stored name-value pairs are displayed.

Example 3
Let's see an example to store each name-value pair in a different cookie.
1. <!DOCTYPE html>

2. <html>

3. <head>

4. </head>

5. <body>

6. Name: <input type="text" id="name"><br>

7. Email: <input type="email" id="email"><br>

8. Course: <input type="text" id="course"><br>

9. <input type="button" value="Set Cookie" onclick="setCookie()">

10. <input type="button" value="Get Cookie" onclick="getCookie()">

11.
12. <script>

13. function setCookie()


14. {
15. document.cookie = "name=" + document.getElementById("name").value;
16. document.cookie = "email=" + document.getElementById("email").value;
17. document.cookie = "course=" + document.getElementById("course").value;
18. }
19. function getCookie()
20. {
21. if (document.cookie.length != 0)
22. {
23. alert("Name="+document.getElementById("name").value+"
Email="+document.getElementById("email").value+"
Course="+document.getElementById("course").value);
24. }
25. else
26. {
27. alert("Cookie not available");
28. }
29. }
30. </script>

31. </body>

32. </html>

Output:

Test it Now

On clicking Get Cookie button, the below dialog box appears.


Here, also we can see that all the stored name-value pairs are displayed.

Deleting a Cookie in JavaScript


In the previous section, we learned the different ways to set and update a cookie in JavaScript.
Apart from that, JavaScript also allows us to delete a cookie. Here, we see all the possible ways
to delete a cookie.

Different ways to delete a Cookie


These are the following ways to delete a cookie:
ADVERTISEMENT

○ A cookie can be deleted by using expire attribute.

○ A cookie can also be deleted by using max-age attribute.

○ We can delete a cookie explicitly, by using a web browser.

Examples to delete a Cookie


Example 1
In this example, we use expire attribute to delete a cookie by providing expiry date (i.e. any past
date) to it.
1. <!DOCTYPE html>

2. <html>

3. <head>

4. </head>

5. <body>

6.
7. <input type="button" value="Set Cookie" onclick="setCookie()">

8. <input type="button" value="Get Cookie" onclick="getCookie()">

9. <script>

10. function setCookie()


11. {
12. document.cookie="name=Martin Roy; expires=Sun, 20 Aug 2000 12:00:00 UTC";
13.
14. }
15. function getCookie()
16. {
17. if(document.cookie.length!=0)
18. {
19. alert(document.cookie);
20. }
21. else
22. {
23. alert("Cookie not avaliable");
24. }
25. }
26. </script>

27. </body>

28. </html>

Example 2
In this example, we use max-age attribute to delete a cookie by providing zero or negative
number (that represents seconds) to it.
1. <!DOCTYPE html>

2. <html>

3. <head>

4. </head>

5. <body>

6.
7. <input type="button" value="Set Cookie" onclick="setCookie()">
8. <input type="button" value="Get Cookie" onclick="getCookie()">

9. <script>

10. function setCookie()


11. {
12. document.cookie="name=Martin Roy;max-age=0";
13. }
14. function getCookie()
15. {
16. if(document.cookie.length!=0)
17. {
18. alert(document.cookie);
19. }
20. else
21. {
22. alert("Cookie not avaliable");
23. }
24. }
25.
26. </script>

27. </body>

28. </html>

Example 3
Let's see an example to set, get and delete multiple cookies.
1. <!DOCTYPE html>

2. <html>

3. <head>

4. </head>
5. <body>

6.
7. <input type="button" value="Set Cookie1" onclick="setCookie1()">

8. <input type="button" value="Get Cookie1" onclick="getCookie1()">

9. <input type="button" value="Delete Cookie1" onclick="deleteCookie1()">

10. <br>

11. <input type="button" value="Set Cookie2" onclick="setCookie2()">

12. <input type="button" value="Get Cookie2" onclick="getCookie2()">

13. <input type="button" value="Delete Cookie2" onclick="deleteCookie2()">

14. <br>

15. <input type="button" value="Display all cookies" onclick="displayCookie()">

16.
17. <script>

18. function setCookie1()


19. {
20. document.cookie="name=Martin Roy";
21. cookie1= document.cookie;
22. }
23. function setCookie2()
24. {
25. document.cookie="name=Duke William";
26. cookie2= document.cookie;
27. }
28.
29. function getCookie1()
30. {
31. if(cookie1.length!=0)
32. {
33. alert(cookie1);
34. }
35. else
36. {
37. alert("Cookie not available");
38. }
39. }
40.
41. function getCookie2()
42. {
43. if(cookie2.length!=0)
44. {
45. alert(cookie2);
46. }
47. else
48. {
49. alert("Cookie not available");
50. }
51. }
52.
53. function deleteCookie1()
54. {
55. document.cookie=cookie1+";max-age=0";
56. cookie1=document.cookie;
57. alert("Cookie1 is deleted");
58. }
59.
60. function deleteCookie2()
61. {
62. document.cookie=cookie2+";max-age=0";
63. cookie2=document.cookie;
64. alert("Cookie2 is deleted");
65. }
66.
67. function displayCookie()
68. {
69. if(cookie1!=0&&cookie2!=0)
70. {
71. alert(cookie1+" "+cookie2);
72. }
73. else if(cookie1!=0)
74. {
75. alert(cookie1);
76. }
77. else if(cookie2!=0)
78. {
79. alert(cookie2);
80. }
81. else{
82. alert("Cookie not available");
83. }
84.
85. }
86.
87. </script>

88. </body>

89. </html>

Example 4
Let's see an example to delete a cookie explicitly.
1. <!DOCTYPE html>

2. <html>

3. <head>

4. </head>

5. <body>

6.
7. <input type="button" value="Set Cookie" onclick="setCookie()">

8. <input type="button" value="Get Cookie" onclick="getCookie()">

9. <script>

10. function setCookie()


11. {
12. document.cookie="name=Martin Roy";
13.
14. }
15. function getCookie()
16. {
17. if(document.cookie.length!=0)
18. {
19. alert(document.cookie);
20. }
21. else
22. {
23. alert("Cookie not avaliable");
24. }
25. }
26. </script>

27. </body>

28. </html>

After clicking Set Cookie once, whenever we click Get Cookie, the cookies key and value is
displayed on the screen.

To delete a cookie explicitly, follow the following steps:

○ Open Mozilla Firefox.

○ Click Open menu - Library - History - Clear Recent History - Details.

JavaScript Window open method


JavaScript offers in-built methods to open and close the browser window to perform additional
operations like robot window etc. These methods help to open or close the browser window
pop-ups. Following are the window methods:

○ open()
○ close()

The window.open method is used to open a new web page into a new window and window.close
method to close web page opened by window.open method. See the window.open() method in
detail:

Window.open()
It is a pre-defined window method of JavaScript used to open the new tab or window in the
browser. This will depend on your browser setting or parameters passed in the window.open()
method that either a new window or tab will open.

This method is supported by almost all popular web browsers, like Chrome, Firefox, etc.
Following is the syntax and parameters of the window open method -

Syntax
This function accepts four parameters, but they are optional.

1. window.open(URL, name, specs, replace);

Or

You can also use this function without using the window keyword as shown below:

1. open(URL, name, specs, replace)

There is no difference between both syntaxes.

Parameters List
Below is the parameters list of window.open() method. Note that - all parameters of this method
are optional and works differently.

URL: This optional parameter of the window.open() function contains the URL string of a
webpage, which you want to open. If you do not specify any URL in this function, it will open a
new blank window (about:blank).

name: Using this parameter, you can set the name of the window you are going to open. It
supports the following values:
_ Passed URL will load into a new tab/window.

_ URL will load into the parent window or frame that is already opened.

_ By passing this parameter, the URL will replace the previous output and a new
window will open in the same frame.

_ URL replaces any frameset that can be loaded.

N Provide the name of the new window to show the text or any data on it. (Note - not
the title of the window)
The above-specified values are passed inside a single or double quote to the window.open()
function at the name parameter place.

specs: This parameter contains the settings that are separated by the comma. Element used in this
parameter cannot have whitespaces, e.g., width=150,height=100.

It supports several values.

replace: Like the other parameters of window.open() method, this is also an optional parameter.
It either creates a new entry or replaces the current entry in history list. It supports two Boolean
values; this means that it returns either true or false:

Tr Return true if URL replaces the current entry or document in history list.
u
e

Fa Return false if URL creates a new entry in history list.


l
s
e
Return Values
It will return a newly opened window.

Examples
Here are some examples of window.open() function to open the browser window/tab. By default,
the specified URL opens in new tab or window. See the examples below:

1. open() with URL parameter

This is a simple example of window open method having a website URL inside it. We have used
a button. By clicking on this button, window.open() method will call and open the website in
new browser tab.

Copy Code

1. <html>

2. <body>

3. Click the button to open new window <br><br>

4. <button onclick="window.open('https://www.javatpoint.com')"> Open Window


</button>
5.
6. </body>

7. </html>

Test it Now

Or

This code can be written as given below -

Copy Code

1. <html>

2. <body>

3. <script>

4. function openWindow() {
5. window.open('https://www.javatpoint.com');
6. }
7. </script>

8.
9. Click the button to open new window <br><br>

10. <button onclick="openWindow()"> Open Window </button>

11. </body>

12. </html>

Test it Now

Output

When you click on this Open Window button, javatpoint site will open in a new tab inside the
same window.

See the screenshot below:


2. open() without parameters

In this example, we will not pass any parameter to window.open() function so that the new tab
will open in previous window.

Copy Code

1. <html>

2. <body>

3. <script>

4. function openWindow() {
5. window.open();
6. }
7. </script>

8.
9. Click the button to open new window <br><br>

10. <button onclick="openWindow()"> Open Window </button>


11. </body>

12. </html>

Test it Now

Output

When you will execute the above code, a button will appear with it.

When you click this Open Window button, a blank window will open in a new tab.

3. open() with name parameters

In this example, we will specify the _parent at the name parameter. You can pass any of these
values (_parent, _blank, _top, etc.) in it.

Copy Code

1. <html>

2. <script>

3. function openWindow() {
4. window.open('https://gmail.com', '_parent');
5. }
6. </script>

7.

8. <body>
9. <b> Click the button to open new window in same tab </b>

10. <br><br>

11. <button onclick="openWindow()"> Open Window </button>

12. </body>

13. </html>

Test it Now

Output

Execute the code and get the output as given below. This will contain a button to click and open
the new URL on the same parent window.

When you click this button, Gmail will open under the same parent window.
When you will pass the different values in second parameter, you will see the difference for
different values.

4. Define the size for the new window

In this example, we will specify the height and width for the new window. For this, we will use
the third parameter (specs) in window.open() method and pass the height and width of the
window separated by a comma to this function. So, the window will open in the specified size.

Copy Code

1. <html>

2. <script>

3. function openWindow() {
4. window.open("", "", "width=300,height=200");
5. }
6. </script>

7.
8. <body>

9. <b> Click the button to open new window in same tab </b>

10. <br><br>

11. <button onclick="openWindow()"> Open Window </button>

12. </body>

13. </html>

Test it Now

Output

Execute the above code and get the output as given below. This will contain a button to click and
open the new URL on the same parent window.
When you click this button, a new blank window will open under the parent window of size.

Note that you can also pass the URL to the window.open() method to
open any website.
Open new window with a name and having a message
We can show any user-defined text or form in new window that we are going to open on button
click. For this, we need to provide any name to the new window and write some text into it. This
name will pass to the window.open() method. See the code below how it will implement with
actual coding.

Copy Code

1. <html>

2. <script>

3. function openWindow() {
4. var newtab = window.open("", "anotherWindow", "width=300,height=150");
5. newtab.document.write("<p> This is 'anotherWindow'. It is 300px wide and 150px tall
new window! </p>");
6. }
7. </script>

8.
9. <body>

10. <b> Click the button to open the new user-defined sized window </b>

11. <br><br>

12. <button onclick="openWindow()"> Open Window </button>

13. </body>

14. </html>

Test it Now

Output

Execute the code and get the output as given below. It will contain a button to click and open the
new URL on the same parent window.

When you click this button, a new window will open with a user-defined message under the
parent window of size 300*150.
JavaScript also offers the in-built method, i.e., close() to close the browser window.

Close the window opened by window.open()


In this example, we will show you how to close the window or tab opened by the window.open()
method. Firstly, we will open a website URL in a new window (size defined in code) using a
button click and then use another button to close that opened window. See the below code how it
will be done:

Copy Code

1. <html>

2. <head>

3. <title> Open and close window method example </title>

4. <script>

5. // function to open the new window tab with specified size


6. function windowOpen() {
7. var newWindow = window.open(
8. "https://www.javatpoint.com/", "_blank", "width=500, height=350");
9. }
10.
11. // function to close the window opened by window.open()
12. function windowClose() {
13. newWindow.close();
14. }
15. </script>

16. </head>

17.
18. <center>

19. <h2 style="color:green"> Window open() and close() method </h2>

20. <body>
21. <b> Click the button to open Javatpoint tutorial site </b><br>

22. <button onclick="windowOpen()"> Open Javatpoint </button>

23. <br><br>

24. <b> Click the button to close Javatpoint tutorial site </b><br>

25. <button onclick="windowClose()"> Close Javatpoint </button>

26. </body>

27. </center>

28. </html>

Test it Now

Output

When you will execute the code, you will get the response as shown below:

Click the Open Javatpoint button to open the Javatpoint tutorial website. We have specified the
size (height and width) of the new pop-up window to open.

○ Here we can see a Cookies checkbox which is already marked. Now, click Clear Now to
delete the cookies explicitly.

Now, on clicking Get Cookie, the below dialog box appears.


JavaScript Window close method
JavaScript provides an in-built function named close() to close the browser window that is
opened by using window.open() method. Unlike the window.open() method, it does not contain
any parameter. This window.close() method simply close the window or tab opened by the
window.open() method.
Remember that - You have to define a global JavaScript variable to hold the value returned by
window.open() method, which will be used later by the close() method to close that opened
window.

Syntax
1. window.close()
Here, window is the name of that window that is opened by the window open method.

Parameters List
This method does not have any parameters.

AClose the window


Let's understand with the help of an example. We will take an example to show you how to close
the window or tab opened by the window.open() method.
Firstly, we will open a website URL in a new window (size defined in code) using a button click
and then use another button to close that opened window.
Example
In this example, we will not specify any URL in open() method. See the below code how it will
work:
Copy Code
1. <html>

2. <script>

3. var newWindow;
4.
5. function openWindow() {
6. newWindow = window.open("", "myWindow", "width=200,height=100");
7. newWindow.document.write("<p>It is my 'newWindow'</p>");

8. }
9.
10. function closeWindow() {
11. newWindow.close();
12. }
13. </script>

14. <h3 style="color:brown"> Close Window Example </h3>

15. <body>

16. <button onclick="openWindow()">Open New Window</button>

17. <br><br>

18. <button onclick="closeWindow()">Close New Window </button>

19. </body>

20. </html>
Test it Now

Output
You will get the output same as the given below. Here, clicks the Open New Window button to
open a user-defined browser window.
A new window will pop-up with a message, as shown below. Now, click the Close New
Window button to close this pop-up window.

Example 2
This example will have a website URL inside the window.open() method to open a website in a
new window. Then we will use close() method to close that window.
Copy Code
1. <html>

2. <head>

3. <title> Open and close window method example </title>

4. <script>

5. var newWindow;
6. // function to open the new window tab with specified size
7. function windowOpen() {
8. newWindow = window.open(
9. "https://www.javatpoint.com/", "_blank", "width=500, height=350");
10. }
11.
12. // function to close the window opened by window.open()
13. function windowClose() {
14. newWindow.close();
15. }
16. </script>

17. </head>

18.
19. <center>

20. <h2 style="color:green"> Window open() and close() method </h2>

21. <body>

22. <b> Click the button to open Javatpoint tutorial site </b><br>

23. <button onclick="windowOpen()"> Open Javatpoint </button>

24. <br><br>

25. <b> Click the button to close Javatpoint tutorial site </b><br>

26. <button onclick="windowClose()"> Close Javatpoint </button>

27. </body>

28. </center>

29. </html>
Test it Now

Output
When you will execute the code, you will get the response as shown below:
Click the Open Javatpoint button to open the Javatpoint tutorial website. We have specified the
size (height and width) of the new pop-up window to open.

If you click the Close Javatpoint button, this opened window will be minimized.
ADVERTISEMENT

Browser Support
Several web browsers support this window function, such as:
ADVERTISEMENT

○ Chrome

○ Mozilla Firefox

○ Internet Explorer (IE)

○ Opera

○ Safari, etc.

You can run window.close() JavaScript function on these above browsers

Window Location in JavaScript


Window.location is used to provide a Location object with details about the document's current
location. This Location object reflects the location (URL) of the object it's linked to, i.e., it holds
information about the current content location (host, href, etc.)

JavaScript Location Object


The window.location attribute represents the URL of the page being displayed in that window.
Since the window is at the top of the scope chain, window.location properties can be accessed
without the window prefix. Using the window object's location attribute, you may get the page's
URL, hostname, protocol, etc.

Javascript window.location.href property


ADVERTISEMENT

○ The href attribute on the location object contains the current webpage's URL.

○ By modifying the href property, a user can go to a new URL or page.

○ It adds an item to the history list (so that when the user clicks "Back," they can return to
the current page).

○ Updating the href attribute is faster andeasier than using the assign() function.

○ The calling function is slower than accessing the property.

Syntax:
Backward Skip 10s
Play Video

Forward Skip 10s


ADVERTISEMENT

The following syntax shows javascript windows.href.location working procedure.


1. window.location.href = 'https://www.javatpoint.com';

○ The "window.location.href " function is used to display the current URL path. We can see
the path of the website and html file.

Examples
The following examples show the href value of the location of the window using the javascript
method.
Example1
The following example shows the file path on the running browser. We can see the URL link of
the location of the windows using the "innerHTML" function.
1. <!DOCTYPE html>

2. <html>

3. <body>

4. <h3> JavaScript function </h3>

5. <h4> The javascript window.location.href object </h4>

6. <p id = "value"> </p>

7. <script>

8. document.getElementById("value").innerHTML =
9. "The full windows href URL of the page is:<br>" + window.location.href;
10. </script>

11. </body>

12. </html>

Output
ADVERTISEMENT

ADVERTISEMENT

The given output shows the current url link.


Example2
The following example shows the file path on the running browser. It shows the current href link
using the onclick function and buttons. We can see the URL link using the alert box.
1. <!DOCTYPE html>

2. <html>

3. <body>

4. <h3> JavaScript function </h3>

5. <h4> The javascript window.location.href object </h4>

6. <button onclick = "getLocation()">

7. Get Href URL


8. </button>

9. <script>

10. function getLocation() {


11. // Get the current location
12. var location_var = window.location.href;
13. alert(location_var);
14. }
15. </script>

16. </body>

17. </html>

Output
The given output shows the current href link using the javascript function.
Output1

Output2

JavaScript location properties


We can use windows location properties using the JavaScript function. We can get the path,
filename, port number and other files and url related information. We can see multiple functions
or methods to get location property as per user requirement.

○ Location.protocol

The Javascript location.protocolis used to show the protocol scheme of the given URL, including
the final colon (:) symbol. The 'http:' and 'https:' are examples of the location protocol in
javascript.
Syntax
ADVERTISEMENT

The below syntax is utilized for the return protocol of the url.
1. window.location.protocol

○ The website name or file path name is the required protocol, and this syntax is used to
display the protocol.

Example
ADVERTISEMENT
The following example shows other properties of the JavaScript location protocol.
1. <!DOCTYPE html>

2. <html lang="en">

3. <head>

4. <meta charset="utf-8">

5. <title>JavaScript Location property </title>

6. </head>

7. <body>

8. <h2> JavaScript Location protocol </h2>

9. <input type = "button" value = "Load new document" onclick = "newDocument()">

10. <p id = "value"></p>

11. <script>

12. function newDocument() {


13. // Prints protocol such as http: or https:
14. document.getElementById("value").innerHTML ="URL Path:+window.location.protocol
+ "<br>";
15. }
16. </script>

17. </body>

18. </html>

Output
The given output shows the url properties value.
○ JavaScript location host and hostname property

The Javascript location.hostis displayed as the required or available host number. The Javascript
location.hostname is used to get the required or available hostname.
The "localhost:8080" is an example of the location host of the URL. The "www.javatpoint.com "
is an example of the local hostname.
Syntax
The below syntax is used to return the host value.
1. window.location.host
The below syntax is used to return the hostname.
1. window.location.hostname

○ The simple syntax is worked to show localhost of the file path or url.

○ The website name or file path name is displayed as a hostname.

Example
The following example is displayed the JavaScript location hostname.
1. <!DOCTYPE html>

2. <html lang="en">

3. <head>

4. <meta charset="utf-8">

5. <title> JavaScript Location hostname property </title>

6. </head>

7. <body>

8. <h2> JavaScript Location host and hostname </h2>

9. <input type = "button" value = "Load new document" onclick = "newDocument()">

10. <p id = "value"></p>

11. <p id = "value1"></p>

12. <script>

13. function newDocument() {


14. // Prints host with a usable port such as a localhost:8080
15. document.getElementById("value").innerHTML = " URL host with port: "
+window.location.host + "<br>";
16. // Prints hostname such as a www.javatpoint.com
17. document.getElementById("value1").innerHTML = " URL hostname with port: "
+window.location.hostname + "<br>";
18. }
19. </script>

20. </body>

21. </html>

Output
The given output shows the url properties value.

○ JavaScript location port

The Javascript location.port shows the port number of the available URL. The 8080 or 8085 is an
example of a windows location port.
ADVERTISEMENT

Syntax
The below syntax is used to show the location port of the url.
1. window.location.port
Example
The following example is displayed the JavaScript location hostname.
1. <!DOCTYPE html>
2. <html lang="en">

3. <head>

4. <meta charset="utf-8">

5. <title> JavaScript Location property </title>

6. </head>

7. <body>

8. <h2> JavaScript Location port </h2>

9. <input type = "button" value = "Load new document" onclick = "newDocument()">

10. <p id = "value"></p>

11. <script>

12. function newDocument() {


13. // Prints port number, e.g. 8080
14. document.getElementById("value").innerHTML = " URL port: " +window.location.port+
"<br>";
15. }
16. </script>

17. </body>

18. </html>

Output
The given output shows the url properties value.
ADVERTISEMENT

○ Location.pathname
The Javascript location.pathnameincludes an initial'/'followed by the given path of the URL. The
"/js/index.html" is an example of the location pathname.
Syntax
The below syntax and return values are displayed as the path value.
1. window.location.pathname
Example
The following example is displayed the JavaScript location pathname.
1. <!DOCTYPE html>

2. <html lang="en">

3. <head>

4. <meta charset="utf-8">

5. <title> JavaScript Location property </title>

6. </head>

7. <body>

8. <h2> JavaScript Location Path </h2>

9. <input type = "button" value = "Load new document" onclick = "newDocument()">

10. <p id = "value"></p>

11. <script>

12. function newDocument() {


13. document.getElementById("value").innerHTML = " Path: "
+window.location.pathname + "<br>";
14. }
15. </script>

16. </body>

17. </html>

Output
The given output shows the url properties value.
○ Location.hash

The Javascript location.hash gives a given string. It contains a '#' followed by the fragment
identifier of the available URL.
Syntax
The given syntax is used to show the hash included in the url.
1. window.location.hash
Example
The following example is displayed the JavaScript location pathname.
1. <!DOCTYPE html>

2. <html lang="en">

3. <head>

4. <meta charset="utf-8">

5. <title> JavaScript Location property </title>

6. </head>

7. <body>

8. <h2> JavaScript Location Hash</h2>

9. <p><a id="jtp"
href="file:///G:/writing%20stuff/content-writing/JavaTpoint/2022/nov/file.html#seee_has
h_data">
10. JavaScript Location Hash
11. </a><p>

12. <p id="value"></p>

13. <script>
14. let url_data = document.getElementById("jtp");
15. document.getElementById("value").innerHTML = "The Hash data of the URL is: " +
url_data.hash;

16. </script>

17. </body>

18. </html>

Output
The given output shows the url properties value.

○ Location.origin

The Javascript location.origin is a string that includes the canonical form of the origin of the
specific location.
The http://localhost:8080 is the demo example of the javascript location by default.
Example
The following example is displayed the JavaScript location's origin format.
1. <!DOCTYPE html>

2. <html lang="en">

3. <head>

4. <meta charset="utf-8">

5. <title> JavaScript Location property </title>

6. </head>

7. <body>

8. <h2> JavaScript Location Origin </h2>

9. <input type = "button" value = "Load new document" onclick = "newDocument()">


10. <p id = "value"></p>

11. <script>

12. function newDocument() {


13. document.getElementById("value").innerHTML = "Origin: "
+window.location.origin + "<br>";
14. }
15. </script>

16. </body>

17. </html>

Output
The given output shows the url properties value.

○ Location.username

The Javascript location.username is a string that includes the username before the domain name.
The "url.username" is used to get the predefined URL value's username using javascript.
Example
The following example is displayed the JavaScript location username.
1. <!DOCTYPE html>

2. <html lang="en">

3. <head>

4. <meta charset="utf-8">

5. <title> JavaScript Location property </title>

6. </head>
7. <body>

8. <h2> JavaScript Location Username</h2>

9. <p><a id="jtp" href="https://javatpoint:[email protected]">

10. JavaScript Location property


11. </a><p>

12. <p id="value"></p>

13. <script>

14. let url_data = document.getElementById("jtp");


15. document.getElementById("value").innerHTML = "The Username of the URL is: " +
url_data.username;
16. </script>

17. </body>

18. </html>

Output
The given output shows the url properties value.

○ Location.password

The Javascript location.password is a string that shows the password specified before the domain
name.
Example
The following example is displayed the JavaScript location password.
1. !DOCTYPE html>

2. <html lang="en">
3. <head>

4. <meta charset="utf-8">

5. <title> JavaScript Location property </title>

6. </head>

7. <body>

8. <h2> JavaScript Location Password</h2>

9. <p><a id="jtp" href="https://javatpoint:[email protected]">

10. JavaScript Location property


11. </a><p>

12. <p id="value"></p>

13. <script>

14. let url_data = document.getElementById("jtp");


15. document.getElementById("value").innerHTML = "The password of the URL is: " +
url_data.password;
16. </script>

17. </body>

18. </html>

Output
The given output shows the url properties value.

○ Location.search

The Javascript location.searchis a string which shows the query string of the given URL:
"?type=listing&answer=no"
Example
The following example is displayed the JavaScript location password.
1. <!DOCTYPE html>

2. <html lang="en">

3. <head>

4. <meta charset="utf-8">

5. <title> JavaScript Location property </title>

6. </head>

7. <body>

8. <h2> JavaScript Location Search</h2>

9. <p><a id="jtp" href="https://javatpoint:[email protected]/?yes">

10. JavaScript Location property


11. </a><p>

12. <p id="value"></p>

13. <script>

14. let url_data = document.getElementById("jtp");


15. document.getElementById("value").innerHTML = "The Location search of the URL is: "
+ url_data.search;
16. </script>

17. </body>

18. </html>

Output
The given output shows the url properties value.
Location properties Examples
The following example shows all properties of the JavaScript location. Here, we can see all the
location properties of the file path using the javascript function.
1. <!DOCTYPE html>

2. <html lang="en">

3. <head>

4. <meta charset="utf-8">

5. <title>JavaScript Location property </title>

6. </head>

7. <body>

8. <h2> JavaScript Location property </h2>

9. <h3> The window.location assign object </h3>

10. <input type = "button" value = "Load new document" onclick = "newDocument()">

11. <script>

12. function newDocument() {


13. // Prints complete file URL
14. document.write(" full url path: " +window.location.href + "<br>");

15. // Prints protocol such as http: or https:


16. document.write(" URL Path: <br>" +window.location.protocol + "<br>");

17. // Prints hostname with a usable port such as a localhost:8080


18. document.write(" URL hostname with port: " +window.location.host + "<br>");

19. // Prints hostname such as localhost or www.javatpoint.com


20. document.write(" url hostname: " +window.location.hostname + "<br>");

21. // Prints port number, e.g. 8080


22. document.write(" port: " +window.location.port + "<br>");

23. // Prints pathname


24. document.write(" url pathname: " +window.location.pathname + "<br>");

25. // Prints query string


26. document.write(" full url search: " +window.location.search + "<br>");

27. // Prints fragment identifier


28. document.write(" full url identifier: " +window.location.hash);
29. }
30. </script>

31. </body>

32. </html>

Output
The given output shows the url properties value.

Manipulate the Javascript location


The manipulation of location is used to get the required url or file path as per user requirement.
Themanipulation of the locationis used three methods which are assign(),reload(), andreplace().
This method is worked with JavaScript functions and events.

○ JavaScript Assign() method


The assign() method is used to get a URL and navigate url path on the page. It is worked for
adding url path to the browser's history stack.
Syntax
The following syntax uses to assign the required URL.
1. window.location.assign("URL")

○ The "window.location.assign" function is used to get the required URL path.

○ We can place the path or url link of the file or website.

Example
The given an example assigns the given and the required URL. Here, we can use the button with
the onclick function to display the assigned url.
1. <!DOCTYPE html>

2. <html>

3. <body>

4. <h2> JavaScript location method </h2>

5. <h3> The window.location assign object </h3>

6. <input type = "button" value = "Load new document" onclick = "newDocument()">

7. <script>

8. function newDocument() {
9. window.location.assign("https://www.javatpoint.com")
10. }
11. </script>

12. </body>

13. </html>

Output
The given output images show the assigned url.
Output1
Output1

○ Javascript replace() method

The replace() pattern is related to assign(), except it doesn't create a new history stack entry.
Therefore, you can't use the back button to go back. This function shows new or replaced URLs
from old URLs.
Syntax
The following syntax uses to replace the required URL.
1. Window.location.replace("URL")

○ The "window.location.replace" function is used to get a new URL path.

○ We can replace the path or url link from old to new using the simple javascript method.

Example
The given example replaces the given required URL. Here, we can use a button with the onclick
function to get a new url from an old url.

1. <!DOCTYPE html>

2. <html>

3. <body>

4. <h2> JavaScript location method </h2>

5. <h3> The window.location replace object </h3>

6. <input type = "button" value = "Load new document" onclick = "newDocument()">

7. <script>

8. function newDocument() {
9. window.location.replace("https://www.javatpoint.com")
10. }
11. </script>

12. </body>

13. </html>

Output
The given output images show replaced url.
Output1

Output1
○ Javascript reload() method

The reload() method is utilized to reload a page. When you call reload() with no argument, the
browser reloads the page in the most effective method, loading page resources from the cache if
they haven't changed since its last request.
Syntax
The following syntax uses to reload the required URL.
1. location.reload();

○ the location.reload() function reload url and display a blank page.

○ It does not need any file path or current url

Example
The given an example reloads the given required URL. We can reload the page using the
javascript onclick function.

1. <!DOCTYPE html>

2. <html>

3. <body>

4. <h2> JavaScript location method </h2>

5. <h3> The location.reload object </h3>


6. <input type = "button" value = "Load new document" onclick = "newDocument()">

7. <script>

8. function newDocument() {
9. location.reload();
10. }
11. </script>

12. </body>

13. </html>

Output
The given output shows reload url.

How to open URL in a new window using


JavaScript?
Last Updated : 01 Aug, 2024

In HTML, the anchor tag (<a>) is used to open new windows and tabs in a very
straightforward manner. However, there are situations where you need to achieve the
same functionality using JavaScript. This is where the window.open() method becomes
useful.
The window.open() method is used to open a new browser window or a new tab,
depending on the browser settings and the parameter values provided. Here’s how you
can use it:
Syntax
window.open(URL, name, specs, replace);

Note: All the parameters are optional.


There are several methods to open the URL in a new window using JavaScript which
are as follows:
Table of Content
● Using Window.Open() method
● Using Anchor tag
● Using Input tag
● Conclusion

Using Window.Open() method


To open a URL in a new window, make sure that the second parameter is not _blank.
The other parameters can be varied accordingly as per the need of the new window.
Example: To demonstrate creating a button and setting an onclick function to open a
new window.
HTML
<!DOCTYPE html>

<html>

<head>

<title>

Click the button to


open a new window.
</title>

</head>

<body style="text-align:center;">
<h1 style="color:green">

GeeksforGeeks
</h1>

<p>

Click the button to


open a new window.
</p>

<button onclick="NewTab()">

Open Geeksforgeeks
</button>

<script>

function NewTab() {

window.open("https://www.geeksforgeeks.org",

"", "width=300, height=300");

</script>

</body>

</html>

Output:
Video Player
00:00
00:06

Using Anchor tag


The anchor tag (<a>) can also be utilized with JavaScript to open URLs in new
windows or tabs. By specifying target="_blank", the link will open in a new tab. This
approach is straightforward and commonly used for external links, enhancing user
experience by keeping the current page intact.
Example: Use Anchor tag to open URL in a new window using JavaScript.
HTML
<!DOCTYPE html>

<html>

<head>

<title>Using anchor tag</title>

</head>

<body style="text-align:center;">

<h1 style="color:green">

GeeksforGeeks
</h1>

<p>

Click the button to open


GeeksforGeeks in a new window.
</p>
<a onclick='window.open("https://www.geeksforgeeks.org/",

"_blank", "width=300, height=300");'>

GeeksforGeeks
</a>

</body>

</html>

Output:
Video Player
00:00

00:09

Using Input tag


Another approach involves using the input tag (<input type="button">) with an onclick
event handler to open URLs in new windows. Similar to the anchor tag, this approach
allows for customizing window properties such as width, height, and position. It
provides a clickable button for users to initiate the action.
Example: To demonstrate using the Input tag to open the URL in a new window.
HTML
<!DOCTYPE html>

<html>

<head>

<title>Using input tag</title>

</head>

<body style="text-align:center;">
<h1 style="color:green">

GeeksforGeeks
</h1>

<p>

Click the button to open


GeeksforGeeks in a new window.
</p>

<input type="button" onclick="window.open(

'https://www.geeksforgeeks.org/','geeks',

'toolbars=0,width=300,height=300,left=200,top=200,scrollbars=1,resizable=1');"

value="Open the window">

</body>

</html>

Output:

How to Display Changed Browser URL Without


Reloading Through alert using JavaScript ?
Last Updated : 24 Jan, 2023


To change the URL in the browser without loading the new page, we can use
history.pushState() method and replaceState() method from JavaScript. To
display the browser-URL before changing the URL we will use
window.location.href in the alert() function and will use again after changing the
browsers-URL. Note: The history.pushState() method combines HTML 5 History
and JavaScript pushState() method.
Syntax:
alert(" Message:" + window.location.hrf);

Below examples illustrate the above approach:


Example 1:

HTML
<head>

<script>

function geeks() {

alert("The current URL of this"

+ " page is: " + window.location.href);

function change_url() {

window.history.pushState("stateObj",

"new page", "changedURL.html");

alert("The URL of this page is: "

+ window.location.href);

</script>

</head>

<body onload="geeks()">

<a href="javascript:change_url()">

Click to change url

</a>

</body>
Output:

Example 2:

HTML
<head>

<script type="text/javascript">

function geeks() {

alert("The current URL of this "

+ "page is: " + window.location.href);

function change_url() {

window.history.replaceState("stateObj",

"new page", "changedURL.html");

alert("The URL of this page is: "

+ window.location.href);

</script>

</head>

<body onload="geeks()">

<a href="javascript:change_url()">

Click to change url

</a>

</body>
Output:

JavaScript timer
In JavaScript, a timer is created to execute a task or any function at a particular time.
Basically, the timer is used to delay the execution of the program or to execute the
JavaScript code in a regular time interval. With the help of timer, we can delay the
execution of the code. So, the code does not complete it's execution at the same time when
an event triggers or page loads.
The best example of the timer is advertisement banners on websites, which change after
every 2-3 seconds. These advertising banners are changed at a regular interval on the
websites like Amazon. We set a time interval to change them. In this chapter, we will show
you how to create a timer.
JavaScript offers two timer functions setInterval() and setTimeout(), which helps to delay
in execution of code and also allows to perform one or more operations repeatedly. We will
discuss both the timer functions in detail as well as their examples.

Examples
Below are some examples of JavaScript timer using these functions.
ADVERTISEMENT

setTimeout()
The setTimeout() function helps the users to delay the execution of code. The setTimeout()
method accepts two parameters in which one is a user-defined function, and another is the
time parameter to delay the execution. The time parameter holds the time in milliseconds
(1 second = 1000 milliseconds), which is optional to pass.
The basic syntax of setTimeout() is:
1. setTimeout(function, milliseconds)
We will use the setTimeout() function to delay the printing of message for 3 seconds. The
message will display on the web after 3 seconds of code execution rather than immediately.
Now, let's look at the code below to see how it works:
Execution of code after a delay
1. <html>
2. <body>
3. <script>
4. function delayFunction() {
5. //display the message on web after 3 seconds on calling delayFunction
6. document.write('<h3> Welcome to JavaTpoint <h3>');
7. }
8. </script>
9. <h4> Example of delay the execution of function <h4>
10.
11. <!?button for calling of user-defined delayFunction having 3 seconds of delay -->
12. <button onclick = "setTimeout(delayFunction, 3000)"> Click Here </button>
13.
14. </body>
15. </html>
Test it Now

Output
The above code will execute in two sections. Firstly, the HTML part of the code will
execute, where by clicking on Click Here button the remaining JavaScript code will execute
after 3 seconds. See the output below:
ADVERTISEMENT
On clicking the Click Here button, the remaining code will execute after 3 seconds. A
message Welcome to javaTpoint will display on the web after 3 seconds (3000 milliseconds).

setInterval()
The setInterval method is a bit similar to the setTimeout() function. It executes the
specified function repeatedly after a time interval. Or we can simply say that a function is
executed repeatedly after a specific amount of time provided by the user in this function.
For example - Display updated time in every five seconds.
The basic syntax of setInterval() is:
1. setInterval(function, milliseconds)
Similar to setTimeout() method, it also accepts two parameters in which one is a
user-defined function, and another is a time-interval parameter to wait before executing
the function. The time-interval parameter holds the amount of time in milliseconds (1
second = 1000 milliseconds), which is optional to pass. Now, see the code below how this
function works:
Execution of code at a regular interval
1. <html>
2. <body>
3. <script>
4. function waitAndshow() {
5. //define a date and time variable
6. var systemdate = new Date();
7.
8. //display the updated time after every 4 seconds
9. document.getElementById("clock").innerHTML =
systemdate.toLocaleTimeString();
10. }
11.
12. //define time interval and call user-defined waitAndshow function
13. setInterval(waitAndshow, 4000);
14. </script>
15.
16. <h3> Updated time will show in every 4 seconds </h3>
17. <h3> The current time on your computer is: <br>
18. <span id="clock"></span> </h3>
19.
20. </body>
21. </html>
Test it Now

Output
On executing the above code, the response will be a simple HTML statement without any
time string like below output:

After 4 seconds, the JavaScript function will call and start displaying the time. This will
repeatedly display your system time in every four seconds.
Example
One more example of setInterval() methods for displaying a message string after every 4
seconds continuously.
1. <html>
2. <body>
3. <script>
4. function waitAndshow() {
5. //display the message on web on calling delayFunction
6. document.write('<h3> Welcome to JavaTpoint <h3>');
7. }
8. </script>
9. <h3> A string will show in every 4 seconds </h3>
10. <!-- call user-defined delayFunction after 4 seconds -->
11. <button onclick = "setInterval(waitAndshow, 4000)"> Click Here </button>
12.
13. </body>
14. </html>
Test it Now

Output
On executing the above code, a message with a button will show on the browser. Click on
this button to process more and see what happens next.
By clicking on this Click Here button, the waitAndshow() will start printing the message
Welcome to Javatpoint repeatedly on the web in every 4 seconds.

You have seen how to create timer or set time interval. Sometimes, we need to cancel these
timers. JavaScript offers the in-built function to clear the timer, which are as follows:

Cancel or Stop the timer


JavaScript offers two functions clearTimeout() and clearInterval() to cancel or stop the
timer and halt the execution of code. The setTimeout() and setInterval() both return a
unique IDs. These IDs are used by the clearTimeout() and clearInterval() to clear the timer
and stop the code execution beforehand. They both take only one parameter, i.e., ID.
Example
In this example, we will use clearTimeout() to clear the timer set by with setTimeout()
function. Look at the example how clearInterval() work with setInterval().

Disable the regular interval


1. <html>
2. <body>
3. <script>
4. function waitAndshow() {
5. //define a date and time variable
6. var systemdate = new Date();
7.
8. //display the updated time after every 4 seconds
9. document.getElementById("clock").innerHTML =
systemdate.toLocaleTimeString();
10. }
11.
12. //function to disable the time interval
13. function stopClock() {
14. clearInterval(intervalID);
15. }
16.
17. //define time interval and call user-defined waitAndshow function
18. var intervalID = setInterval(waitAndshow, 3000);
19. </script>
20.
21. <p>Current system time: <span id="clock"> </span> </p>
22.
23. <!-- button to stop showing time in a regular interval -->
24. <button onclick = "stopClock();" > Stop Clock </button>
25. </body>
26. </html>
Test it Now

Output
By executing the above code, the current system time will start showing on the web with 3
seconds of regular interval. This page also has a button to disable this timer.
The timer will show the updated time after every three seconds. If you click on this Stop
Clock button, the timer will be disabled and stop showing the updated time.

How to access history in JavaScript ?


Last Updated : 31 Jul, 2024

In this article, we will learn how to access history in JavaScript. We will use the
History object to access the history stack in JavaScript. Every web browser will store
the data on which websites or webpages opened during the session in a history stack.
To access this history stack we need to use the History object in JavaScript.
History object: The history object contains the browser’s history. The URLs of pages
visited by the user are stored as a stack in the history object. There are multiple
methods to manage/access the history object.
Methods of History object:
1. The forward() Method: This method is used to load the next URL in the history
list. This has the exact functionality as the next button in the browser. There are no
parameters and it will return nothing.
Syntax:
history.forward()
2. The back() Method: This method is used to load the previous URL in the history
list. This has the exact functionality as the back button in the browser. There are no
parameters and it will return nothing.
Syntax:
history.back()

3. The go() Method: This method is used to loads a URL from the history list.
Syntax:
history.go(integer)

Parameters: This method has a single parameter that specifies the URL from the
history. It can have the following values:

Valu
Usage
e

-1 Loads the previous page from the history stack

0 Reloads the page.

1 Loads the next page from the history stack


Example 1: Using forward() and back()
HTML
HTML
<!DOCTYPE html>

<html>

<head>

<style>

a,

input {

margin: 10px;

</style>

</head>

<body>

<h1>This is page 1</h1>

<a href="/geekshtml2.html">Go to page 2</a> <br>

back button : <input type="button"


value="Back"

onclick="previousPage()"> <br>

forward button : <input type="button"


value="Forward"

onclick="NextPage()"> <br>
<script>

function NextPage() {

window.history.forward()

function previousPage() {

window.history.back();

</script>

</body>

</html>

Output:

Example 2: Using go(), forward() and back() methods.


HTML
HTML
<!DOCTYPE html>

<html>

<head>

<style>

a,
input {

margin: 10px;

</style>

</head>

<body>

<h1>This is page 1</h1>

<a href="/geekshtml2.html">Go to page 2</a> <br>

back button : <input type="button"


value="Back"

onclick="previousPage()"> <br>

forward button : <input type="button"


value="Forward"

onclick="NextPage()"> <br>

Go button : <input type="button"


value="go"

onclick="go()"> <br>

<script>

function NextPage() {

window.history.forward()

function previousPage() {
window.history.back();

function go() {

window.history.go(0);

</script>

</body>

</html>

Output:

JavaScript History object


Last Updated : 08 May, 2023


The JavaScript History object contains the browser’s history. First of all, the window
part can be removed from window.history just using the history object alone works
fine. The JS history object contains an array of URLs visited by the user. By using the
history object, you can load previous, forward, or any particular page using various
methods.
JavaScript history object Properties:
● length: It returns the length of the history URLs visited by the user in that
session.
JavaScript history object Methods:
● forward(): It loads the next page. Provides the same effect as clicking back
in the browser.
● back(): It loads the previous page. Provides the same effect as clicking
forward in the browser.
● go(): It loads the given page number in the browser. history.go(distance)
function provides the same effect as pressing the back or forward button in
your browser and specifying the page exactly that you want to load.
Example 1: JavaScript code to show the working of history.back() function.

HTML
<strong>

Press the back button

</strong>

<input type="button"

value="Back"

onclick="previousPage()">

<script> function previousPage() {

window.history.back();

</script>
Output: This example will not work if the previous page does not exist in the history
list. If you click the above link then a new page opens and when you press the back
button on that page it will redirect to the page that you opened previously.
Press the back button Back

Example 2: JavaScript code to show the working of history.forward() function.

HTML

<strong>

Press the forward button

</strong>

<input type="button"

value="Forward"

onclick="NextPage()">

<script>

function NextPage() {

window.history.forward() }

</script>
Press the forward button Forward

Note: This example will not work if the next page does not exist in the history list.
This code can be used when you want to use the forward button on your webpage. It
works exactly the same as the forwarding button of your browser. If the next page
doesn’t exist it will not work.
Example 3: JavaScript code to show the working of history.go() function, go(4) has
the same effect as pressing your forward button four times. A negative value will
move you backward through your history in a browser.go(-4) has the same effect as
pressing your back button four times.

HTML

<input type="button"

value="go"

onclick="NextPage()">

<script> function NextPage() {


window.history.go(4); }

</script>

You might also like