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?

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?

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):

    $('#container').on('click', '.innerElement', function(){
       /// Do stuff
    });
    

    In your case, #container would be an element that is known to exist on page load which will contain the child elements you care about (either now or in the future). This approach takes advantage of event bubbling in the DOM.

  • 50sQuiff50sQuiff ✭✭
    edited July 2013

    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.

  • R_JR_J Admin

    That's great! I've used delegate to make it compatible to the current stable version. Thanks to both of you

Sign In or Register to comment.