Home > Mobile >  Is there a way to unlink an specific part of of a <a> tag
Is there a way to unlink an specific part of of a <a> tag

Time:05-31

I have an card component which I wrapped with tag. In the tag, I have added some button. Now the problem is when I click on the button then the tag sends me to the URL but I don't want to go to a page when I click on a button.

I have tried event.stopPropagation() but It didn't work with tag. So, if there is any way to solve it please let me know.

Thank you

<a href="/somewhere">
    <button>Hide</button>

    <div>
        <div>
            <img src="" alt="" />
            <span>name</span>
        </div>

        <a href="/somewhere">Title</a>
    </div>
</a>

Here I want that the <button></button> tag will be unlinkable.

CodePudding user response:

heres a little example how you could manage to do it.

const wrapperRef = document.querySelector('#wrapperRef');
wrapperRef.addEventListener('click', (event) => {
if(event.target === wrapperRef.querySelector('button')){
  event.preventDefault();
  //what should happen if you click on button
}
})
<a id="wrapperRef" href="/somewhere">
    <button>Hide</button>

    <div>
        <div>
            <img src="" alt="" />
            <span>name</span>
        </div>
    </div>
</a>

You catch the click inside the wrapping a tag, then check if the target that has been clicked on is equal to the inside button. If so you stop redirecting and can add code (I think hiding the href) in the function.

Would be an addition of:

wrapperRef.style.display = 'none'

or delete it out of the dom:

wrapperRef.parentNode.removeChild(wrapperRef);

CodePudding user response:

It's not an good idea to have nested links inside link. Instead you can wrap your card items in div wrapper and locate this whole-card-size link inside it and style it. In Code Snippet below it's called .outer-link. We can stretch it to card size, so whole card will be clickable; Items, that also should be clickable inside this card could be moved in front of stretched links:

.inner-link,
.toggle-button {
  ...
}

In this case you don't have to create any JS code to override links behaviour, check Code Snippet:

const btnTrigger = () => {
  console.log('click');
}
.card {
  position: relative;
}

/* make link card-size */
.outer-link:before {
  content: '';
  position: absolute;
  height: 100%;
  width: 100%;
  top: 0;
  left: 0;
  background-color: #ff634721;
}

/* make inner link and button be in front of full-size link */
.inner-link,
.toggle-button {
  position: relative;
  z-index: 1;
}
<div >
  <button  onclick="btnTrigger()">Hide</button>

  <div>
    <div>
      <img src="https://dummyimage.com/200x200/000000/fff" alt="" />
      <span>name</span>
    </div>

    <a  href="/somewhere2">Title</a>
  </div>
  
  <a  href="/somewhere1"></a>
</div>

  • Related