History API HTML 5

by 0GiS0

HTML

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>HTML 5 History API</title>
</head>
<body>
    <header>
        <h1>HTML 5 History API</h1>
    </header>
    <article>
        <div id="history">
            <button id="btnBack">Back button</button>
            <button id="btnForward">Forward button</button>
            <button id="btnModifyURL">Modify URL</button>
        </div>
    </article>    
</body>
</html>

CSS

body {
    font-family: "Verdana";
    font-size: 9pt;
}

header {
    padding: 15px;
    box-shadow: 0px 1px 2px rgba(0,0,0,0.4);
    background-color: rgb(27, 161, 226);
    color: #fff;
}

    header h1 {
        font-size: 14pt;
    }


article {
    width: 80%;
    margin: auto;
    margin-top: 20px;
}

button{
    padding: 15px;    
}

JavaScript

window.onload = function () {
            console.log("History length: " + history.length);

            //Create a select element
            var select = document.createElement("select");

            for (var i = 0; i < history.length; i++) {
                var option = document.createElement("option");
              //  option.value = i;
              //  option.innerText = i;

                select.appendChild(option);
            }

            var div = document.getElementById("history");

            select.addEventListener("change", function () {
                console.log(select.value);
                history.go(select.value);
            });

            div.appendChild(select);

            var btnBack = document.getElementById("btnBack");
            var btnForward = document.getElementById("btnForward");
            var btnModifyURL = document.getElementById("btnModifyURL");

            btnBack.addEventListener("click", function () {
                //Back button
                history.back();
            });

            btnForward.addEventListener("click", function () {
                //Forward button
                history.forward();
            });

            btnModifyURL.addEventListener("click", function () {
                alert("Modify URL");
                history.pushState(null,"A title","/home.html");

            });
        }