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

Move divs that are currently not visible on the screen to a new position using CSS animations

Upon entering the site, I would like certain divs to animate from an offscreen position. I came across this code snippet: $( document ).ready(function() { $('.box-wrapper').each(function(index, element) { setTimeout(function(){ ...

Deactivating AngularJS debug information in a gulp / typescript production compilation

What is the most effective approach to disabling debug data in a gulp production build? The recommended method for disabling debug data is: myApp.config(['$compileProvider', function ($compileProvider) { $compileProvider.debugInfoEnabled(false ...

How can the edit feature be implemented in AngularJS?

I am struggling with implementing an edit field in AngularJS. Can someone please help me with this? Here is the code for my CRUD operations: var app = angular.module('myApp', []) app.controller('myCtrl', ['$scope', functio ...

SelectBoxIt jquery plugin can be applied after the completion of populating options in the select element with AngularJS

Utilizing AngularJS, I am dynamically populating a select box with the code below: <select ng-model="department" ng-options="dept as dept.name for dept in departmentList" class="fancy"> <option value="">-- select an optio ...

Optimizing rest service calls with $resource

I am currently learning about the $resource to utilize RESTful Web Services. For my first attempt, I created a factory like this : 'use strict'; angular.module('BalrogApp').factory('Req', ['$resource', function($r ...

Is it possible to set up VS Code's code completion feature to automatically accept punctuation suggestions?

For all the C# devs transitioning to TypeScript in VS Code, this question is directed at you. I was captivated by the code completion feature in VS C#. To paint a clearer picture, let's say I'm trying to write: console.log('hello') W ...

Updating the parameters when clicking on each pagination button: A guide

Does anyone have advice on implementing pagination? I am currently working on loading a datatable with a few records initially. Once the page is loaded, I want to be able to click on pagination buttons like next or any pagination buttons to display a new s ...

"Modifying state within a child component and utilizing the refreshed value in the parent component

I'm currently working on creating a simple header mini cart with a cart item counter in NextJS. I'm utilizing the form state value in the header component and then passing that value to the child components of the header where the numerical quant ...

Jquery Mobile - Unstyled Popup

I have a question regarding popups. From what I've read, popups should be on the same page as the anchor that triggers them. But how does it work with multipage websites? The problem I'm encountering is that while the popup appears, the elements ...

Escape sequences do not seem to be functioning properly when using innerHTML

I am facing an issue where a string containing HTML escape characters (such as < and >) needs to be rendered inside a div using innerHTML. The intention is for the escaped characters to appear as text rather than as actual HTML, but they still render ...

Encoding URLs for LoopBack applications

I am experiencing an issue with the filter I have: { "fields": {"goal":true,"amountPledged": true,"title": true},"where": {"title": {"like":`%${this.state.searchText}%`}} } The this.state.searchText value is bio. According to my understanding, it should ...

Guide on how to combine the strings retrieved from an API

I'm having trouble concatenating multiple sentences together and highlighting specific words in each sentence. Although I can successfully highlight one sentence using the code below, I haven't been able to concatenate more than one sentence: th ...

When a base html tag is dynamically added, the browser mistakenly loads assets twice

When managing relative paths on a website, I utilize the <base> tag within the <head> section of each page. Although all resources loaded via relative-like paths in the documents are displayed correctly, my observations show that browsers such ...

Effortless sliding panel that appears on hover and vanishes when mouse is moved away

I am in the process of creating a menu for my website that utilizes linkbuttons which trigger additional linkbuttons to slide down upon hover. The desired effect is a smooth sliding panel that appears when hovering over the linkbutton, and disappears when ...

The module script failed to load due to an unexpected response from the server, which was MIME type of text/jsx instead of a javascript module script

I have recently set up an express server and created an API, as well as installed React using Vite for my frontend. However, when I attempt to connect or load my main HTML file to the server, an error is displayed in the console. This is all new to me as I ...

Why is TypeScript unable to recognize package exports? (using CommonJS as the module system and Node as the module resolution)

I have an NPM package that is built for ESM and CJS formats. The package has a dist folder in the root directory, which contains: dist/esm - modules with ESM dist/cjs - modules with CJS dist/types - typings for all modules In the package.json file, there ...

Unable to pass an Array to the Controller

let formData = new FormData(); payloadData = JSON.stringify(payload.unitDoctors); for (var prop in payloadData) { formData.append(prop, payloadData[prop]); } axios({ method: "put", url: apiUrl + payload.id, data: formData }) .then(resp ...

What is the correct way to define an abstract method within a class to ensure that an IDE detects and notifies if the abstract method is not implemented

Is there a way to properly define an abstract method in an abstract class and have the IDE notify us if we forget to implement it? I attempted the following approach, but it did not work: export abstract class MyAbstractClass { /** * @abstract ...

The error message "GetListItems is not defined" indicates that the function is not recognized

I am currently working on a project in SPFx using React, where I need to retrieve SharePoint list items that exceed 5000 through a REST call. Everything seems to be going smoothly until an error occurs during the next iteration process, displaying this me ...

Extracting information from JSON using arrays

I'm facing a bit of a challenge with this one. I've been trying to use jQuery on my website to update an element. It works perfectly fine without using an array of data in JSON, but as soon as I introduce an array of data, it stops functioning. I ...