Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to block the triggering of a link if I click on its internal element?

I have a div that is inside an "a" tag (Link in next.js), and there is also a "like" div inside it. If I click anywhere in the div, I want it to take me where the "a" tag points. However, if I click on the "like" div, I don’t want it to take me anywhere; instead, I want a JavaScript script to be triggered.

How to do this? Is there any other way? How should it look to be both functional and SEO-friendly?

On Twitter, there’s something similar: the entire "tweet" is clickable and takes you to another page, whereas buttons like "like" work as they should, and that’s the effect I want to achieve.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

'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 tried use
e.nativeEvent.stopImmediatePropagation();
but is not working.

part of outside component wraping LikeCard

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

>Solution :

preventDefault should work

document.querySelector('button').addEventListener('click', e => {
  e.preventDefault()
})
<a href="https://stackoverflow.com">
  Post: <button>Like</button>
</a>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading