How to only trigger a function when window width is less than a certain amount?

Viewed 56

I have created a simple accordion for some footer content that I only want to trigger when the window width is less than 600px. I've tried using window.resize but when resizing the window above 600px the function is still initialising and I can't understand why.

If anyone would mind sharing some advice on this I'd really appreciate it. I keep going round in circles.

jsFiddle

JS:

function initializeAccordion() {
  var mainToggle = $('.footer-accordion > .footer-column > p');
  $('.footer-accordion > .footer-column > .menu').css('display', 'none');

  mainToggle.click(function() {
    var that = $(this);
    var secondLevel = $(this).siblings('.menu');
    var allSeconds = $('.footer-accordion > .footer-column > .menu');

    if (that.hasClass('is-active')) {
      secondLevel.slideUp();
      that.removeClass('is-active');
      mainToggle.removeClass('is-active');
      allSeconds.removeClass('is-active');
      allSeconds.slideUp();
    } else {
      mainToggle.removeClass('is-active');
      allSeconds.removeClass('is-active');
      allSeconds.slideUp();
      secondLevel.slideDown();
      that.addClass('is-active');
      secondLevel.addClass('is-active');
    }
  });
};

if ($(window).width() < 600) {
  initializeAccordion();
}

$(window).on('resize', function() {
  if ($(window).width() < 600) {
    initializeAccordion();
  }
});
1 Answers

A pure JS cross-browser solution:

window.onresize = function() {
  checkWidth();
}
checkWidth();

function checkWidth() {
  var vw = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0)
  if (vw < 600) {
    //callFunction();
  }
}

Related