Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

108
Views
Use one() in inline onclick attribute

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!