Damiano Barbati
Damiano Barbati

Reputation: 3496

Can't change src in image with jquery

I can't change the image with jquery: whats going on??

<!DOCTYPE HTML>
<HTML>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>

<script text="text/javascript">
$('#caccia').attr('src', '2.png');
</script>

<img id="caccia" src="1.jpg" />

</HTML>

Upvotes: 0

Views: 2384

Answers (4)

Calvein
Calvein

Reputation: 2121

It's because you have not tell your script to wait until the DOM is ready, just write that instead.

$(function() {
    $('#caccia').attr('src', '2.png');
});

Which is the same as (it can be easier to understand this way).

$(document).ready(function() {
    $('#caccia').attr('src', '2.png');
});

Plus, it's better to have you JavaScript before thz </body> http://developer.yahoo.com/performance/rules.html#js_bottom

Upvotes: 5

insomiac
insomiac

Reputation: 5664

If you want to just change the image, as soon as the page loads:

You can do something like this in jquery :

$(document).ready(function(){
    $('#caccia').attr('src','2.jpg');
});

Demo : http://jsfiddle.net/QJKWK/1/

Upvotes: 1

ghkaren
ghkaren

Reputation: 601

try this code

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>

    <script text="text/javascript">
        $(document).ready(function() {
            $('#caccia').attr('src', '2.png');
        });
    </script>
    </head>
    <body>
    <img id="caccia" src="1.jpg" />
</body>

Upvotes: 0

Tim B James
Tim B James

Reputation: 20364

You need to put your code within

$(function(){
    // your code here
});

That way, the script will execute only when all the elements of your DOM have been rendered.

Upvotes: 2

Related Questions