-2

Why does a jQuery function inside a javascript function fire off increasingly for each time it's clicked? Clicked enough times it gets executed 100+ times per one click.

<div class="clickity" onclick="funky()">Test</div>

var x = 0;

function funky(){
    $('.clickity').on('click', function(){
        x += 1;
        alert(x);
    });
};

JsFiddle I'm just curious about why it works this way.

CDspace
  • 2,639
  • 18
  • 30
  • 36
  • Remove the `onclick="funky()"` and unwrap `$('.clickity').on('click', fn)` from a function declaration statement. – rishat Dec 01 '17 at 23:02

4 Answers4

1

Because every time you click on clickity, funky method is called and registers a new event listener on clickity. You're mixing two methods, either do:

var x = 0;

function funky(){
    x += 1;
alert(x);
};
<div class="clickity" onclick="funky()">Test</div>

or

var x = 0;

$('.clickity').on('click', function(){
    x += 1;
alert(x);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="clickity" >Test</div>
0

I don't understand, why insert the listener in the function? Every time you click add a new listener to the button. Every click execute the increment and add a new listener.

Valerio Cicero
  • 347
  • 4
  • 13
  • I was assigning an Id to onclick="func(id)" and using that id in my jquery $('.class'+id). so as not to have a for loop running each time I click or hover over an element to run hundreds of times just to find one number, will have to find a better solution tho :) – NewbieLearner Dec 01 '17 at 23:17
0

The addEventListener a.k.a. on in jQuery has a cumulative aspect. You are not assign it by replacing the old one but adding a new one and keeping the previous handlers chain.

bluehipy
  • 2,254
  • 1
  • 13
  • 19
0

You are combining class Javascript Onclick HTML attribute with jquery.

First round

  1. user clicks clickity
  2. a. funky is called because of HTML attribute onclick
  3. funky attaches a listener to clickety.
  4. note funky has not increased x on this first click.

Next round

  1. user clicks clickity
  2. a. funky is called because of HTML attribute onclick
  3. b. x is incremented by 1 because of jquery event listener to clickety attached in first round
  4. funky attaches a listener to clickety

Future rounds

  1. user clicks clickity
  2. a. funky is called because of HTML attribute onclick
  3. b. x is incremented by 1 because of jquery event listener to clickety attached in first round
  4. c. x is incremented by 1 because of jquery event listener to clickety attached in second round
  5. funky attaches a listener to clickety
ledlogic
  • 774
  • 1
  • 9
  • 19