How to switch images using JS?

Tags: , , ,



I have a simple code that switches text when an image is clicked:
js:

$(document).ready(function() {
   $('.srb').on('click', function() {
      var r = $('.localization').each(function() {
         var el = $(this);
         var key = (el.attr('caption'));
         el.text(srb[key]);
      });
   });
   $('.eng').on('click', function() {
      var r = $('.localization').each(function() {
         var el = $(this);
         var key = (el.attr('caption'));
         el.text(eng[key]);
      });
   });
   var srb = {
      welcome: 'Добро дошли на наш сајт!'
   };
   var eng = {
      welcome: 'Welcome to our site!'
   };
});

HTML:

<span class='localization' caption='welcome'>Welcome to our site!</span>
<img src="img/Serbia.png" value='srb' class="srb" id="flag"/>
<img src="img/United-Kingdom.png" class='eng' value='eng'/>

Is it possible to switch images when language is switched (for example, when English language is set, GB flag disappears)?

Answer

Edit html like that

<img src="img/Serbia.png" value='srb' class="image_flag srb" id="flag"/>
<img src="img/United-Kingdom.png" class="image_flag eng" value="eng"/>

add class hidden element

.d-none{
    display: none !important;
}
<script>
function activeImageFlag(flagActive){
    document.querySelectorAll(".image_flag").forEach(function(flagImage){
        flagImage.classList.add('d-none')
    });
    document.querySelector(".image_flag." + flagActive).classList.remove('d-none')
}
</script>


Source: stackoverflow