JS History Object 📅📝

beginner
23 min

JS History Object 📅📝

Welcome to our comprehensive guide on the History object in JavaScript! This tutorial is designed for both beginners and intermediates, so let's dive right in.

What is the History Object? 📚

The History object in JavaScript represents the browsing history of a web page. It allows you to manipulate the browser's history, such as going back and forward, loading a specific page from the history, and more.

Navigating Through History 🔄

Going Back and Forward 🔙🔝

You can navigate through the browser's history using the back() and forward() methods. Here's a simple example:

javascript
// Go back one page history.back(); // Go forward one page history.forward();

Refreshing a Page 🌐

To refresh the current page, you can use the reload() method:

javascript
// Refresh the current page history.reload();

Loading a Specific Page from History 🔐

The go() method allows you to navigate directly to a specific page from the history. The argument for go() is the position of the page in the history, with 0 being the current page:

javascript
// Go to the third last page in history history.go(-3);

Manipulating the Title 📝

You can change the title of the current page using the window.document.title property:

javascript
// Change the title of the page window.document.title = "New Page Title";

Quiz Time 🎯

Quick Quiz
Question 1 of 1

What method would you use to go back one page in the browser's history?

Practice Exercise 💡

Create a simple web page and add a button that, when clicked, takes the user back to the previous page.

html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>History Object Practice</title> </head> <body> <button id="backButton">Go Back</button> <script> // Get the button const backButton = document.getElementById('backButton'); // Add a click event listener to the button backButton.addEventListener('click', function() { // Go back one page history.back(); }); </script> </body> </html>

That's all for now! In the next lesson, we'll explore more advanced uses of the History object, such as updating the history and managing state changes. Stay tuned! 🎯