-2

This is my code:

In JSFile.js:

alert('hello');

$('#mydiv').change(function(){
   alert("i'm here");
})

In a script in html file:

<asset:javascript src="JSFile.js"/>
<script>
    $(document).ready(function(){
        $('#mydiv').trigger('change');
    });
</script>

The JS file gets imported correctly cause i see the 'hello' alert when i load the html file, but the 'i'm here' alert never pops up. If i copy the code from the js file and paste it below the document ready, the alert pops up.

Does anybody know how to make it work the way I want? Thanks.

Barmar
  • 741,623
  • 53
  • 500
  • 612
diebarral
  • 61
  • 12
  • 2
    Sounds like you are binding event *before* element is available in DOM, resulting in `$('#mydiv')` returning empty matched set – A. Wolff Oct 23 '15 at 15:03
  • 2
    [can't reproduce](http://jsbin.com/xokado/1/edit?html,js,console) – Quentin Oct 23 '15 at 15:04
  • 1
    @Quentin Binding event is done from external file, i guess included from head – A. Wolff Oct 23 '15 at 15:05
  • 1
    @A.Wolff — Probably, but the OP should create a test case to demonstrate the problem and not leave us guessing how to fill in the gaps in the supplied code. – Quentin Oct 23 '15 at 15:07
  • 1
    @Quentin Oh ya, sorry, i get your point! – A. Wolff Oct 23 '15 at 15:07
  • The Javascript file is included in head, yes. – diebarral Oct 23 '15 at 15:10
  • In that case, [this question applies](http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) (but I've already voted so can't mark as dupe) – James Thorpe Oct 23 '15 at 15:10
  • Well, the element i'm targeting it's actually in a partial view that is rendered inside the html file where the document ready is. Maybe that's the reason @JamesThorpe. Thanks for the link to the other question. – diebarral Oct 23 '15 at 15:15

1 Answers1

-3

I cant recreate but have you tried:

$('#mydiv').change(function(){
   alert("i'm here");
}).change();

Define the change event, and trigger it immediately. This ensures the event handler is defined before calling it.

Darren Willows
  • 2,053
  • 14
  • 21