Prevent the default action on all anchor links in HTML using JavaScript code

I'm exploring the possibility of updating URLs using JavaScript alone, by refreshing content through AJAX.

This approach aims to avoid the unwanted side effects of traditional page refreshes, such as interrupting music playback or clearing input fields like chat messages.

  1. Stopping the current music playback
  2. Losing unsaved work, such as typed messages

I've recently started experimenting with this concept and here's what I have so far:


var links = document.querySelectorAll('a');
for (let i = 0; i < links.length; i++) {
    links[i].addEventListener('click', function(event){
        event.preventDefault();
    });
}
return false;

However, there are a couple of issues with this code:

  1. The URL doesn't get updated
  2. AJAX content is not loaded

My question is: how can I prevent the page from refreshing but still allow the URL to be changed?

Answer №1

Consider trying the following approach:

let links = document.getElementsByTagName('a');
let xhr;

for (let i=0; i<links.length; ++i) {
   links[i].addEventListener('click', handleLinkClick, false);
}

function handleLinkClick(event){
    event.preventDefault();
    if(xhr) xhr.abort();
    
    xhr = new XMLHttpRequest();
    xhr.onload = updatePageContent;
    xhr.open("get", this.href, true);
    xhr.send();
}

function updatePageContent() {
    // Implement logic to update page content using `this.responseText`
}

Answer №2

If you're looking for a different way to structure your URLs, consider using a hash-based URL scheme:

someurl/#param1

someurl/#param2

...

Answer №3

const links = document.querySelectorAll('a');

for(let i=0; i < links.length; i++) {
    addClickEvent(links[i], 'click', disableDefault);
}

function disableDefault(event) {
    event = event || window.event;
   (event.preventDefault)? 
       event.preventDefault() : e.returnValue = false;
}

function addClickEvent(element, eventType, callback){ 
   if (element.addEventListener){ 
       element.addEventListener(eventType, callback, false); 
       return true; 
   } 
   else if (element.attachEvent){ 
       var result = element.attachEvent("on"+eventType, callback); 
       return result; 
 } else { 
       return false; 
 } 
}

Check out this solution I found on how to prevent default for all links inside a div using jquery

Answer №4

Experiment with this technique, using jquery .load()

html

<div class="1">content 1</div><div class="2">content 2</div>
<a class="1" href="#">update 1</a>
<a class="2" href="#">update 2</a>

js

$(function() {
var url = "http://sample.org";
    $("a").each(function(i, el) {
        $(this).on("click", function(e) {
          e.preventDefault();
            if (i === 0) {
              $("div.1")
              .load(url + " #" + $(el).attr("class"));
             };
            if (i === 1) {
              $("div.2")
              .load(url + " #" + $(el).attr("class"));
            };
        })
    });
});

Check out the jsfiddle demo http://jsfiddle.net/guest271314/dL4b4/

Answer №5

Give it a shot

 $("a[href=#]").on("click", function (event) {
    event.preventDefault();
 })

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 MongoDB update functions in JavaScript

I've encountered some difficulties while using the MongoDB API to update a document. Despite trying various methods, none of them have been successful so far. Strangely enough, inserting and deleting documents work perfectly fine. Let me explain what ...

Display a React Native modal within another modal

