Notes
Notes
Example 1
Let's see an example to set and get a cookie.
1. <!DOCTYPE html>
2. <html>
3. <head>
4. </head>
5. <body>
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>
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>
8. <option value="yellow">Yellow</option>
9. <option value="green">Green</option>
11. </select>
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>
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>
2. <html>
3. <head>
4. </head>
5. <body>
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>
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>
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>
ADVERTISEMENT
○ Serialize the custom object in a JSON string, parse it and then store in a cookie.
2. <html>
3. <head>
4. </head>
5. <body>
11. <script>
33. </body>
34. </html>
Output:
Test it Now
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>
11.
12. <script>
40. </body>
41. </html>
Test it Now
Output:
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>
11.
12. <script>
31. </body>
32. </html>
Output:
Test it Now
2. <html>
3. <head>
4. </head>
5. <body>
6.
7. <input type="button" value="Set Cookie" onclick="setCookie()">
9. <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>
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()">
10. <br>
14. <br>
16.
17. <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()">
9. <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.
○ 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.
Or
You can also use this function without using the window keyword as shown below:
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.
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.
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
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:
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>
7. </html>
Test it Now
Or
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>
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.
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>
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.
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>
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.
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>
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>
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.
Copy Code
1. <html>
2. <head>
4. <script>
16. </head>
17.
18. <center>
20. <body>
21. <b> Click the button to open Javatpoint tutorial site </b><br>
23. <br><br>
24. <b> Click the button to close Javatpoint tutorial site </b><br>
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.
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.
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>
15. <body>
17. <br><br>
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>
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>
21. <body>
22. <b> Click the button to open Javatpoint tutorial site </b><br>
24. <br><br>
25. <b> Click the button to close Javatpoint tutorial site </b><br>
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
○ Opera
○ Safari, etc.
○ The href attribute on the location object contains the current webpage's URL.
○ 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.
Syntax:
Backward Skip 10s
Play Video
○ 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>
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
2. <html>
3. <body>
9. <script>
16. </body>
17. </html>
Output
The given output shows the current href link using the javascript function.
Output1
Output2
○ 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">
6. </head>
7. <body>
11. <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.
Example
The following example is displayed the JavaScript location hostname.
1. <!DOCTYPE html>
2. <html lang="en">
3. <head>
4. <meta charset="utf-8">
6. </head>
7. <body>
12. <script>
20. </body>
21. </html>
Output
The given output shows the url properties value.
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">
6. </head>
7. <body>
11. <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">
6. </head>
7. <body>
11. <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">
6. </head>
7. <body>
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>
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">
6. </head>
7. <body>
11. <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">
6. </head>
7. <body>
13. <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">
6. </head>
7. <body>
13. <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">
6. </head>
7. <body>
13. <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">
6. </head>
7. <body>
10. <input type = "button" value = "Load new document" onclick = "newDocument()">
11. <script>
31. </body>
32. </html>
Output
The given output shows the url properties value.
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>
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
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")
○ 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>
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();
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>
7. <script>
8. function newDocument() {
9. location.reload();
10. }
11. </script>
12. </body>
13. </html>
Output
The given output shows reload url.
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);
<html>
<head>
<title>
</head>
<body style="text-align:center;">
<h1 style="color:green">
GeeksforGeeks
</h1>
<p>
<button onclick="NewTab()">
Open Geeksforgeeks
</button>
<script>
function NewTab() {
window.open("https://www.geeksforgeeks.org",
</script>
</body>
</html>
Output:
Video Player
00:00
00:06
<html>
<head>
</head>
<body style="text-align:center;">
<h1 style="color:green">
GeeksforGeeks
</h1>
<p>
GeeksforGeeks
</a>
</body>
</html>
Output:
Video Player
00:00
00:09
<html>
<head>
</head>
<body style="text-align:center;">
<h1 style="color:green">
GeeksforGeeks
</h1>
<p>
'https://www.geeksforgeeks.org/','geeks',
'toolbars=0,width=300,height=300,left=200,top=200,scrollbars=1,resizable=1');"
</body>
</html>
Output:
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);
HTML
<head>
<script>
function geeks() {
function change_url() {
window.history.pushState("stateObj",
+ window.location.href);
</script>
</head>
<body onload="geeks()">
<a href="javascript:change_url()">
</a>
</body>
Output:
Example 2:
HTML
<head>
<script type="text/javascript">
function geeks() {
function change_url() {
window.history.replaceState("stateObj",
+ window.location.href);
</script>
</head>
<body onload="geeks()">
<a href="javascript: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:
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.
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
<html>
<head>
<style>
a,
input {
margin: 10px;
</style>
</head>
<body>
onclick="previousPage()"> <br>
onclick="NextPage()"> <br>
<script>
function NextPage() {
window.history.forward()
function previousPage() {
window.history.back();
</script>
</body>
</html>
Output:
<html>
<head>
<style>
a,
input {
margin: 10px;
</style>
</head>
<body>
onclick="previousPage()"> <br>
onclick="NextPage()"> <br>
onclick="go()"> <br>
<script>
function NextPage() {
window.history.forward()
function previousPage() {
window.history.back();
function go() {
window.history.go(0);
</script>
</body>
</html>
Output:
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>
</strong>
<input type="button"
value="Back"
onclick="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
HTML
<strong>
</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>