smolus
smolus

Reputation: 125

Adding buttons inside <a> tag

So basically I have a list of elements that look like this: enter image description here

I want the whole div to be a link to another page and have the two buttons on the side do some javascript things. Html doesn't seem to allow any nested interactive elements. Buttons and other things dont work inside an <a> tag and vice versa. Can someone give me some ideas on how can this be achived?

Upvotes: 0

Views: 116

Answers (2)

Dejan.S
Dejan.S

Reputation: 19158

You could also do like this. You have a link inside the div that is your link to, give it an pseudo element with position absolute, that way it will cover the full element and now you give your buttons a z-index of 1 and they are above that pseudo element, this would also apply for other links inside there without having to stop propagation ect.

const button = document.querySelector('.js-console-log')
button.addEventListener('click', () => {
  alert('I dont trigger the link')
})
.header {
  position: relative;
  padding: 3rem;
  border: 1px solid deepskyblue;
}

.header__link {
  font-size: 2rem;
}

.header__link::after {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}

.button {
  position: relative;
  padding: 1rem;
  background-color: aqua;
  border: none;
  z-index: 1;
}
<div class="header">
  <a href="#0" class="header__link">Link to this awesome place...</a>

  <button class="button js-console-log">I'll do something</button>
</div>

Upvotes: 1

Kosem
Kosem

Reputation: 373

Here is one way to achieve that, and that is by doing:

<div onclick="location.href='index.html'"></div>

Upvotes: 2

Related Questions