Home > OS >  Getting jquery script to delete itself after executing
Getting jquery script to delete itself after executing

Time:09-11

I am a rookie web developer with a website containing 3 different items, each with its individual "contact me" button. When the button is pressed for the first time, the page scrolls down to display the form.

My problem is the event fires once pr button, instead of once in total. I want the script to fire once regardless of which button is pressed, then the script should delete itself or stop further executions.

I just don't see where this script fails. Please enlighten me :)

Below is a very simplified proof of concept with a jsfiddle attached.

https://jsfiddle.net/8wegb32s/

#megaspacer {
  height: 1000px;
}
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<input form="form"  type="radio" id="1" name="product" value="Value1" />
<input form="form"  type="radio" id="2" name="product" value="Value2" />
<input form="form"  type="radio" id="3" name="product" value="Value3" />
<div id="megaspacer">
  <!--Give me som space -->
</div>
<form id="anchor">
  <input type="text" name="name" id="name"  placeholder="Name*">
</form>
<script id="runonce">
  $(".orderbutton").one("click", function() {
    $('html, body').animate({
      scrollTop: $("#anchor").offset().top
    }, 2000);
    $("script").remove("#runonce");
  });
</script>

Solved in https://jsfiddle.net/gaby/g7bw1mkn/10/

CodePudding user response:

Do not remove the script. Just remove the event handler.

$(".orderbutton").on("click", function() {
  $('html, body').animate({
    scrollTop: $("#anchor").offset().top
  }, 2000);
  
  $(".orderbutton").off('click');
});

If you bind additional handlers on the same buttons, though, you will have to use a named function which is required when you want to remove only that.

function orderButtonClickHandler(){
  $('html, body').animate({
    scrollTop: $("#anchor").offset().top
  }, 2000);
  
  $(".orderbutton").off('click',orderButtonClickHandler);
}
$(".orderbutton").on("click", orderButtonClickHandler);

Or you can use the delegated form, where you bind the event handler to an ancestor of the buttons. This way, since it is only bound to a single element, it will stop functioning after the first use, as expected.

$("body").one("click", ".orderbutton", function() {
  $('html, body').animate({
    scrollTop: $("#anchor").offset().top
  }, 2000);
});
  • Related