0

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

3 Answers 3

1

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

2 Comments

Thanks for the quick answer. I did that I now I got an 'Uncaught SyntaxError: Unexpected end of input'
thanks, got it to work, the problem was that the '$' was conflicted, so I had to do var $j = jQuery.noConflict();. Thanks, it now works!
1

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.

Comments

0

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

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.