Is it possible to open a modal from within another modal in react native? For example, if I have a form in one modal and a color picker field within that form, how can I open the color picker in a separate modal? Name: XYZ Age: 21 Color: A (Clicking thi ...

Receiving binary information through enyo.Ajax

I am currently facing an issue while trying to download an image, which is essentially a chunk of binary data, using imagelink and enyo.Ajax module. A warning message pops up stating: "Ajax request set to handleAs JSON but data was not in JSON format ". Be ...

Why does the jQuery hide function fail to work on a div with the same class after an ajax

1. I'm encountering an issue with my code. I have a div class "inner" which is being dynamically loaded via an ajax call. However, after the ajax call, if I click the hide button, it doesn't work. Strangely, it was working perfectly fine before ...

Guide on removing the parent JSON array while retaining the child JSON array

I have been searching for a solution to remove specific JSON array elements, but I have not found one yet. Here is the JSON data I am working with: [ { "KODE": [ { "name": "kode", "value": [ ...

When working with Visual Studio and a shared TypeScript library, you may encounter the error message TS6059 stating that the file is not under the 'rootDir'. The 'rootDir' is expected to contain all source files

In our current setup with Visual Studio 2017, we are working on two separate web projects that need to share some React components built with TypeScript. In addition, there are common JavaScript and CSS files that need to be shared. To achieve this, we hav ...

When a POST request fails, which AJAX event is triggered?

How can you handle a failed post request in jQuery AJAX? Suppose the site shows this message: POST http://s-t-h-c.appspot.com/dispatch 500 (Internal Server Error) which AJAX event should you use to address it? In case of a successful request, we typicall ...

Best practices for managing JWT tokens on the front-end with fetch requests and secure storage methods

Currently trying my hand at development, I am working on a task manager app where I've implemented JWT tokens for verification. While I managed to make it work on Postman, I'm stuck on how to store the token in a browser and send it to the server ...

Extract the element from one array that is not present in another array

I am attempting to extract the values from arrayOne that do not appear in both groups within arrayTwo. In the example below, I am looking to identify b and d for group1 and a and b for group2. arrayOne = ['a','b','c',' ...

Strategies for enabling form resubmission in AngularJS when encountering a Sequelize validation error

Having issues with the form.$valid property in my SignUp controller for user registration. It seems to be stuck at false when a validation error is thrown by Sequelize. Any suggestions on what I should modify in my controller? Perhaps resetting the $vali ...

Guide on how to modify the color of a single row within a table with just a click

My table structure is as follows: <table> <tr> <td>A1</td> <td>A2</td> <td>A3</td> <td>A4</td> </tr> <tr> ...

The .angular-cli.json file is causing issues with loading scripts

I have recently updated my .angular-cli.json file by adding new scripts in the following format: "apps": [ { "root": "src", "outDir": "dist", "assets": [ "assets", "favicon.ico" ], "index": "index.html ...

Retrieving a partial view using an XMLHttpRequest

My website homepage itself is around 25K in size, but with several PNG images included it reaches about 2 MEG once fully loaded. I am considering loading the page initially without any images (or excluding the banner that has all the PNGs and some HTML), ...

Align component within material-ui grid

Looking to center align the same cards but not just the grid component, I need the content itself to be equally distant from the borders and each other. I've searched and tried different solutions without luck. https://i.stack.imgur.com/aZj7H.png htt ...

extract elements from dataset

Attempting to splice an array but encountering index issues var kode_pelayanan = []; function deleteKodePelayanan(index){ kode_pelayanan.splice(index, 1); console.log(kode_pelayanan); } Experimented in the console with an array for kode_pelayanan ...

When toggling visibility with JS, the Bootstrap Grid Row may not center-align as expected

Sorry for the odd spacing issue that might occur. I currently have a basic Bootstrap Grid setup as follows: <div class="row justify-content-center" align="center" id="details"> <div class="col-sm-2"> ...

What makes it possible for Vue v3 to handle variables that are undefined?

We are in the process of developing a web application that monitors analytical changes and updates them in real time. While this may not be crucial information, we thought it would be worth mentioning. If you visit Vue.js's official website at https: ...

Combining various Google calendar feeds into a single JSON object using JavaScript

I'm currently in the process of integrating JSON feeds from multiple Google calendars to organize upcoming events and showcase the next X number of events in an "Upcoming Events" list. While I initially achieved this using Yahoo! Pipes, I aim to elim ...

When initializing React Native, the Android, iOS, and app folders seem to be missing

https://i.sstatic.net/bkmvE.png Where have my android, ios, and app folders gone? Also, why are the index js files missing? I am currently working with React Native version 0.1.10 on a Windows 7 operating system. ...

Can files be saved using AngularJS JavaScript with Windows-1250 encoding?

I am currently working on a web application using AngularJS and SpringBoot API REST. My challenge involves calling a REST API with a GET request to retrieve a flow of text data, and then attempting to save this data in a file with the charset WINDOWS-125 ...