Skip to content
Advertisement

How to switch images using JS?

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)?

Advertisement

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>
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement