Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery Horizontal Scroll on Click

Tags:

html

jquery

css

I am trying to get this horizontal section of the page to auto scroll when the left or right arrows are clicked. I can get the Jquery code to run correctly in the console. However, the auto scroll events won't run at all on my page. Could anyone provide any insight into this issue?

The code is as follows :

HTML

<div class = "horizon horizon-prev">
      <img src = "../images/left-arrow.png" />
    </div>
    <div class = "horizon horizon-next">
      <img src = "../images/right-arrow.png" />
    </div>

  <div class="center" id="content">
      <div class=internal>
        div 1
      </div>
       <div class=internal>
        div 2
      </div>
       <div class=internal>
        div 3
      </div>
       <div class=internal>
        div 4
      </div>
       <div class=internal>
        div 5
      </div>
       <div class=internal>
        div 6
      </div>
       <div class=internal>
        div 7
      </div>
       <div class=internal>
        div 8
      </div>
    </div>

CSS

div.center {
 width: 90%;
 height: 210px;
 border: 1px solid #000;
 margin: auto;
 overflow-x: hidden;
 overflow-y: hidden;
 white-space: nowrap;
  }
  div.internal {
   display: inline-block;
   vertical-align: middle;
   width: 100%;
   text-align: center;
  }

Jquery

$('.horizon-prev').click(function() {
  event.preventDefault();
  $('#content').animate({
    scrollLeft: "-=775px"
  }, "slow");
});

 $('.horizon-next').click(function() {
  event.preventDefault();
  $('#content').animate({
   scrollLeft: "+=775px"
  }, "slow");
});
like image 435
Seth Spivey Avatar asked May 26 '16 14:05

Seth Spivey


People also ask

How to scroll horizontally with jQuery?

The scrollLeft() method sets or returns the horizontal scrollbar position for the selected elements. Tip: When the scrollbar is on the far left side, the position is 0. When used to return the position: This method returns the horizontal position of the scrollbar for the FIRST matched element.

What is scrollLeft?

scrollLeft property gets or sets the number of pixels that an element's content is scrolled from its left edge.

How do you animate in scrollLeft?

To animate scrollLeft using jQuery, use the animate() method with scrollLeft.


1 Answers

(based on looking at your site sethspivey.com)

You need to add the missing event parameter you are using, and also move the click handlers into document.ready, like so:

$(function() {
  $('.horizon-prev').click(function(event) {
    event.preventDefault();
    $('#content').animate({
      scrollLeft: "-=775px"
    }, "slow");
  });

   $('.horizon-next').click(function(event) {
    event.preventDefault();
    $('#content').animate({
     scrollLeft: "+=775px"
    }, "slow");
  });
});
like image 162
libcthorne Avatar answered Oct 12 '22 20:10

libcthorne