2

I want to create a flashing effect. When user click the flashing element, it will be disappeared. However, it seems not every "user's click" can fire the "click event". Sometimes, when I clicked the flashing element, it didn't disappear. I thought the reason is a hidden element can not be clicked. Just like this article says CSS: Is a hidden object clickable?. So, is there other methods to make the flashing element disappeared immediately when user clicks the element?

var flashToggle = setInterval(function() {
  $("div").toggle();
}, 200)

$("div").on("click", function(e) {
  clearInterval(flashToggle);
  $(this).hide();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div>Flashing element</div>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
bcjohn
  • 2,383
  • 12
  • 27

5 Answers5

1

Yes, hidden/toggle will hide elements by setting the css display. When hidden, elements can not receive clicks. You can try the following:

  1. Use .css('visibility','hidden|visible') instead. This is recommended as it does not have the side effect of changing container size and causing jiggling of other elements.

  2. Wrap your flashing element inside a container element, register the click on the container element instead.

David Lin
  • 13,168
  • 5
  • 46
  • 46
  • Thanks a lot. Although method 1 can't work(The visibility: hidden element can not fired click event either), method 2 can remove the flashing element immediately! – bcjohn Jul 17 '18 at 02:48
1

Put the flashing element inside another element, and put the handler on that parent element. Also, you might change the visibility property of the flashing element, not the display of the flashing element, so that it doesn't change the layout of your page every time it appears or disappears.

const child = $('#child');
let visible = true;
var flashToggle = setInterval(function() {
  visible = !visible;
  child.css('visibility',
    visible
    ? 'visible'
    : 'hidden'
  );
}, 500)

$("#container").on("click", function(e) {
  clearInterval(flashToggle);
  $(this).hide();
})
div {
  background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="container">
  <div id="child">Flashing element</div>
</div>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

Try to use opacity : 0|1 instead of display: none / visibility: hidden. On click event on opacity: 0 worked for me. It worked for me.

Sofiane
  • 103
  • 2
  • 10
0
$(this).hide(); ---> $("div").hide();
Quang Dat Pham
  • 178
  • 1
  • 12
0

I think this might be what you're looking for: $("my-element").click()

Lapys
  • 936
  • 2
  • 11
  • 27