1
\$\begingroup\$

I have a jQuery code that helps me to scroll to specific sections on mouse scroll. To handle mouse scroll events I am using the jQuery mousewheel plugin.

    function goTo(location) {             
        $('html,body').animate({
            scrollTop: $(location).offset().top
        }, 'slow');
         };
    //Mouse Wheel 
// My code is repeating consistently below these line
    $('#slides').on('mousewheel', function(event) {
        event.preventDefault();
        if (event.originalEvent.wheelDelta >= 0) {} else {
            //console.log('Scroll down');
            goTo("#rev_slider_2_1");
        }
    });
    $('#rev_slider_2_1').on('mousewheel', function(event) {
        event.preventDefault();
        if (event.originalEvent.wheelDelta >= 0) {
            goTo("#slides");
        } else {
            //console.log('Scroll down');
            goTo("#clients");
        }
    });

    $('#clients').on('mousewheel', function(event) {
        event.preventDefault();
        if (event.originalEvent.wheelDelta >= 0) {
            goTo("#rev_slider_2_1");
        } else {
            //console.log('Scroll down');
            goTo("#slider");
        }
    });

I want to simplify and make this code shorter so that I no longer need to use the same code again and again. I just want to know how I can create a function that helps me to just pass the parameters and then do my required task.

\$\endgroup\$
0

1 Answer 1

4
\$\begingroup\$

A simple each loop could make your code smaller, something like:

var elems = [
  $('#slides'),
  $('#rev_slider_2_1'),
  $('#clients')
];

$.each(elems, function (index, $elem) {
  var previous = index > 0 : elems[index-1].id : null;
  var next = index < elems.length-1 ? elems[index+1].id : null;
  $elem.on('mousewheel', function(event) {
    event.preventDefault();
    if (event.originalEvent.wheelDelta >= 0 && previous) {
        //console.log('Scroll up');
        goTo(previous);
    } else if (next) {
        //console.log('Scroll down');
        goTo(next);
    }
  });
});
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.