jQuery event not firing (advanced)
<p>For a dynamic added element via ajax or any after page load, I know that we have to use the <code>.on</code> like</p>

<pre><code>$(document).on('click', '#dynamically-added-element', function() {
    // do something
    console.log('Hello World!');
});
</code></pre>

<p>I even wrapped mine with <code>(function($){})(jQuery);</code> to make sure no conflict; and to make sure everything should be run/loaded in proper order, I also have <code>$(document).ready(function(){});</code>.</p>

<p>Now that event was originally meant to run on <code>Page A</code> and it works well, but when I made and try it run on <code>Page B</code> having the same <code>id</code> for the main container and have the same child html, it doesn't work.</p>

<p>So I've done some experiment/tests and both works.</p>

<p>(1) So what I've done, I wrote exact same event listener through my browser's console with just <code>console.log</code> and click the target element, it works!</p>

<p>(2) On the same <code>.js</code> script, I've added exact same event listener with just <code>console.log</code> but wrapped it inside <code>setTimeout(function(){}, 5000);</code>, after 5 seconds, I clicked the target element and it worked!</p>

<p>So my question now is, why my original code doesn't work? Why these tests works? So what's the solution?</p>

<p>Also, my html elements aren't loaded dynamically, it's loaded on page load, generated via server side <code>PHP</code>.</p>

<p><strong>Edit:</strong>
This info might be useful.</p>

<ul>
<li>running in magento</li>
<li>js script is being included on <code>head</code> (that's why <code>$(document).ready</code> is really important).</li>
<li>jquery script is being loaded before my custom script.</li>
<li>Page A and Page B are on different pages.</li>
<li><strong>It's not an ajax generated element nor js/jquery added element on the fly; it's generated on postback with <code>php</code> code</strong></li>
</ul>

<p>(3) My third experiment works as well. But I don't want this to be my solution if possible, nor using javascript inline <code>onclick</code>. So what I did, I added a whole new script block inside the <code>php</code> file where that 'part' of the page is being included, with exact same code and it works. But the thing is, I have now two identical event listener.</p>

<p>So now I have 2 identical event listener (regardless if the other one doesn't work - only for Page B), 1 from within (internal) and 1 from external <code>.js</code> file.</p>

<pre><code>&lt;script type="text/javascript"&gt;
(function($) {
    $(document).ready(function() {
        $(document).on('click', '#the-container a', function(e) {
            e.preventDefault();
            var target = $(this).attr('href');
        });
    });
})(jQuery);
&lt;/script&gt;
</code></pre>