I only want to run a script when the viewport width is greater than a set value. I would also like this to check as the browser resizes and disable/enable as required. I've tried to achieve this using matchMedia
and rather than checking every pixel, the script only triggers when the viewport is less/greater than a set value.
If I load a narrow viewport (less than 1080px) the JS doesn't trigger - perfect! Enlarging the viewport to have a width greater than 1080px then runs the script - also perfect!
The problem I have is when I scale down from a larger viewport (greater than 1080px) to narrow/small. The script still functions until I refresh the page - I'm hoping someone can help me with that.
As an aside, is it possible to change const mediaQuery = window.matchMedia('(min-width: 1080px)')
to include a min-height or a more complex media query if required (not essential for this).
My script:
const mediaQuery = window.matchMedia('(min-width: 1080px)')
function viewportChange(e) {
// Check if the media query is true
if (e.matches) {
$(document).ready(function() {
var num_children = $('.split-loop__left').children().length;
var child_height = $('.split-loop__right').height() / num_children;
var half_way = num_children * child_height / 2;
$(window).scrollTop(half_way);
function crisscross() {
var parent = $(".split-loop");//.first();
var clone = $(parent).clone();
var leftSide = $(clone).find('.split-loop__left');
var rightSide = $(clone).find('.split-loop__right');
if (window.scrollY > half_way ) {
//We are scrolling up
$(window).scrollTop(half_way - child_height);
var firstLeft = $(leftSide).children().first();
var lastRight = $(rightSide).children().last();
lastRight.appendTo(leftSide);
firstLeft.prependTo(rightSide);
} else if (window.scrollY < half_way - child_height) {
var lastLeft = $(leftSide).children().last();
var firstRight = $(rightSide).children().first();
$(window).scrollTop(half_way);
lastLeft.appendTo(rightSide);
firstRight.prependTo(leftSide);
}
$(leftSide).css('bottom', '-' + window.scrollY + 'px');
$(rightSide).css('bottom', '-' + window.scrollY + 'px');
$(parent).replaceWith(clone);
}
$(window).scroll(crisscross);
});
}
}
// Register event listener
mediaQuery.addListener(viewportChange)
// Initial check
viewportChange(mediaQuery)