Deactivating a hyperlink on my print-friendly webpage with JavaScript

My code is designed to generate a printable version of a webpage by duplicating the HTML content and then making certain modifications, such as deactivating buttons upon page load.

In addition to disabling buttons, I also aim to deactivate all links on the page. It doesn't matter if they still visually appear as links, as long as they don't have any functionality and don't trigger any JavaScript errors! Unfortunately, the anchor tag does not support a disabled attribute...

Regrettably, I am unable to utilize jQuery for this task, so I need a solution using only JavaScript!

Edit: My goal is to prevent users from interacting with the 'printable page' in another window by disabling links, buttons, and other elements on the page. This way, it will act as a static 'frozen snapshot' of the original page that users intend to print.

Answer №1

By setting the href attribute to "#" and replacing the onclick event, you can achieve the desired result.

let anchorTags = document.getElementsByTagName("A"), k;
for (k = 0; k < anchorTags.length; k += 1) {
    anchorTags[k].href = '#';
    anchorTags[k].onclick = function () {
        return false;
    };
}

Answer №2

Have you considered using jQuery for this task? It offers a much smoother solution...

$('a').each(function(){this.onclick=function(){return false}});

However, if you prefer a more traditional approach in vanilla JavaScript, here is a simpler method that does not require modifying the links directly. By setting the onclick event to return false, you can prevent the link from being visited:

var anchors = document.getElementsByTagName("a");
    for (i = 0; i < anchors.length; i++)
        anchors[i].onclick = function(){return false};

Answer №3

In addition, the document object contains a variety of links. Although I have not personally attempted it, I think it is possible to manipulate them as well.

for (i=0;i<document.links.length;i+=1) {
  document.links[i].href = 'https://example.com';
}

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

What is the proper way to detach an event listener from a class?

I am facing a challenge when trying to remove an event listener. After running the script, I receive an error message stating that changeGirl.off("click") is not a function. Despite this issue, everything else within the code is working perfectly fine. Any ...

Ways to verify if the user has inputted a typeahed value

My code snippet looks like this: var students = new Bloodhound({ datumTokenizer: Bloodhound.tokenizers.obj.whitespace('fullName'), queryTokenizer: Bloodhound.tokenizers.whitespace, remote: { ...

Issue with 1.bundle.js not loading during webpack production build with routing

I have been encountering an issue with my test repository for this specific problem (Link) It appears that the problem lies within the localization file, as I am using react-intl. The development version seems to be functioning properly. This is what&ap ...

Incorporating a javascript library or plugin into Vue.js code

Hey there, I recently came across the really cool component called vue-social-sharing. It's my first time using a library like this and I'm a bit confused on how to set it up properly. I've installed it through NPM, but when it comes to the ...

Encountering a problem when trying to utilize material-ui icons in a React application

After installing the Material-UI core and icons packages using npm install @material-ui/core and npm install @material-ui/icons in my React app, I tried to use the FileUploadIcon. Here's how I imported it: import { FileUploadIcon } from '@materia ...

Highlight dates in Vue.js that are overdue using a date filter

Currently, I have a Vue filter set up to display dates in a visually appealing way. However, I am looking to enhance the filter by adding a feature that would highlight dates in red if they are overdue (meaning the date is earlier than the current date). I ...

Preserving the background image on an html canvas along with the drawing on the canvas

Can users save both their drawings and the background image after completing them? var canvas = document.getElementById("canvas"); // This element is from the HTML var context = canvas.getContext("2d"); // Retrieve the canvas context canvas.style.ba ...

An error in Coffeescript and Express.js: attempting to call the 'sliced' method on an undefined object

Currently working on my debut app using express.js and coffeescript. Want to take a look? Find the code here: https://github.com/findjashua/contactlist However, upon attempting to run it, I encountered the following error: /Users/jashua/local/lib/node_mo ...

How to retrieve an anchor element from a list using JavaScript

My current code loops through each <li> within a <td> cell and adds a class to the <li>. I have now inserted <a> tags between each <li> and am facing challenges in accessing the <a> tags. What I actually want is to assig ...

Retrieving the IDs of all socket connections in a Node.js Socket.IO array

I currently have a complex program utilizing socketio 0.9 where I am storing all the sockets id in arrays like so: var clients = {}; To uniquely identify and store my sockets, I assign them a serial and then set the 'socket' key with its actual ...

There seems to be a clash between Modal Semantic UI React and Bootstrap causing issues

I created a project using .net core MVC. I have integrated the semantic-ui-react modal by importing its library and linking the CSS for it to function properly. However, I encountered an issue where the bootstrap CSS was conflicting with the CDN for semant ...

Steps for clearing input field with type=date in Protractor:

I am currently working with protractor version 4.0.4 and I'm encountering an issue where I cannot clear a date input field. It seems like Chrome is introducing some extra controls that are causing interference. You can find further details about Chro ...

Ensure that the contents of the upper and lower divs are appropriately aligned, while maintaining the centered positioning of the

As a complete beginner in the world of HTML and CSS, I am facing a challenge with my code. Here's the HTML snippet: <section class="instructions"> <div class="row"> <div class="instructions-col" ...

Implementing CSS styles with the className attribute in a Material UI component within a ReactJS application sourced from a dynamic JSON object

I have a dynamic JSON object that includes a button element. I am using createElement and Material UI to display the data from this object. I wanted to add custom CSS styling to the button component using className, but I've been struggling to achiev ...

Code in JavaScript: Generating Random Number within a Loop

Can anyone help me come up with a unique JavaScript loop that can guess a correct number within the range of 1-500? I want each iteration of the loop to generate a new number that has not been guessed before, but it should guess in a random order. For ex ...

The execution of dynamically generated Javascript in JSON format, returned through AJAX, is prevented when it is appended

Recently, I encountered an issue on my webpage where I made an AJAX request to a PHP script. The PHP script responded with a valid JSON object and set the Content-type header to application/json. After examining the JSON format using console.log(JSON.stri ...

Tips for extracting a value from a currently active list item's anchor tag with JQuery on Mapbox API?

Currently, I am attempting to extract the value from a forward geocoder that predicts addresses while a user is typing. My goal is to then send this value to a form with an id of "pickup". However, I am encountering difficulties in capturing the li > a ele ...

What is the best way to interweave my objects within this tree using recursion?

I am working on creating a new function called customAdd() that will build a nested tree structure like the one shown below: let obj = [] let obj1 = { key: "detail1Tests", id: "94d3d1a2c3d8c4e1d77011a7162a23576e7d8a30d6beeabfadcee5df0876bb0e" } ...

Is there a way to display my array within my React component using JavaScript?

I am working with an element that looks like this: const DropdownElements = [ { key: 1, title: "City", placeholder: "Select City", apiUrl: "https://api.npoint.io/995de746afde6410e3bd", type: "city&qu ...

Move the components over to the right

How can I vertically align the user and the search bar on the right side of the page? #search { float: right; margin-top: 9px; width: 250px; } .search { width: 230px; height: 30px; position: relative; line-height: 22px; } ...