Please upgrade here. These earlier versions are no longer being updated and have security issues.
HackerOne users: Testing against this community violates our program's Terms of Service and will result in your bounty being denied.
JS Question: how to bind a function to an existing html element?
R_J
Admin
Sorry if this is trivial: I try to bind a function to the #Form_CategoryID
select box, but my JS script is loaded in the header and at that time, the select box does not even exist. So my binding never happens.
From what I know, for performance reasons javascript should be loaded last. If I do this, I will not have the problem. But I think it is better to stick to the frameworks rules in order to stay consistent and Garden loads JS in the header.
If I insert a <script>$('#Form_CategoryID').change(function() {do something});</script>
section into the html of the page, everything is working as expected, but I'd prefer to keep my scripts in a separate file and do also the bindings from there.
Could anybody help me out?
0
Comments
You can use
jQuery.on()
to do bind an event listener to elements that will be created in the future. From StackOverflow (sorry for being too lazy to retype the answer):My shop | About Me
To expand BD's answer slightly, if you're using Vanilla 2.0 it depends on an older version of jQuery that predates On(). In that case you can use live() or delegate(), which aren't as efficient but will still get the job done.
That's great! I've used delegate to make it compatible to the current stable version. Thanks to both of you