March 29, 2011

jQuery script BEFORE HTML elements

Question by Hello_jQuery

Is it possible for jQuery to bind events to elements if the jQuery script block comes before the html tags in the page?

As an example, this does not work:

<script>
    $('a').bind('click', function() {
    alert($(this).attr("innerHTML"));
</script>

<a href="#Hello">Greetings</a>

Yes, I could just put the script after the elements, but hey, maybe I don’t wanna. Just curious if this is the only way.

Answer by Felix Kling

Yes, if you put the code in a ready[docs] event handler (and fix your syntax errors ;)):

$(function() {
    $('a').bind('click', function() {
        alert(this.innerHTML);
        // jQuery way would be: $(this).html()
    });
});

Answer by Starx

Another way is to execute the script during $(window).load() event

$(window).load(function() {
    $('a').bind('click', function() {
    alert($(this).attr("innerHTML"));
});

Now the bind will occur once all the document is fully loaded.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!