How To Remove a Function Depending on Screen Width? [jQuery]

How To Remove a Function Depending on Screen Width? [jQuery]
0

#1

I’m currently working on my tribute page and I’ve added a bit of JQuery to it to make it so some images appear after you’ve scrolled to a specific amount of space above it. Due to these images appearing early on in the page, when opening the site on a mobile/smaller screen, the area where the images should show up appear empty until the user scrolls, which then makes them appear and messes with the users originally perceived layout. [Even though it looks how it should after the images pop up, the site doesn’t look that way before the user scrolls.]

I’m currently attempting to make it so the page doesn’t add any animation or disappearance of the images when being opened on a smaller screen. I am capable of making them appear once the page loads, but once the user scrolls, the animation is added regardless.

Is there any way I can cancel out the function I’ve created in JQuery only on a specific page width?

Here’s the current code I have for it:

JQuery

$(document).ready(function() {

var div = $(’#show-hide1’);
var pos = div.position();

$(window).scroll(function() {
var windowpos = $(window).scrollTop();
if (windowpos >= (pos.top - 600)) {
div.addClass(“AfterScroll animated fadeInLeft”);
}
});

$(window).load(function() {
var viewportWidth = $(window).width();
if (viewportWidth < 545) {
div.removeClass(“BeforeScroll animated fadeInLeft”);
}
});
});

CSS [The two classes I made that are used in the above code]

.BeforeScroll {
  display: none;
}

.AfterScroll {
display: block;
}

Thanks in advance!

#2

Hey!

Could you not just use a css media query for this? Seems like the Jquery is a bit overkill.


#3

@SyntaxErrorless, as @theador0691 mentioned, CSS media queries can be used to check the screen width.

This article which I thought might be helpful - https://paulund.co.uk/checking-media-queries-javascript.
It seems to describe how to check screen width in jquery.

I tried it in the example below.

My code is not perfect. But I hope it helps.

Thanks,
Pradnya.