How to exchange an image inside a div for javascript

Asked

Viewed 188 times

-1

I need to change the image inside the div if the width of the screen is less than or equal to 991. I’ve done the code below, but it’s not working, I need to know where I’m going wrong and how to fix it.

html

<div class="dImg">
   <img class="dImg2" src="assets/img/path.svg">
</div>

javascript

$(window).load(function teste() {
    var tamanho = window.innerWidth;
    if (tamanho <= 991) {
        $(".dImg2").remove();
        $(".dImg").append("<img src="
            assets / img / path991.svg ">");
    };
});

Also test with this js

$(window).load(function teste() {
    var tamanho = window.innerWidth;

    if (tamanho <= 991) {
        $('.dImg2')
             .attr("src")
             .replace("assets/img/path.svg","assets/img/path991.svg");
    };
});

2 answers

0

I have no knowledge in Jquery but strongly believe that you are not changing any value, at least not in the second code. That’s because the method attr returns the attribute value and the replace returns a string. Therefore, you are not setting anything to the element.

Using pure JS only, try changing the property src image as in the code below:

function changeImage() {
    document.getElementById("myimg").src = "https://ispeakcode.com/blog/wp-content/uploads/2018/07/stackoverflow-1.png";
}
<img id="myimg" src="https://cdn.sstatic.net/Sites/br/Img/apple-touch-icon.png?v=e57f45c9cfaf"/><br>
<button onclick="changeImage();">Troca Imagem</button>

0

Less than or equal to 991

function teste() {
    var tamanho = window.innerWidth;

   if (tamanho <= 991) {
       document.getElementById("myimg").src = "https://i.stack.imgur.com/hvQfa.png";
    };
}

// Chamada da função
teste();
  <div class="dImg">
     <img id="myimg" src="https://i.stack.imgur.com/akFTE.png"/><br>
  </div>
  

Greater than 991

function teste() {
    var tamanho = window.innerWidth;

   if (tamanho > 991) {
       document.getElementById("myimg").src = "https://i.stack.imgur.com/hvQfa.png";
    };
}

// Chamada da função
teste();
  <div class="dImg">
     <img id="myimg" src="https://i.stack.imgur.com/akFTE.png"/><br>
  </div>
  

Browser other questions tagged

You are not signed in. Login or sign up in order to post.