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
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!
– Alexandre Lopes
Have @Alexandrelopes. There was some doubt or difficulty to implement Javascript code on your page?
– Gustavo Carvalho
No problem! Thank you! D
– Alexandre Lopes