Danconia
Danconia

Reputation: 563

Using jQuery to change the background image

I am trying to change the background image of a link when it get clicked. I keep getting the error that you cannot call 'click' on null.

JQuery (in the header)

<script type="text/javascript">
    $('a.upvote-arrow').click(function(){
        $('#tempid1').css('background-image','url(../images/icons/up-arrow2.png)');
    });
</script>

HTML

<div class="top-comment-vote">
    <a href="#" class="upvote-arrow" title="Up vote" id="tempid1"></a>
</div>

Thanks

Upvotes: 0

Views: 139

Answers (3)

Alex Grande
Alex Grande

Reputation: 8027

Are you sure this script is being loaded after the html is in the DOM?

Try wrapping what you wrote in a onload closure.

$(function() {
 $('a.upvote-arrow').click(function(){
   $('#tempid1').css('background-image','url(../images/icons/up-arrow2.png)');
 });
});

Another thing you can do is take advantage of delegation for the event registration.

$('body').on("click", ".a.upvote-arrow", function(){
 $('#tempid1').css('background-image','url(../images/icons/up-arrow2.png)');
});

This binds it to the body instead.

Upvotes: 1

zallarak
zallarak

Reputation: 5525

Try wrapping your script with document.ready; I suspect that you're script might be running before your entire page loads.

Upvotes: 0

mgraph
mgraph

Reputation: 15338

Try adding $(document).ready:

<script type="text/javascript">
$(document).ready(function(){
    $('a.upvote-arrow').click(function(){
        $(this).css('background-image','url(../images/icons/up-arrow2.png)');
    });
})
</script>

Upvotes: 1

Related Questions