0

I need to change the source of image if its width is less than 600px. I created following script but it is not working.

var sizewidth = window.innerWidth;
screensize();

function screensize() {
  if (sizewidth < 601) {
    document.getElementById('logotipo').src = "../imgs/image.png";
  }
}

What is wrong in it? Can someone help me correct it?

3
  • Can use media queries. Commented Dec 26, 2017 at 11:51
  • Yes, but i want use javascript to learn about this language Commented Dec 26, 2017 at 11:54
  • what's the error coming? Commented Dec 26, 2017 at 11:56

3 Answers 3

1

I copied your code and I think its working fine. Maybe issue is the placement of your script file/code. Just check below

var sizewidth = window.innerWidth;
screensize();

function screensize() {
  if (sizewidth < 601) {
    document.getElementById('logotipo').src = "../imgs/image.png";
  }
}
<img id="logotipo" src="logo.png">

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I think that the problem is in the location of script in my html.
@d3pod replace the function call screensize(); for window.onload=screensize; this will ensure the DOM has loaded.
1
    var sizewidth = window.innerWidth;
    screensize();
    function screensize() {
        if (sizewidth < 601) {
            document.getElementById('logotipo').setAttribute("src", "../imgs/image.png");
        }
    }

1 Comment

If you're using the OP's code, please indicate where you made the change. Otherwise the reader has to unnecessarily compare each line. Better yet, just paste the one line you made the change on and include a short explanation.
0

Are you sure the path of your image is correct??(you can try looking for console logs on your web browser) If yes then,try putting double \ in your code instead of \

1 Comment

What? "try putting double \ in your code instead of \" the OP doesn't have any backslashes in the source code? I think your approach to solving this is far from the actual issue. The source code functions just find if placed in the correct location on the page or placed within a window load function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.