Is there a way to prevent a link from activating when I click on one of its internal elements?

Within a div nested inside an "a" tag (specifically in Link within next.js), there is another div labeled as "like." When clicking anywhere within the main div, the intention is for it to redirect to the destination specified by the "a" tag. However, if the user clicks on the "like" div, the goal is not to navigate to a new page but rather trigger a JavaScript function.

How can this be achieved? Are there alternative methods? What is the optimal approach to ensure both functionality and maintain SEO-friendliness?

A comparable example can be found on Twitter: tapping on a tweet directs you to a separate page, while interactive elements like the "like" button perform their designated actions — this desired outcome is what I hope to replicate.

'use client'
import React from 'react'

interface LikeTypes {
    likes:number
}

function LikeCard({likes}:LikeTypes ) {

    const likeButtonClicked= () => {

      };
    

  return (
    <div className='flex justify-center items-center ' onClick={(e) => { e.nativeEvent.stopImmediatePropagation(); likeButtonClicked(); }}>❤ {likes}</div>
  )
}

export default LikeCard

I've attempted utilizing

e.nativeEvent.stopImmediatePropagation();
but have encountered issues with its effectiveness.

Snippet from the wrapping component housing LikeCard:

    <Link href={href}>
                  <LikeCard likes={likes}/>
    </Link>

Answer №1

stopPropagation is the key

document.querySelector('a').addEventListener('click', e => {
  e.stopPropagation()
})
<a href="https://example.com">
  Link: <span>Click Me</span>
</a>

Answer №2

You have two options to choose from in this scenario.

  1. Utilize the event object that is passed to the event handler.

    function anotherFunction(event) {

    event.stopPropagation();
    

    }

    This will prevent the default behavior of browsers.

  2. Alternatively, use

    href="javascript:void(0)"

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

Do designers often manually adjust elements using media queries when working with Bootstrap?

Is it common practice to directly invoke media queries in order to manually adjust the layout of elements when using Bootstrap? In other words, if I have a custom element that I need to display or position in a specific way, is it acceptable to call the m ...

Styling and scripting with CSS and jQuery in an external JavaScript file

Is it possible to add the jquery library from "http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" into an external .js file? And how can a .css file be included in a .js file? ...

The Apollo mutation is not showing up in the props list

Take a look at my component below: import React, { Component } from 'react'; import { gql, graphql, compose } from 'react-apollo'; export class ExampleComponent extends Component { render() { console.log("Checking this.props: " ...

I am facing a challenge with my data, as it includes start and end values representing character indexes for styles. I need to find a way to convert this information into valid HTML tags

I have some content from another source that I must transform into proper HTML. The content contains a string such as: "Hello, how are you?" Additionally, there is a separate section detailing styling instructions. For example: 'bold:star ...

React is unable to locate the component element within the DOM

I'm attempting to set the innerHTML for the div element with the ID of ed. Unfortunately, I am unable to access it once React has finished rendering. It seems that this is due to the render stages, as I am receiving a null value for the div element. W ...

Dynamic autocomplete feature with AJAX integration for filtering in Flask

Looking for some guidance on creating an HTML form with two input fields. Check out the HTML template code below: <form role="form" action="/cities/" method="get" autocomplete="on"> <label for="#input1"><strong>Country:</strong&g ...

Can you determine if a function is a generator function if .bind() has already been applied to it?

It seems like using .bind(this) on a generator function is interfering with determining if the function is actually a generator. Any suggestions on how to resolve this issue? function checkIfGenerator(fn) { if(!fn) { return false; } ...

What is the best way to dynamically set an ID in Angular using the pound symbol (#)?

I am currently developing a dynamic Angular 6 application that utilizes dynamic components. My approach involves using @ViewChild('<id>', { read: ViewContainerRef }) <id>; to reference the divs where I intend to populate with dynamic ...

Using jQuery to create clickable URLs within a rollover div

I am looking to have the div appear on a mouse over effect in the following code. Is there a way for me to input a url based on the data that is passed to it? Anchorage: ["Anchorage", "(555)555-5555"], (This represents the data being posted) AtlanticCit ...

Ways to mix up a term while maintaining the original first and final characters intact (Javascript)

I've been given a task to shuffle a word that has more than 3 letters while keeping the first and last letters unchanged. The revised word should not be identical to the original, ensuring some sort of rearrangement is apparent. For example, when sh ...

NextJs conveniently removes query strings from headers automatically

Whenever I access the following url , the query parameter fpr=marten48 is automatically removed from the header. How can I stop this from happening? ...

Ways to address memory leakage issues in Angular

Is there a way to manually optimize the Garbage Collector by forcefully pushing variables into it? For example, if we have a root or global level variable in an Angular component that is no longer needed when switching to another page, how can we ensure it ...

Assigning websockets to a global variable may cause them to malfunction

I'm utilizing websockets in conjunction with JavaScript and HTML5. Here is the code snippet I am currently working with: <input type="text" onFocus="so = new Websocket('ws://localhost:1234');" onBlur="so.close();" onKeyUp="keyup();"> ...

Spacing between the rows of a table

I am seeking to achieve a unique visual style for the rows in my table, similar to the one shown below. I attempted to use CSS border properties in the code snippet provided but desire more spacing between each row with a thin border and sharp edges. .dat ...

Understanding the hierarchy of LESS css class structure is crucial for

In my chat contact list, each contact can have a different state represented by classes: .online .offline .online .selected .offline .selected Here are the corresponding styles (example): .online { background-color: #fff; p { color: #000; } } . ...

How to modify color in React Material UI's ListItemIcon

I am struggling to make the list item icon red, can someone guide me on how to achieve this? Being a beginner in reactJS and Material UI icons, I find it challenging. This is the code for my button: <ListItem button> <ListItemIcon sty ...

having difficulty sorting items by tag groups in mongodb using $and and $in operators

I'm currently trying to execute this find() function: Item.find({'tags.id': { $and: [ { $in: [ '530f728706fa296e0a00000a', '5351d9df3412a38110000013' ] }, { $in: [ ...

Using feature flags in Vue for enhanced functionality

I am interested in incorporating a "feature toggling mechanism" into my Vue application. Although I have set up a basic system, I want to explore the methods outlined in a article by Pete Hodgson. The concept of "Inversion of Decision" seems particularly i ...

How about allowing markLabel to span across several lines for better readability?

Struggling to style my MUI Slider the way I want. Can't figure out how to make the markLabel CSS break my text into multiple lines. Using the slider for a "Strongly Agree, Agree, Neutral, Disagree, Strongly Disagree" selector, but text on smaller scre ...

Encountering a red squiggly line while working on an Angular 2 project in an HTML file within Visual Studio

Whenever I incorporate Angular 2 code into my HTML files, I notice red squiggly lines appearing like this: Hovering over the red squiggly lines does not reveal any errors or warnings. It may be worth mentioning that I am currently utilizing ReSharper Ult ...