0

I'm trying to add an object's function to a button that is created when some conditions are met. Does it matter if I have the var I'm trying to change outside document.ready?

var myvar = 1;
$(document).ready(function(){
 var myobj = {
  changeMyVar: function(){ myvar++;}
 }
...
/* button id='my-button' is created in a div id='mydiv' */
...
 $('#mydiv').on('click', '#my-button', myobj.changeMyVar);
});

No function is attached to the button and no error is thrown. In fact, console.log(myobj.changeMyVar) returns undefined. What am I missing here?

Edit: I lied about no errors, I get a 'undefined is not a function' on the .on() line.

Thanks!

Edit2: After further analysis, I discovered a silly type-o in my original code. Thanks for the answers!

1

2 Answers 2

1

I tried replicating your issue in a fiddle, but it worked.

Try this out http://jsfiddle.net/7fjk3wxs/1/

This is what I used:

var myvar = 1;
$(document).ready(function(){
 var myobj = {
  changeMyVar: function(){ 
      myvar++;
      alert(myvar);
  }
 };


 $('#mydiv').on('click', '#my-button', myobj.changeMyVar);
});
Sign up to request clarification or add additional context in comments.

Comments

0

After further analysis, I discovered a silly type-o in my original code. Thanks for the answers!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.