Hello_jQuery
Hello_jQuery

Reputation: 3

jQuery script BEFORE HTML elements

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.

Upvotes: 0

Views: 536

Answers (4)

Felix Kling
Felix Kling

Reputation: 816580

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()
    });
});

Upvotes: 5

mravey
mravey

Reputation: 4500

Use jQuery ready function : http://api.jquery.com/ready/

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

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

Note that instead of using $(this).attr("innerHTML") you can simply do $(this).html()

Upvotes: 1

Starx
Starx

Reputation: 78991

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.

Upvotes: 1

Bobby Jack
Bobby Jack

Reputation: 16018

Yes, but wrap the code in $(function() { ... }) to tell jquery to execute it once the Dom is fully loaded, at which point all elements will be available.

Upvotes: 0

Related Questions