Home > Enterprise >  Use one() in inline onclick attribute
Use one() in inline onclick attribute

Time:10-27

I have a function that is triggered on an inline onclick.

What I want is for that function to get called only once but don't know how to do that with an inline onclick. It's working at the moment but runs everytime the user clicks rather than just once.

This is how I have it:

HTML

<div class= "container" onclick="modal('#modal')"></div>

I have tried having it as a Jquery function as follows and remove the above click but that is not working either:

$(".container").on( "click", modal( '#modal') {
  alert( "The event happened!" );
});

Any idea how to make it so the function only runs once?

Thank you

CodePudding user response:

If you wish to use jQuery's one(), you'll need to remove the onclick from the HTML, and change the JS to read:

$( ".container" ).one( "click", function() {
  alert( "The event happened!" );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class= "container">Container</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

This way, the alert() will only show on the first click.


If you wish to use the on() as stated in your question, use $(this).off('click'); to remove the event listener after the fist press:

$( ".container" ).on( "click", function() {
  alert( "The event happened!" );
  $(this).off('click');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class= "container">Container</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related