Reputation: 11
I want to change my img src with jQuery click function but can't seem to do it. Here is my html code:
<div id="main2"><img id='mty' style="width: 500px;height: 600px;"
src="https://cdn.pastemagazine.com/www/articles/morty%20main.jpg">
</div>
Here is my jQuery code that won't work:
<script type="text/javascript">
$('#paper').click(function()
{
$('#mty').attr('src', 'http://www.cliparthut.com/clip-arts/1008/paper-stack-clip-art-1008442.jpg');
}); </script>
what am I doing wrong? I want to be able to change the html src if I click on #paper which is a button btw.
Upvotes: 0
Views: 138
Reputation: 1
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<link rel="stylesheet" href="style.css" />
<script data-require="jquery" data-semver="3.1.1" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<img id="image" src="http://lorempixel.com/400/200" alt="random image"/>
<button id="changeImage">Change image</button>
<script>
$('#changeImage').on('click', function(){
$('#image').attr('src', 'http://lorempixel.com/400/200');
});
</script>
</body>
</html>
Upvotes: 0
Reputation: 1578
Html is as-
<button type="button" id="paper">change image</button>
<div id="main2">
<img id='mty' style="width: 500px;height: 600px;"
src="https://cdn.pastemagazine.com/www/articles/morty%20main.jpg">
</div>
Script-
<script type="text/javascript">
$('#paper').click(function () {
$('#mty').attr('src', 'http://www.cliparthut.com/clip-arts/1008/paper-stack-clip-art-1008442.jpg');
});
</script>
Things to remember-
User script after html render or use jquery ready.
Upvotes: 0
Reputation: 1540
$('#mty').attr('src', 'http://www.cliparthut.com/clip-arts/1008/paper-stack-clip-art-1008442.jpg');
You need to set "src" to img tag, not the div tag
<script type="text/javascript">
$(document).ready(function(){
$('#paper').click(function() {
$('#mty').attr('src', 'http://www.cliparthut.com/clip-arts/1008/paper-stack-clip-art-1008442.jpg');
});
});
</script>
Upvotes: 2