Ad

Alert Shows Up Twice Instead Of Once

- 1 answer

My code contains two divs with the same class ("box") but different ids as follows:

<div class="box" id="inside1">
  <button>Hey</button>
</div>
<div class="box" id="inside2>
  <button>Hey</button>
</div>

Within each div is a <button> that is hidden. Once one "box" is clicked, both buttons appear. If the user clicks one of the buttons, the message "hey" should be pushed to an array (either array1 or array2, depending on the button the user clicked) and that array should be alerted:

alert(array1[0]); // or alert(array2[0]) depending on button clicked

My code works fine, but the problem is, after clicking one of the buttons and getting 1 alert, if I click the other button, I get 2 alerts instead of just 1.

Here is my code:

var array1 = [];
var array2 = [];

$('body').once('click','.box', function() {
  $('button').show();

  var id = $(this).attr('id');

  function x(array) {
    $('button').click(function() {
      array.push("hey");
      y(array);
    });
  }

  function a() {
    if (id == "inside1") {
      x(array1);
    }
    if (id == "inside2") {
      x(array2);
    }
  }
  a();
});

function y(array) {
  alert(array[0]);
}

And the JSFiddle.

Ad

Answer

Look at this.

function x(array) {
        $('button').click(function() {
          array.push("hey");
          y(array);
        });
      }

You are registering the click event every time you call x method, which you do on the click event.

You should move out the click event handler registration outside of your method. Something like,

$(function(){
 var array1 = [];
 var array2 = [];    

  $('button').click(function() {
      alert('clicked');
  });

});

Complete-simplified version of your code is

$(function(){

  var array1 = [];
  var array2 = [];

    $('button').click(function() {

      var id=$(this).closest(".box").attr("id");
      if (id == "inside1") {
          y(array1,'hey');
      }
      else if (id == "inside2") {
          y(array2,'hey');
      }        
    }); 

    $('body').on('click','.box', function() {
       $('button').show();     
    });    

});

function y(array,val) {
  array.push(val);
  alert(array[0]);
}

Here is a complete working sample.

Ad
source: stackoverflow.com
Ad