I created a script that changes an image when you click a button. The problem is with clicking again, because the src attribute remains the same. I would like after clicking again the source of the photo to go back to the initial src. I tried to do it using toggle method, but with positive effect.
My code:
$(document).ready(function(){
$('#button').click(function(){
$('.logo').attr('src', 'http://domena.com/logo-1.jpg');
});
});
I tried to solve it that way, but I failed.
$(document).ready(function(){
$('#button').click(function(){
$('.logo').toggle(
function() {
$(this).attr('src', 'http://domena.com/logo-1.jpg');
},
function(){
$(this).attr('src', 'http://domena.com/logo-2.jpg');
}
);
});
});
You can pass the URL
of new image
in an attribute of <img>
, then you can get the current image
ie src
and next image( data-new
) and interchange their values, like so -
$(document).ready(function(){ $('#button').click(function(){ let curr_img = $('.logo').attr('src'); // get current image let new_img = $('.logo').attr('data-new'); // get new image to be shown $('.logo').attr({'src': new_img, 'data-new': curr_img}); // interchange their values }); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <:-- give next values as an attribute ie data-new here--> <img src="https.//w7.pngwing.com/pngs/247/564/png-transparent-computer-icons-user-profile-user-avatar-blue-heroes-electric-blue:png" class="logo" data-new="https.//image.flaticon.com/icons/svg/21/21104:svg" style="width; 150px: height; 150px;"> <br> <button id="button">Toggle image</button>
Hope it helps you.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.