Reputation:
New to js and trying to apply some lines of code only when the window is larger than 768 pixels.
I've come up with this:
if ($(window).width() > 768) {
const central = document.querySelector('.central');
const tl = new TimelineMax();
tl.fromTo(central,1,{height:'0vh'},{height:'80vh'})
.fromTo(central,1,{width:'100vw'},{width:'80vw'});
}
Loading in the HTML file this two lines:
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/2.1.3/TimelineMax.min.js"
integrity="sha256-fIkQKQryItPqpaWZbtwG25Jp2p5ujqo/NwJrfqAB+Qk=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/2.1.3/TweenMax.min.js"
integrity="sha256-lPE3wjN2a7ABWHbGz7+MKBJaykyzqCbU96BJWjio86U=" crossorigin="anonymous"></script>
<script src='js.js'></script>
Without the if condition it runs fine, so the condition is wrongly applied, can you help me to fix it?
Upvotes: 0
Views: 351
Reputation: 49
You have to listen to the window resize method. Using vanilla Js you can wrap the main function like so: `
function responsiveFeature(){
if (window.innerWidth < 768) {
const central = document.querySelector('.central');
const tl = new TimelineMax();
tl.fromTo(central,1,{height:'0vh'},{height:'80vh'})
.fromTo(central,1,{width:'100vw'},{width:'80vw'});
}
}
`
then run the code on page loaded : `
document.addEventListener('DOMContentLoaded', (event) => {
responsiveFeature();
});
and trigger the resize event :
window.addEventListener('resize',(event) => {
responsiveFeature();
});
`
Upvotes: 1
Reputation: 643
Combine it with a resize event
$(window).resize(function() {
if ($(window).width() > 768) {
const central = document.querySelector('.central');
const tl = new TimelineMax();
tl.fromTo(central,1,{height:'0vh'},{height:'80vh'})
.fromTo(central,1,{width:'100vw'},{width:'80vw'});
}
}).resize();
Added .resize() which will call the window.resize event on load.
Upvotes: 1