0

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?

6
  • There doesn't seem to be anything wrong with the condition though. Commented Aug 13, 2019 at 11:33
  • @Cerbrus that's weird, there is no effect in any width Commented Aug 13, 2019 at 11:34
  • 1
    @santimirandarp depends on when the function gets called Commented Aug 13, 2019 at 11:35
  • it's at the end of the document, right before </body> @KrishnaPrashatt Commented Aug 13, 2019 at 11:36
  • Meaning that it will be executed only once and the working of the condition entirely depends on the window's size at the time of execution. Commented Aug 13, 2019 at 11:40

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

It works for me. Try debugging the code the issue might be in some other code
1

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();
});

`

Comments