Search code examples
javascriptphphtmlsrcalt

Working with src and alt to replace an image


I have a part in my site that dedicated to changing the language. Right now, in a circle button, i have united-kingdom flag. This is the default option.

  <a class="nav-link-language  js-language-trigger">
    <img src="http://my-site.test/wp-content/uploads/2018/04/260-united-kingdom.png" alt="">

For example i have an option for German Language

    <div class="nav-link-language-holder">
      <a><img src="http://my-site.test/wp-content/uploads/2018/04/260-germany.png" alt=""><i>German</i></a>
    </div>

How can i set with javscript, when user click on the icon for Germany, it will be replaced for the default option (right now is united-kingdom)

Thanks a lot


Solution

  • Here's a quick way to change your img src :

    <img id="Your_IMG_ID" src="olg-img-src.png">
    <button onclick="change_img_src()">Change SRC</button>
    <script>
    function change_img_src() {
        document.getElementById("Your_IMG_ID").src = "new-img-src.png";
    }
    </script>
    

    To generalize what you're looking for and further simplify it, here's a way to do it :

    <!--- Your main flag --->
    <img id="main-flag" style="cursor:pointer" src="img.png"/>
    
    <!--- Rest of flags --->
    <img style="cursor:pointer" onclick="Change_flag(this.src)" src="img.png"/>
    <img style="cursor:pointer" onclick="Change_flag(this.src)" src="img-2.png"/>
    <img style="cursor:pointer" onclick="Change_flag(this.src)" src="img-3.png"/>
    <!----Other flags---->
    <script>
    function Change_flag(_src) {
        document.getElementById("main-flag").src = _src;
    }
    </script>