detecting user interactions with hyperlinks

Can links be intercepted in an Angular application to block specific URLs like YouTube links without adding custom attributes or elements?

Is it possible to intercept all clicks on links within the scope of a particular controller's view without modifying the HTML structure?

Answer №1

If you're working with Angular, you have the ability to create a custom directive for the <a> element and attach a click listener to it.

app.directive('a', function() {
    return {
        restrict: 'E', // only Elements (<a>),
        link: function(scope, elm, attr) {
            // Triggered each time the link is clicked
            elm.on('click', function($event) {
                console.log('event')
                $event.preventDefault()
                return false
            })
        }
    }
})

And just like magic!

If you need to restrict access to certain URLs, you can retrieve the href attribute within the link function using attr.href. Here's an example of how you can achieve this:

app.directive('a', function() {
    return {
        restrict: 'E', // only Elements (<a>),
        link: function(scope, elm, attr) {
            // Triggered each time the link is clicked
            elm.on('click', function($event) {
                 // Restrict specific URLs
                if(attr.href.match(/youtube\.com/)) {
                    $event.preventDefault()
                    return false
                }
            })
        }
    }
})

Answer №2

Below is a simple vanilla JS solution:

document.addEventListener("DOMContentLoaded", () => {
  document.querySelectorAll('a').forEach(a => {
    a.addEventListener("click", (event) => {
      event.preventDefault(); // Stop the page from loading
      alert(a.href); // Display an alert with the URL from the href attribute
    })
  })
});
<a href="https://example.com">Click here</a>

Answer №3

Here is a sample I created using jQuery:

// Code for handling click event on a link
$(document).ready(function(){
  $('.block').find('a').each ( function(){
      $(this).click(function(){
        console.log('custom-action');
          return false;
      });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="block">
    <div><a href="http://naver.com" target="_blank">OK</a></div>
</div>

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

encasing a snippet of code within a customized hyperlink

Here's the following "embed code" for an Instagram photo featuring Kim Kardashian. I'm curious - how can one encapsulate this embed code within an <a> tag (or another tag) so that clicking on the image will redirect to www.google.com? < ...

Transforming a JavaScript chained setter into TypeScript

I have been utilizing this idiom in JavaScript to facilitate the creation of chained setters. function bar() { let p = 0; function f() { } f.prop = function(d) { return !arguments.length ? p : (p = d, f); } return f; } ...

Switch between display modes by clicking using collections

I am trying to figure out how to create a function that will only show content for the specific element in which my button is located. Currently, when I click the button it shows content for all elements with the 'one' class, but I want it to dis ...

Having trouble uploading the file to Firebase storage

While attempting to upload files to Firebase using React, I encounter a perplexing issue. The file upload progress bar hits 100%, only to present me with an unfamiliar error message: { "error": { "code": 400, "message": "Bad Request. Could not c ...

The function of removing the ng-submitted class in AngularJS after form submission seems to be malfunctioning when using setPristine and setUnt

When a form is submitted in Angular, the class ng-submitted is automatically added by default. In my attempts to reset the form state by using $setPrestine and $setUntouched, I encountered some errors that prevented it from working properly. Examples of t ...

Grabbing a section of a URL through a bookmarklet: A simple guide

Recently, I've been using this handy bookmarklet: javascript:currentUrl=document.location.href;document.location.assign(currentUrl+'embed'); This neat tool grabs the current URL, such as www.example.com/knZg_INW8fL/, and adds embed to it f ...

Angular reactive forms can be customized to include a patched version of the matTime

I have an angular mattimepicker in my project. When trying to use it in a reactive form, I am encountering issues with patching the value to the edit form <h1>Reactive Form</h1> <form [formGroup]="form"> <mat-form-fie ...

Error: ReferenceError: The object 'angular' is not defined in the script.js file at line

I have gone through all possible solutions but none of them have helped me resolve the issue. I have a simple code that fails to execute due to the error mentioned. Here is my code index.html <!DOCTYPE html> <html data-ng-app="piApp"> & ...

The Angular date filter appears to be malfunctioning in Firefox

When formatting dates in my Angular application, I encountered an issue with the date value appearing differently in Firefox compared to Chrome. In Firefox, the date value displayed as: undefined NaN, NaN NaN:NaN:NaN PM However, in Chrome, it displaye ...

Creating a dynamic web application using Rails 4 and AngularJS for an enhanced user experience

Hey guys, I have this crazy idea that I've been tossing around in my head. I currently have a pretty standard rails app with content pages, a blog, news block, and some authentication. What if I turn it into a single page app? Here's what I envi ...

Exploring the world of React and Material Ui

As I delve into working with Material Ui in React, I am encountering difficulties when trying to customize the components. For instance, let's take a look at an example of the AppBar: import React from 'react'; import AppBar from 'mat ...

Steps for Disabling Autocomplete in a JSP Page

How can I prevent the browser from remembering the username and password on my JSP page after submitting the form? I've already tried using autocomplete=off in the JSP code. <form name="indexFrm" id="indexFrm" autocomplete="off" method="post"> ...

What causes the trigger of `app.get('*')` every time?

Check out this simple app: var express = require("express"); var app = express(); app.get("/json", function(req, res){ console.log("JSON route"); res.json({foo: "bar"}); }); app.get("/", function(req, res){ console.log("Slash route"); res.send(" ...

Leveraging the power of the map function to cycle through two arrays

Right now in React, I am utilizing array.map(function(text,index){}) to loop through an array. But, how can I iterate through two arrays simultaneously using map? UPDATE var sentenceList = sentences.map(function(text,index){ return <ListGr ...

Troubles with Vue and localStorage for storing a theme's data

I've been struggling with this issue for a while now while working on a Vue site. I have not been able to find a solution for my specific bug in other discussions. The concept should be straightforward - I want to have a switch that toggles a value b ...

Experiencing the issue of receiving unexpected commas following a div

Here is the code written in TypeScript for creating an HTML table that displays items from nested objects. The code is functional, but there seems to be an issue with extra commas being printed which are not part of any specific line being executed. im ...

Manipulate the visibility of a child element's dom-if based on a property retrieved from the parent element

Exploring the world of Polymer, I am eager to tackle the following scenario... I have a binding variable called {{readonly}} that sends data from a parent Dom-HTML to a child Dom-HTML in my Polymer project. The code excerpt looks something like this... C ...

Can you please elaborate on the concept of type coercion in JavaScript?

I've come across information stating that when comparing an object with a number, type-coercion occurs. ToPrimitive is called on the object which then invokes valueOf and, if necessary, toString. However, I'm struggling to understand how this pro ...

Having issues with the crucial npm installation of @babel/plugin-transform-react-jsx

Apologies for the inconvenience, but this is my first post. I encountered an issue during npm start, and received this error message: /Users/hp/Desktop/Wszystkie Projekty/ravenous/src/components/BusinessList/BusinessList.js SyntaxError: C:\Users\ ...

Angular JS has a unique feature of a scrollable drop-up menu that allows

https://i.sstatic.net/MOUqO.pngHere is the code snippet for my Dropup component: <div class="dropup"> <button class="btn btn-primary btn-raised dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false> ...