-
-
Save chriswitko/036d1227ed293dc77e717dee35312f34 to your computer and use it in GitHub Desktop.
Pure JS/CSS image zoom on click
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
picture { | |
cursor: zoom-in; | |
height: 0; | |
max-height: 1250px; | |
max-width: 1400px; | |
padding-top: 50%; | |
position: relative; | |
width: 100%; | |
&::before { | |
content: ''; | |
display: block; | |
height: 100%; | |
left: 0; | |
pointer-events: none; | |
position: absolute; | |
top: 0; | |
width: 100%; | |
z-index: 2; | |
} | |
img { | |
height: auto; | |
left: 0; | |
position: absolute; | |
top: 0; | |
width: 100%; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Confere se o DOM Carregou | |
function ready(fn) { | |
if (document.readyState != 'loading') { | |
fn(); | |
} else { | |
document.addEventListener('DOMContentLoaded', fn); | |
} | |
} | |
//Adiciona classe 'zoomed' a imagem | |
function imageClick(e) { | |
e.preventDefault(); | |
this.classList.toggle('zoomed'); | |
} | |
//Faz a tecla ESC sair do zoom | |
function handleEsc(e) { | |
if (e.keyCode == 27) { | |
var zoomedImages = document.querySelectorAll('img.zoomed'); | |
Array.prototype.forEach.call(zoomedImages, function(el, i) { | |
el.classList.toggle('zoomed'); | |
}); | |
} | |
} | |
//Executa a função | |
ready(function() { | |
var images = document.querySelectorAll('article img'); | |
Array.prototype.forEach.call(images, function(el, i) { | |
el.addEventListener('click', imageClick); | |
}); | |
document.addEventListener('keyup', handleEsc); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment