0

I have got a big "click" function in jQuery with a lot of code like this:

$(".Line1").click(function () {
    ...
}

I am creating new buttons dynamically which means that the "click" function doesn't trigger. Now I know that I could add a function like this in order to get it working:

$("#myButton").on('click', function () {
    ...
});

The problem is that my code in the normal click function is too long so I can't just copy and paste it into the new function, it would be way too confusing.

Is there a way where I can link it back up with the old click function? Or can you think of anything else?

Tom el Safadi
  • 6,164
  • 5
  • 49
  • 102
  • If you have to repeat whole actions which has been performed on first button click, then simply move that code in a function and then refer that function in each button's click event. – Nishesh Pratap Singh May 03 '17 at 01:53

2 Answers2

3

jQuery +1.7 .on()

$('body').on('click', '#myButton', function () {
    ...
});

Other versions (+1.4.2) .delegate()

$('body').delegate('#myButton', 'click', function () {
    ...
});

More info: Event binding on dynamically created elements?

Community
  • 1
  • 1
Mehdi Dehghani
  • 10,970
  • 6
  • 59
  • 64
0

You can either trigger the first click as such

$(".Line1").click()

Or better move your large piece of code into a function so you can run it from the second click.

luly
  • 614
  • 3
  • 9