Navigating from a web address to making an asynchronous request using history.js

As I work on a small website that features multiple pages with similar layouts, I often find that only the content within a specific div varies. The rest of the elements such as navigation and header remain consistent throughout.

To address this, I have set up a "base" HTML file along with smaller HTML files containing only the content-div and incorporated JavaScript code like the following (to be activated upon clicking a button):

$.get("content/text1.html", function(data) {
    $("#content").html(data);
});

This process works seamlessly; however, it presents an issue where the URL in the address bar does not change with these requests. This makes it challenging for users to directly link to particular pages. While I am aware of using #-urls as a workaround, my preference is to utilize URLs like:

example.com/talks/foo/bar

And avoid any workarounds.

In a separate discussion thread, someone directed me towards the HTML5 browser history API, particularly history.js.

My objective with this integration is twofold:

  1. Upon clicking a button, trigger an AJAX request to update the content of the content-div and concurrently update the URL to something akin to example.com/talks/foo/bar
  2. If a user manually types in example.com/talks/foo/bar into their browser, replicate the same AJAX request and content update as described in (1)

I attempted to achieve the first goal through:

$.get("content/text1.html", function(data) {
    $("#content").html(data);
    History.pushState(null, null, "content/text1.html"); 
}); 

However, I am uncertain about how to effectively tackle the second point. Should I consider implementing a rewriterule that redirects all traffic to the base HTML file, accompanied by JavaScript logic to decipher the URL and prompt the AJAX request?

I sense that my current approach may require adjustment..


  • Is this the correct usage of history.js?

  • How can I successfully implement the second bullet point?

Answer №1

In order to establish the initial state on html5 browsers, there is no need for any ajax calls. As you mentioned, the URL itself changes without altering the hash, so the server should respond with the appropriate content already loaded.

All ajax calls and DOM manipulation should be done within the statechange event handler.

Simply calling pushState when the user clicks on a link and handling the DOM changes within the statechange event handler works seamlessly. This is because the statechange event is triggered whenever pushState is invoked.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JS/Chrome Extension: Ways to Verify if a User is Currently Logged In

After building a Chrome extension, I am now looking to seamlessly integrate it with my existing PHP-based website. This website allows users to have their own accounts and save their favorite items, similar to a Pinterest platform. My main question is whe ...

The Boostrap Datepicker fails to display

I'm having trouble integrating a Bootstrap Datepicker into my form. I got it working outside of the form, but when I try to include the code in my form, it doesn't seem to work. All necessary files are present and the code is identical. <!D ...

Experience the latest HTML5 features directly within a Java desktop GUI, with seamless communication through

This Java desktop GUI utilizes a Java-based web services communication layer along with an HTML library to provide powerful charting and interactivity. I am looking to integrate an HTML5 view within the Java GUI. Can someone assist me in managing JavaScri ...

A comprehensive guide on implementing filtering in AngularJS arrays

I am working with the array provided below: [ { Id: 1, Name: "AI", Capacity: 2, From: "2021-10-27T08:00:00", To: "2021-10-27T08:50:00", }, { Id: 2, Name: "TEST", Capacity: 2, ...

Troubleshooting: Issue with multiple file input elements on page - only the first input is functional and not displaying preview images

Having some trouble with loading multiple file inputs and their preview images. I've tried using getElementsByClassName but I suspect that I'm not iterating over them correctly. I want to avoid using unique IDs for the elements because they will ...

Guide to including objects into your project without the need for babel through the use of CDN

I'm struggling with getting my Vue code to transpile properly due to some issues. I have resorted to loading Vue and other packages directly using CDN links, like this: <script src="https://cdnjs.cloudflare.com/ajax/libs/survey-vue/1.8.33/surv ...

Utilizing AJAX in Django applications

I'm currently working on integrating a basic AJAX function with Django, but I seem to be facing some issues. The request.is_ajax() function is returning False, and using event.preventDefault() doesn't prevent the form from getting submitted. Her ...

Tips for accessing the next sequential tag that is similar in HTML with the help of jQuery

I have generated the following HTML code from some plugins. <div class="parent"> <span>item1</span> <input type="hidden"></input> <span>item2</span> <span class="active">item3</span> <inpu ...

Disabling $routeprovider while implementing bootstrap

I am encountering an issue with my normal routeprovider code. In a specific section of my HTML, I have some Twitter Bootstrap expand/collapse sections which inadvertently trigger the routeprovider when clicked. Is there a way to prevent this from happening ...

Place the controller information into a div element as a paragraph by utilizing the power of jQuery ajax functions

I am facing an issue with my controller where I am trying to retrieve data from a model and insert each piece of data into a div called test. The data should be displayed as paragraphs within the div, but unfortunately, it is not working as expected. Belo ...

Making sure Angular picks up on $scope changes

Currently, I am in the process of developing my inaugural AngularJS application and am faced with the challenge of a directive not updating its view when there are changes to the array received from the service. Below is the structure of my directive: an ...

An issue with the form.submit function within an if-else statement

Can anyone help me with submitting a form using AJAX within an if-else statement? I have the code below, but it doesn't seem to be working as expected: $.ajax({ type: "POST", url:'<?php echo base_url() ?>signup/orde ...

Prevent MUI Autocomplete from closing when the option menu is opened with blur

Seeking assistance with modifying an autocomplete menu to include a dropdown for each item. Issue arises after trying to open the additional menu as it triggers an immediate closure of the autocomplete. For reference, attached is an image showcasing the i ...

Translate a jQuery ajax request utilizing jQuery().serialize into plain JavaScript

Currently, I've been in the process of converting a jQuery script into vanilla JavaScript to completely eliminate the need for jQuery. The main functionality of the code includes: Upon clicking a button on the front end, an ajax request is sent, upda ...

Using JavaScript to transform JSON information into Excel format

I have tried various solutions to my problem, but none seem to fit my specific requirement. Let me walk you through what I have attempted. function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel) { //If JSONData is not an object then JSON.parse will ...

AngularJS: The `$locationChangeStart` event

I am attempting to check the next token in the next, but I am encountering an error: TypeError: next.localStorage is not a function APP.JS .run(function ($rootScope, $location,$log,User) { $rootScope.$on("$locationChangeStart", function (event,nex ...

Associate the callback function with a directive that does not have an isolated scope

Ensuring the correct context when binding a callback function to a directive is crucial. When working with an isolated scope, this task is easily accomplished. <bar-foo callback="mycontroller.callback()"></bar-foo> The directive code: ... ...

Transforming the MUI CircularProgress into a half circle shape

After utilizing CirculaProgress, I was able to achieve the following: Is there a simple method to transform it into a semicircle like shown here? ...

Display the page for 10 seconds continuously in a loop

I am currently developing a Node JS guessing game where data is collected on the back-end and sent to the front-end to start the game. The data consists of 10 levels, allowing the game to operate on a single page. Each level lasts for 10 seconds. Once the ...

Is it possible to generate a basic HTML page using Express JS without utilizing Ejs or any other templating engine

I have a basic HTML file with a Bootstrap form, along with a simple API coded within. In my server.js file, I've specified that when I request /about, it should redirect me to the about.html page. However, instead of redirecting, I'm encountering ...