Reputation: 21
I'm using this JS and CSS to add a zoom effect to header image. It's perfectly working on desktop.
Problem is on mobile hero image is not "filling" the entire container.
So I would need to have 2 different JS with 2 different % settings to make it work both on desktop and mobile.
Is there a solution to make one script with my 2 differents needs you'll find below based on screen size ? "this function is for desktop, and this function is for mobile" ?
For the one who knows I'm using GeneratePress's Elements feature to display hero header entire site.
Here is the JS + CSS working for desktop :
JS
<script>
var pagehero = document.querySelector('.page-hero');
function hero_animation(){
pagehero.style.backgroundSize = 100+'%';
pagehero.style.opacity = '1';
}
document.onload = hero_animation();
</script>
CSS
.page-hero {
transition: background-size 1s cubic-bezier(0.1, 0.135, 0.15, 0.86), opacity 1s ease-out 0.1s !important;
opacity: 0; background-size: 150% auto;
}
Here is the JS + CSS that I would need to add for mobile :
JS
<script>
var pagehero = document.querySelector('.page-hero');
function hero_animation(){
pagehero.style.backgroundSize = 200+'%';
pagehero.style.opacity = '1';
}
document.onload = hero_animation();
</script>
CSS
.page-hero {
transition: background-size 1s cubic-bezier(0.1, 0.135, 0.15, 0.86), opacity 1s ease-out 0.1s !important;
opacity: 0; background-size: 300% auto;
}
Thanks for your help !
Upvotes: 0
Views: 313
Reputation: 626
You're calling the function when the document html/body
is loaded.
<script>
var pagehero = document.querySelector('.page-hero');
function hero_animation(){
pagehero.style.backgroundSize = 100+'%';
pagehero.style.opacity = '1';
}
document.onload = hero_animation();
</script>
Change it to this:
<script>
var pagehero = document.querySelector('.page-hero');
function hero_animation(){
pagehero.style.backgroundSize = 100+'%';
pagehero.style.opacity = '1';
}
document.onload = hero_animation;
</script>
Or this:
<script>
var pagehero = document.querySelector('.page-hero');
function hero_animation(){
pagehero.style.backgroundSize = 100+'%';
pagehero.style.opacity = '1';
}
document.onload = function() { hero_animation() };
</script>
Second, you should change 100/200
to a string. JavaScript is case-sensitive:
pagehero.style.backgroundSize = '100' + '%';
Or
pagehero.style.backgroundSize = (Number(100).toString()) + '%';
Upvotes: 0