How to change the URL of an image when the resolution is below 767px

Asked

Viewed 2,114 times

4

I have a website that he’s responsive to.

The problem is that the header has a blue background and a white logo. When the resolution is below 767px it changes the menu.

Imagery:

As it is on the computer:

How is the tablet/ mobile:

How to stay on tablet/ mobile:

What I want is that when the resolution is below 767px it changes to another image.

Ex:

<img src="logo-branca.png" />

When resolution is below 767px:

<img src="logo-azul.png" />

1 answer

7


Using pure Javascript we can check the property window.innerWidth of the global object, which represents the width of the browser window in pixels.

<img id="logo" src="branca" />   

<script>
function updateLogo() {
    var logo = document.getElementById("logo");
    if(window.innerWidth < 767) { // verifica a largura da janela do navegador
        logo.src = "logo-azul.png";
    } else {
        logo.src = "logo-branca.png";
    }
}

updateLogo(); // faz o primeiro ajuste

window.addEventListener("resize", updateLogo); // atualiza o logo ao redimensionar a tela
</script>

It is also possible through CSS Media Queries using a background property for the div where the logo will be contained and changing the background image to the desired resolution:

<style>
#logo {
    background: url('logo-azul.png') no-repeat;
    width: 200px; /* a largura da imagem */
    height: 100px;  /* a altura da imagem */
}
@media (min-width: 767px) {
    #logo {
        background: url('logo-branca.png') no-repeat;
    }
}
</style>

<div id="logo"></div>

Give preference to the CSS solution because the Javascript solution will not work if the browser is disabled with Javascript

Example in Jsfiddle

Click here to view in full screen.

NOTE: Decrease the browser window to view the differences.

  • Hello @Gustavo Carvalho In CSS I already know, I would like to know how it works with JS. Thanks!

  • Have @Alexandrelopes. There was some doubt or difficulty to implement Javascript code on your page?

  • No problem! Thank you! D

Browser other questions tagged

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