When JavaScript inserts the # symbol into the URL, it causes the new page to open

I'm currently working on making this website responsive. It is a static HTML website that incorporates some JavaScript to load index.html on each page.

The issue I am encountering is that the JavaScript code adds a # before every link. As a result, when a link is clicked midway through a page, the new page opens at the same scroll position as the previous one.

Any suggestions on how I can ensure that the new page always opens at the top?

The provided JavaScript script is quite complex for me to comprehend...

var ScriptJS = true;
var lastLocation = document.location.href;

$(document).ready(function () {
if (!$('#ajax').length) { 
    document.location = document.location.href.substring(0, 
document.location.href.lastIndexOf('/') + 1) +
        "#" + 
document.location.href.substr(document.location.href.lastIndexOf('/') + 1);
 }

if (window.location.hash) 
    $('#ajax').load(window.location.hash.substr(1));
});

$(document).on("click", "a:not(.regular)", function (e) {
var url = this.href;
if (url.indexOf("https") != -1 || url.indexOf('.html') == -1) 
    return;

e.preventDefault();

$('#ajax').load(url, function () {
    var pagename = url.substr(url.lastIndexOf('/') + 1);
    lastLocation = document.location.href.replace(window.location.hash, "") 
+ '#' + pagename;
    document.location.href = '#' + pagename;
});
});

window.onpopstate = function (event) {
if (lastLocation != document.location.href)
    location.reload();
else
    return;
};

Answer №1

Utilizing AJAX in your code allows for the seamless replacement of current page content with new data fetched from a server.

The '#pagename' element serves the purpose of ensuring functionality with the browser's back button. Feel free to remove it if unnecessary, as it will not impact the overall behavior.

To reset the scroll position to the top of the page after redirecting using document.location.href = ..., simply add document.body.scrollTop = 0; following that line of code.

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

Mastering the Google Places Autocomplete SearchBox: Managing the predictions - enabling or disabling with ease

Is there a way to manage the predictions provided by Google Places Autocomplete SearchBox (google.maps.places.SearchBox) service? In simpler terms, can the HTML input element connected to the Autocomplete SearchBox service be temporarily disconnected and ...

Displaying live IP CAMERA feed using three.js

I am currently facing a challenge in rendering a video stream from an IP Camera to a three.js texture. I have attempted the following code snippet without success: .... var video = document.createElement('video'); video.crossOrigin="anonymous" ...

What are the steps to turn off ASO (Automatic Static Optimization) in Next.js?

In my Next.js application, I am looking to generate a unique CSP (Content Security Policy) nonce for inline scripts on a per-request basis. To implement this, I plan to create a nonce within my `middleware.ts` file and include it in the request headers. T ...

The <h> tag gains height on its own accord

Here is my original code: <h4 class="orange2" ><a href="<?php echo base_url();?>v/<?php echo $this->uri->segment(3);?>/<?php echo $v['uniq'];?>"><?php echo trim(strip_tags($v['video_name']));?> ...

Create a fresh field for the form and store the data in the database

Issue Number One: I am looking to dynamically add a new field along with a button click event that will generate the new field. I attempted to use Jquery for this purpose, but as a newbie in this type of programming language, I am struggling. Can anyone o ...

Mapbox GL - Incorporate a non-scaling polygon feature during zoom operations

Is there a method to incorporate a polygon that maintains its size regardless of zooming? Currently, when adding a polygon circle shape with a 10-meter radius and zooming out, the polygon shrinks in size as expected. However, is it feasible to include a s ...

Choosing a specific column in an HTML table using jQuery based on the text within it

I have a table with a similar structure as shown below: <table> <c:forEach ...> <tr> <td>test</td> // this is the initial value <td>random value</td> <td>random value</td&g ...

3D textile simulation powered by three.js

My current project involves using three.js to develop a cloth simulator similar to the one on the Hermes website. The main difference is that I want to implement top-down waves instead of horizontal waves like the ones on the Hermes site. I have successfu ...

The Perilous Regex That's Bringing Systems to a Halt

There is a code snippet that causes Node to crash without any errors when it reaches the regex: let userIds = [ '{"engagement":{"eng_type":"1","eng_src":"2","eng_tid":"194306103","eng_data":[]},"coeff2_registry_key":"0406","coeff2_info":"Aat8pXwCxGvs ...

Erroneous Marker Placement Detected

Here is the data from my DataTable: Country Types of sales Total sales($) Name State United states of America chemicals 12662871 Obama GA Unite ...

Does Chrome have a feature that disables event listeners?

I'm currently working on a tool that incorporates file drag and drop functionality. Strangely, this feature works perfectly in all browsers except for Chrome. Surprisingly, however, it does work in Chrome when the tool is run locally. Here is the cod ...

Is it feasible to simultaneously load multiple directives in AngularJS?

I currently have a UI table with 5 columns, each containing different charts rendered using various directives such as custom progress bars and margin targets. The functionality is operating smoothly at the moment. Issue: When loading the page, it takes a ...

Getting the Value of an Object in an Array in My Angular Project

Within my Angular Application, I am receiving an array of objects from an API: "register":[ { "club": 8, "players": 100, "officials": 10 }, { "male": 7, "female": 2, "other": 1 }, { "Brazil": 5, "France": 1, "Italy": 2, "England": 2 } ] I want to specifi ...

The gear icon in the video player is not showing up when I try to change the

I am currently trying to implement a feature that allows users to select the quality of the video. I am using videojs along with the videojs-quality-selector plugin, but even though the video runs successfully, the option to choose the quality is not appea ...

Creating a dynamic progress bar animation that transitions smoothly from one color to another using jQuery

Is there a way to change the barColor so that it has different colors at the start and end? var EasyPieChart = function(el, opts) { var defaultOptions = { barColor: '#FFEA82', trackColor: '#e1e1e3', scaleCol ...

How can I troubleshoot the overflow-y problem in a tab modal from w3 school?

https://www.example.com/code-sample overflow: scroll; overflow-y: scroll; When I type a lot of words, they become hidden so I need to use overflow-y=scroll. Despite trying both overflow: scroll; and overflow-y: scroll;, I have been unable to achieve the ...

Array automatically updates its values

.... import * as XLSX from 'xlsx'; ... I am currently parsing a .xlsx file in an Ionic 4 application. showData() { let fileReader = new FileReader(); fileReader.onloadend = (e) => { this.arrayBuffer = fileReader.result; let data ...

Load new Wordpress posts seamlessly without any need to refresh the page automatically

I'm curious if anyone has thoughts on how to make Wordpress automatically display new posts on the homepage without needing to manually refresh? My guess is that this could be done with ajax/jQuery, but I haven't come across any suggestions yet. ...

How is it possible that this event listener is able to capture an event that was already sent before it was

I am facing an issue with my Vue JS code. When I click on the account <a> tag, it triggers the toggle method. The toggle method adds an event listener to the document. However, as soon as the toggle method is executed, the event listener fires and ...

Leveraging $this in conjunction with a jQuery plugin

I'm experimenting with a code snippet to reverse the even text in an unordered list: $(document).ready(function () { $.fn.reverseText = function () { var x = this.text(); var y = ""; for (var i = x.length - 1; i >= 0; ...