Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

205
Visualizações
How do I create a vertical scroll mousewheel function?

I've created this script:

jQuery(".resultlist").mousewheel(function(event, delta) {
  this.scrollLeft -= (delta);
  event.preventDefault();
});

which fires a horizontal scroll function over the .resultlist container and this is working as expected. I need to disable this on screen widths underneath 545px so I've wrapped it in a resize function.

/* Trigger Resize Script */
jQuery(document).ready(function(){
    function resizeForm(){
        var width = (window.innerWidth > 0) ? window.innerWidth : document.documentElement.clientWidth;
        if(width > 545){
            jQuery(".resultlist").mousewheel(function(event, delta) {
              this.scrollLeft -= (delta);
              event.preventDefault();
            });
        } else {
            // invert
        }    
    }
    window.onresize = resizeForm;
    resizeForm();
});
/* End Trigger Resize Script */

The problem I have is that the script still runs if else is true, I did start working on a function that would include and then delete a separate script based on screenwidth but this became very cumbersome and is surely not the right way to achieve this.

I need to convert the mousewheel function so that it behaves like a normal vertical scroll instead, so that I can switch between my current horizontal scroll and a normal vertical scroll inside the resize function.

How do I amend the below function to scroll vertically?

jQuery(".resultlist").mousewheel(function(event, delta) {
   this.scrollLeft -= (delta);
   event.preventDefault();
});
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

There's a lot of going on in your code. One of the misconcepts is, that it creates a ton of mousewheel listeners on the elements when resizing the window. Here's how you can achieve what you need:

'use strict';

// Allows an event handler to run only when the event has stopped to fire
function debounce(callback, delay = 200) {
  let timeout;
  return function() {
    const context = this,
      args = arguments;
    window.clearTimeout(timeout);
    timeout = window.setTimeout(function() {
      callback.apply(context, args);
    }, delay);
  };
}

jQuery(document).ready(function() {
  let width, dirProp;

  function resizeForm() {
    width = jQuery(window).width();
    dirProp = (width > 545) ? 'scrollLeft' : 'scrollTop';
  }

  function scroll(event) {
    event.preventDefault();
    // Use the original event object to access WheelEvent properties
    this[dirProp] += (event.originalEvent.deltaY);
  }

  jQuery(".resultlist").on('wheel', scroll);
  jQuery(window).on('resize', debounce(resizeForm));

  resizeForm();
});
.resultlist {
  position: relative;
  width: 200px;
  height: 200px;
  overflow: auto;
}

.list-content {
  position: relative;
  height: 500px;
  width: 500px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="resultlist">
  <div class="list-content">Text</div>
</div>

The code uses standard WheelEvent and a debouncer to prevent the resize event to be handled continuously (resize event fires tens of times per second during resizing). The resize handler updates width and dirProp variables, which then are used in the WheelEvent handler to determine which way to scroll the element (with the bracket notation you can use a variable as a property name).

It's notable, that the strict mode is a must with this code, otherwise the debouncer might actually consume more time than it was purposed to save.

You might want to add some kind of "scroll home" function to reset the scrollable element when the window size is changed. You can test the code at jsFiddle.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda