0

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.

1
  • 2
    P.s. Does .attr("innerHTML") work for you? Commented Mar 29, 2011 at 7:45

4 Answers 4

5

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()
    });
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Also, I tested your example and see that "this.AttrName" works and is much cleaner than my version, but every example I've seen on the net (including snippets on the jQuery site) uses the "$(this).attr("AttrName")" syntax. Are there any technical reasons (beyond readability) why the syntax in your example is preferred?
@Hello_jQuery: If you already have a jQuery object, then using attr is easier. But if you can be sure that a HTML attribute exists in every browser (e.g. href for a link) then there is no need to wrap it as jQuery object first. You normally don't use it for properties of DOM objects, which innerHTML is. The jQuery way to access this would be $(this).html(). There is a difference between HTML attributes and properties of DOM objects.
1

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.

Comments

1

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.