How to have an element with a click event that only works if the element is visible on screen?

Viewed 30

I have an element with an @click attribute that clicks a different element on screen like this:

<div class="card" @click="$refs.detailsLink.$el.click()">

And $refs.detailsLink refers to this element:

<div class="hidden-mobile">
    <MyLink :id="$id('view-details')"
        ref="viewDetailsLink">
    </MyLink>
</div>

And hidden-mobile is a CSS style that is a part of a media query for mobile devices and simply makes the display be none:

  .hidden-mobile {
    display: none;
  }

The Problem: The problem is that when <MyLink> is hidden because it is a mobile device, the user can still click the card that contains <MyLink> and trigger the on click event.

So what can I do to this <div class="card" @click="$refs.detailsLink.$el.click()"> that checks if the element is even visible and if it is not, then don't triggers the click event.

2 Answers

You can use if else statements like that:

var elementId = document.getElementById('view-details');
if (elementId.style.display === 'none') {
    // do this
} else {
    // do that
}

In your click handler check and see if the display of the link is none.

I'm not sure what framework you're using, but I'm assuming there is some sort of reference to the element that was clicked, so just get that element and check its classList.

Related