1

I try to disable some JS (backstrech) when user reach a specific width.

I use something like :

if (window.innerWidth >= 768) {
/* the function
}

And it works.

But I have an issue because it only work when an user open the website in this particular size.

If he resizes the website this is not working...

I try to use $(window).resize.

But I don't find how to use it and tell the function to work when resize this specific size.

Anyone have a idea ?

Erazihel
  • 7,295
  • 6
  • 30
  • 53
Knaps
  • 21
  • 5

3 Answers3

0

This question: How to trigger the window resize event in JavaScript?

Answers a similar question, here is a snippet from that answer's fiddle that solves your problem by registering an event that is triggered on window resize:

window.onresize = doALoadOfStuff;

function doALoadOfStuff(x) {
    alert('Go' + x);
}

var handler = window.onresize;
//handler();
//or
handler.apply(window, [' On']);

All you need to do is check the size of the window inside the handler with a simple if inside the doALoadOfStuff method:

function doALoadOfStuff(){
   var windowSize = window.innerWidth
      || document.documentElement.clientWidth
      || document.body.clientWidth;

   if(windowSize > 768) {
      //DoSomething
   }
}

Working fiddle to demo code, if you drag the centre screen partition to the left you'll start getting console messages telling you that it is functioning as expected. It kicks off immediately as the page loads.

Community
  • 1
  • 1
Cookie
  • 558
  • 8
  • 24
  • Thanks, but have exactly the same issue and one more (the js are not working until the user resize the windows). – Knaps Mar 21 '17 at 16:42
  • I've edited the code, I'll add a fiddle in a minute. – Cookie Mar 21 '17 at 16:44
  • To be more clear when the user open the site i would like to have this js but if he resize under 768px or open it on mobile i don't want it anymore – Knaps Mar 21 '17 at 16:45
  • Read the edits, it now functions as you'd like, it executes on first load as well. – Cookie Mar 21 '17 at 16:52
  • Yes with the edit works better than my previous code but still have the same issues when the user resize the site under 768 the js is still there. He need to reload to hide the js. When he came from a small screen and resize to > 768 works fine now. thanks for all – Knaps Mar 21 '17 at 17:03
  • Will try some stuff if you have an idea for the last issue ;) – Knaps Mar 21 '17 at 17:23
0

So i find an 100% working solution... Maybe could help an user of backstrech one day. Was so easy but try to complicated my life. Just need a simple css line :

@media (max-width: 768px) {
  .backstrech{
  display: none;
  }
}

Thanks for all your help will help me for another stuff.

Knaps
  • 21
  • 5
0

This worked for me...

if (window.innerWidth <= 500 ) {
    function showSlides(display)    
} else {
    display(none)
}