Tag Archives: pushstate

Having fun with HTML 5 History API – part three

Part 1 – Description of the problem
Part 2 – simple history replacement
Part 3 – additional history items – this article

As we’ve seen in the previous parts, we can alter the history of the current page navigation by replacing the current URL with a new one (this freedom has limits, of course, and we can’t alter the protocol or the host).

What we’ll explore in this part is creating new history items while not leaving the page. In order to achieve this, we’ll make use of

history.pushState( ... )

and an event called popstate :

window.addEventListener('popstate', function () { /* ... */ });

First we’ll need to replace all replaceState calls to pushState calls. The parameters stay the same:

function loadModels(make, pushState, onSuccess) {
    $.ajax({
        cache: true,
        type: 'GET',
        url: '@Url.Action("GetModelsByMake")',
        data: { 'makeId': make },
        success: function (data) {
            if (pushState)
                history.pushState(null, null, "/Home/Selector?mkId=" + make);
            var models = $("#SelectedModel");
            models.empty();
            models.append($("<option></option>").attr("value", "").text(" -- please select a model -- "));
            $.each(data, function (key, val) {
                models.append($("<option></option>").attr("value", val.Id).text(val.Text));
            });
            $('#divModel').show();
            if (onSuccess)
                onSuccess();
        },
        error: function (xhr, ajaxOptions, error) {
            alert(error);
            $('#divModel').hide();
        }
    });
}

// ...

function modelChanged() {
    var makeId = getParameterByName("mkId", document.location.href);
    var modelId = $("#SelectedModel").val();
    if (!modelId)
        history.pushState(null, null, "/Home/Selector?mkId=" + makeId);
    else
        history.pushState(null, null, "/Home/Selector?mkId=" + makeId + "&mdId=" + modelId);
}

Read more »

WP Like Button Plugin by Free WordPress Templates