Connecting with javascript through the href attribute, but lacking support for JavaScript

A link with a JavaScript href has been created:

<a href="javascript:document.location='http://'+location.hostname.replace('.com', '.co.uk')">stackoverflow uk</a>

Is there a way to provide a direct link like this when JavaScript is disabled?

<a href="http://stackoverflow.co.uk/questions/ask"> stackoverflow uk</a>

I am aware of the noscript tag:

<noscript><a href="http://stackoverflow.co.uk/questions/ask"> stackoverflow uk</a></noscript>

However, this will show both the broken link and the correct link. How can I remove the broken link from the user interface?

Answer №1

Let's spice up a simple link:

<a id="foo" href="http://example.com">example</a>

Next, let's attach a JavaScript event handler to it:

const link = document.getElementById('foo'); // OR some other method to target the link
link.addEventListener('click', customHandler);

function customHandler(event) {
    // Add any additional actions you want to perform
    // ...
    // just remember to prevent the default link behavior
    event.preventDefault();
}

For more information: Progressive Enhancement and Unobtrusive JavaScript

Answer №2

Check out the following pseudo code snippet:

<a href="normalLink" onclick="execute javascript to dynamically create and submit a new link; return false">text</a>

In this code, the default normal link is used as a fallback option. However, when a user has JavaScript enabled, the onclick event will trigger first instead of the original link. The 'return false' statement is included to prevent the actual link from being activated.

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

Is there a way to substitute certain values retrieved from a database within sails?

I am currently working on replacing fields in the data retrieved from a database using sails. async.waterfall( [ function getscores(callback) { Score.find({course : courseId}).paginate({page : 1 , limit: 10}).populate('course') ...

Change the object's property names from camel case to sentence case

Consider an array of objects like this: data = [{keyOne: 'value1', keyTwo: 'value2'}, {keyOne: 'value3', keyTwo: 'value4'}]; We need to change it to look like this: data = [{Key one: 'value1', Ke ...

Is it more beneficial to categorize REST-based modules/controllers by resource or by specific action/feature?

I'm facing a scenario that goes like this: Endpoint 1: Retrieve all books in the United States owned by John with a GET Request to /country/us/person/john/books Endpoint 2: Get all books owned by John in every country with a GET Request to /person/j ...

Show an image within my project's .rdl report that is located in a specific folder

Looking for guidance on how to incorporate an image into an .rdl report in visual studio. The image should be dynamically displayed according to a parameter (ndc number) and the images are located in an images folder within my solution. Any assistance wo ...

Utilize Google Analytics without Tag Manager to track page views with hashed URLs using AJAX requests in a Single Page Application (SPA) web application

I am currently working with a web application (AJAX/SPA type) that I did not develop, but now need to track analytics for. The URLs generated by the application are not very user-friendly or semantically structured, as they are mainly ran via AJAX calls. U ...

How can I pass a JavaScript variable through the URL in a Rails 4 application to access it in the controller?

Struggling to pass the value of a JavaScript variable in the URL and then retrieve it in my Rails 4 app controller using param[:my_variable]. Despite trying various methods, none seem to work for me. I am unable to successfully pass my JavaScript variable ...

Guide on adding an element following a directive in Angular 4

My AngularJS directive is functioning correctly with jQuery, but now I want to convert it to Angular 4. Previous Directive (AngularJS) app.directive('errName', function () { return { link: function (scope, element, attrs) { ...

How can I stop the accordion from toggling in Bootstrap V5 when clicking on an element in the header?

In the latest version of Bootstrap, v5, it seems that using e.stopPropagation(); no longer prevents the accordion from toggling when an element in the header is clicked. Do you have a solution for this problem? How to prevent accordion from toggling when ...

AngularJS: Share event from the parent component exclusively with its child components

I am looking to establish a way to broadcast an event from a parent directive to a specific child, without all children in every instance of the "parent" directive receiving it when using scope.broadcast in the parent directive link function. Current Beha ...

Serve Webpack bundle on various routes - Express Way

I recently completed a web application using an Express backend and React frontend. Upon sending a request to the Express server, it undergoes a process where the URL is checked against the backend routes. If there isn't a match, the React bundle gen ...

JavaScript method to refine JSON Data

I have a JSON dataset of job information, with each job containing the following details: { jobs: [ { jobseeker_create_job_id: 1, job_title: "Fashion Designer", job_description: "Fashion Designer", salary: ...

Steps for removing the bottom border for the last child in the Material UI Box Component

I have a Box Component where ListItems are wrapped. For each child, I have a border-bottom of 1px solid class set for the Box component, but I don't want it for the last child. How can I achieve that? {data.map((item, i) => { return ...

Error: The program encountered a type error while trying to access the '0' property of an undefined or null reference

I am a beginner in the world of coding and I am currently working on creating an application that allows users to add items to their order. My goal is to have the quantity of an item increase when it is selected multiple times, rather than listing the same ...

Using FB Messenger iOS to verify a third-party app

I am in the process of creating a web application that features Facebook authentication and the capability to invite friends through Facebook. While working on this project, I encountered a specific issue that is quite frustrating and I am hoping someone o ...

Updating NodeJs to Express 4.0 may result in encountering errors

Hey there, I've been diving into node.JS and the express module recently and came across this helpful resource link However, when attempting to update the dependencies to express 4.0 in the example provided, it seems to break. I understand that app.c ...

Difficulty in querying a DynamoDB GSI Composite key with the .NET Core Object Persistence Model

I am struggling with querying a GSI composite key using OPM. Even after following the documentation example provided in this link, I continue to face two issues: 1). While attempting to execute the code similar to the example mentioned, I encounter errors ...

I am attempting to simultaneously filter an array of objects based on both numerical and string values

I'm facing an issue with my App. It's a basic application that displays restaurant tables and allows users to filter the tables based on the number of people (capacity) and preferred location (Inside, Patio, Bar). The problem lies in the filteri ...

Searching for all potential arrays of length L that total N or fewer can be achieved using an algorithm

In JavaScript, I am looking for a way to discover all potential arrays - consisting of non-negative integers - with a size L that add up to - at most - N: function findArrays(size, maxSum){} For example: findArrays(3, 2) Sample output: [[0,0,0], [0,0,1], ...

Using the $ sign to choose a subdocument in mongoose

Here is the structure of my document: "event": { "attendants": { "seekers": [ { "$oid": "5bcdabd27e51de001576d289" }, { "$oid": "5bc9b39c1a48dd0d7d521924" } ...

Tips for setting up bootstrap scrollspy in Angular 6

Working with Angular 6 and Bootstrap 4, I am trying to integrate Bootstrap's scrollspy component into my setup. However, Bootstrap requires jQuery and I am facing difficulties in getting it to work properly. HTML <header> <div class="head ...