I have an .aspx
page and a separate .js
file that contains all of my JavaScript
and jQuery
. The page also has a UserControl
that doesn't exist on page load and that only appears when a certain button is clicked. And the UserControl
contains, among other things, a JavaScript
button.
The problem I'm having is connecting the newly-created JavaScript
button that didn't exist on page load to my .js
file.
At first I tried adding a jQuery
select to get the button that lives inside the UserControl
to the document.ready()
that's in my existing .js
file like this:
$(".TheClassOnMyUserControlButton").click(function () {
// do stuff here
}
But I couldn't get it to respond to anything I tried. So I put my jQuery
inside a <script>
tag in the UserControl
page itself and the button suddenly started responding.
I have since come to understand that the reason the jQuery
select wasn't working from the .js
file is because the button didn't exist on page load and you can't select a thing that doesn't exist, and that makes sense now.
So my pseudo-newbie developer brain started trying to figure out how I could refresh the document.ready()
in my .js
file once the UserControl
was on the page so that it would become aware of the newly-created UserControl
and its buttons.
I asked another developer that I work with about it and they said to try bind.jquery without explaining how.
Googling that led me here as usual and I saw in the jQuery
documentation that their bind()
method has been deprecated and they suggest using on()
instead.
I think I understand what the other developer meant and I know what I want to do, but I'm getting a little fuzzy on the details and I'm not exactly sure how to use on()
to achieve what I'm trying to do.
I know I could just leave the <script>
tag inside the UserControl
, but I'd like to keep all my JavaScript
and jQuery
in one place if I can.
Does anyone have any suggestions or things I could try?
I appreciate any help anyone can offer.
Thanks