Home > Net >  How to make inner elements of a container not able to be clickable and selected
How to make inner elements of a container not able to be clickable and selected

Time:05-10

I want to implement a loading state where when we click on the button, we make the container opacity to .32 and we shouldn't be able to click or select the elements inside the container. In the example below, the inner a tag is still clickable and selectable after the loading is shown.

const container = document.getElementById('container');
const btn = document.getElementById('load');

btn.addEventListener('click', () => {
    container.classList.add('loading');
})
#container {
  width: 300px;
  height: 300px;
  background: tomato;
}

.loading {
  opacity: .32;
  user-select: none;
}
<div id="container">
    <a href="www.google.com">Test</a>
    <a href="www.google.com">Test</a>
    <a href="www.google.com">Test</a>
    <a href="www.google.com">Test</a>
</div>

<button id="load">
  Load
</button>

CodePudding user response:

Have you looked into using pointer-events: none; from CSS? See running snippet below.

const container = document.getElementById('container');
const btn = document.getElementById('load');

btn.addEventListener('click', () => {
    container.classList.add('loading');
})
#container {
  width: 300px;
  height: 300px;
  background: tomato;
}

.loading {
  opacity: .32;
  user-select: none;
  pointer-events: none;
}
<div id="container">
    <a href="www.google.com">Test</a>
    <a href="www.google.com">Test</a>
    <a href="www.google.com">Test</a>
    <a href="www.google.com">Test</a>
</div>

<button id="load">
  Load
</button>

CodePudding user response:

I believe what you are trying to do is, disabling the anchor tag. For this, you can simply use the following property in the CSS: pointer-events: none;.

With this even if the anchor tag is clicked, nothing will happen.

  • Related