Home > Blockchain >  JQuery Nested onclick function running twice
JQuery Nested onclick function running twice

Time:11-01

I have used the document.ready function of JQuery with onlick function inside of it which is triggered when clicked the button with id="btn1" adding text before the image.

similar onclick button "btn2" function is inside of it which is adding text after the Image.

The Problem I am facing is that when I run it 1st time all is working fine but when I click the "insert before" button 2nd time and then click "insert after", the text after is outputted 2 times.

$(document).ready(function(){
  $("#btn1").click(function(){
    $("#check").before("<b>Before</b><button class='btn2'>Insert after</button>");
    $(".btn2").click(function(){
    $("#check").after("<i>After</i>");
  });
  });

  
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>


</head>
<body>

<img id="check" src="/images/w3jquery.gif" alt="jQuery" width="100" height="140"><br><br>

<br>
<button id="btn1">Insert before</button>
</body>
</html>

CodePudding user response:

I would not advice you to have a click event inside another click event.

What you need to is this:

$(document).ready(function() {
  $("#btn1").click(function() {
    $("#check").before("<b>Before</b><button class='btn2'>Insert after</button>");
  });

  $(document).on("click", ".btn2", function() {
    $("#check").after("<i>After</i>");
  });
});

What happens when you have a click event inside another click event is this:

Lets say we have ClickEvent1 & ClickEvent2.
ClickEvent2 is inside ClickEvent1.

When ClickEvent1 is triggered it will bind ClickEvent2 to the selector.
If you trigger ClickEvent1 again, then you will bind ClickEvent2 once more. That means if you trigger ClickEvent2 it will run the code 2 times.

Demo

$(document).ready(function() {
  $("#btn1").click(function() {
    $("#check").before("<b>Before</b><button class='btn2'>Insert after</button>");
  });

  $(document).on("click", ".btn2", function() {
    $("#check").after("<i>After</i>");
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img id="check" src="/images/w3jquery.gif" alt="jQuery" width="100" height="140"><br><br>

<br>
<button id="btn1">Insert before</button>

  • Related