Help a noob with some ugly jquery

So here I have some jquery that could probs be done prettier (feel free to optimize this code if you like=) ).
The problem is that the things inside the if (min-width: 768 ) {} is still triggered if I resize the browser window to less then this. the else {} is only triggered if I reload the page.

I guess I want it to trigger on(‘resize load’) and I tried wrapping everything in $(window).on(‘resize load’, function(){}); but that messed it up even more.

So how could I do this?

  if (window.matchMedia('(min-width: 768px)').matches) {

    $(window).scroll(function() {
        var window_top = $(window).scrollTop();
        var div_top = $('.filter-anchor').offset().top + 300;
        if (window_top > div_top) {
            $('#filter').addClass('stick-filter');
            $('.filter-filler').show();
        } else {
            $('#filter').removeClass('stick-filter');
            $('.filter-filler').hide();
            $('.filter-car').show();
        }
    });

    $("#tofilter").click(function(e) {
      e.preventDefault();
      if($(window).scrollTop() < $('.filter-anchor').offset().top + 300){
        $('html, body').animate({
          scrollTop: $("#filter").offset().top - 80
        }, 1000);
      } else if ($('.filter-car').is(':visible')){
          $('.filter-car').velocity("slideUp", function() { duration: 100 });
      } else {
          $('.filter-car').velocity("slideDown", function() { duration: 100 });
      }
    });

  } else {

    $('#filter').addClass('stick-filter');
    $('.filter-filler').hide();
    $("#tofilter").click(function(e) {
      e.preventDefault();
      if ($('.filter-car').is(':visible')){
          $('.filter-car').velocity("slideUp", function() { duration: 100 });
      } else {
          $('.filter-car').velocity("slideDown", function() { duration: 100 });
      }
    });

  }

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.