The jQuery scrollLeft function seems to be stuck and not working correctly

I have a container div with a ul inside of it set up like this CodePen: http://codepen.io/example/123

Why won't the scroll feature work?

HTML:

<div id="container">
  <ul class="list">
    <li>apple</li>
    <li>orange</li>
    <li>banana</li>
  </ul>
</div>
<button id="left">←</button>
<button id="right">→</button>

CSS:

#container {
  width: 200px;
  height: 50px;
  overflow: scroll;
}
.list {
  width: 1000px;
}
.list li {
  background: blue;
  width: 99px;
  height: 40px;
  border-right: 1px solid black;
  float: left;
  padding: 5px;
}

JavaScript:

var position = $(".list").scrollLeft();
$(document).ready(function() {
  $("#right").on("click", function() {
    $(".list").animate({
      scrollLeft: position + 100
    }, 1000);
  });
});

Answer №1

To make the content scroll horizontally, you should use the scrollLeft property on an element with the overflow set, like the element with the id of #outside.

Check out a live demo on jsBin

$(function() {  // Shortened version for DOM READY
  
  $("#right, #left").click(function() {
    var dir = this.id=="right" ? '+=' : '-=' ;
    $("#outside").stop().animate({scrollLeft: dir+'100'}, 1000);
  });

});

In this code snippet, both buttons, with ids of #right and #left, are linked to the same click event handler. Depending on which button is clicked, the value of dir will be either "+=" or "-=". This allows for intuitive scrolling functionality.

Answer №2

Everything is functioning flawlessly

To achieve optimal results, be sure to include either offset() or position(). Additionally, remember to animate the left property.

$(document).ready(function() {
  $("#right").bind("click", function() {
    var position = $("#inside").position();
    $("#inside").animate({
      left: position.left - 100
    }, 1000);
  });
});
$("#left").bind("click", function() {
  var position = $("#inside").position();
  $("#inside").animate({
    left: position.left + 100
  }, 1000);
});

Adjustments Needed

  1. When applying float: left;, ensure you clear your floats properly. Please await the completion of the fiddle...
  2. JQuery has not been loaded in your fiddle.
  3. Remember to assign position: relative; to the UL.

Fiddle Link: http://jsfiddle.net/BQPVL/9/

Answer №3

For a helpful solution, consider utilizing the following code: http://jsfiddle.net/BQPVL/10/

$("#right").on("click", function () {
  $("#inside").stop(true, true).animate({
    left: '-=100'
  }, 1000);
});
$("#left").on("click", function () {
  $("#inside").stop(true, true).animate({
    left:'+=100'
  }, 1000);
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Sending PHP arrays through AJAX using json_encode

After creating the array called $latent_weights_array, my goal is to trigger a PHP script using Ajax when the 'save' button is clicked. This will involve passing the array as a $_GET variable. In PHP <?php echo "<input type='butt ...

Modifications to contenteditable elements result in a change to their IDs

Having some trouble with the behavior of a contenteditable div. The code structure is like this: <div contenteditable="true"> <p id="element-id-1">element-id-1</p> <p id="element-id-2">element-id-2</p> </div> E ...

Resetting the Countdown Clock: A Transformation Process

I have implemented a countdown timer script that I found online and made some adjustments to fit my website's needs. While the current setup effectively counts down to a specific date and time, I now require the timer to reset back to a 24-hour countd ...

Display the Image Element in Angular only when the image actually exists

In my HTML code, I have two sibling elements - one is an image and the other is a div. I want to display the image element if the image exists, and show the div element if the image doesn't exist. Here's how my elements are structured: <img ...

I'm looking for a way to have an element shift in a particular direction only when two keys are pressed simultaneously

Having trouble moving a square diagonally when two keys are pressed simultaneously. Trying to create an if statement that detects both key presses at the same time and triggers the movement. However, all attempts have failed so far, leaving uncertainty abo ...

What is the best way to ensure that the buttons remain in place once they have been clicked to reveal a drop-down menu?

Is there a way to keep 3 buttons inline and prevent them from moving when clicked to open a submenu? Changing their positions results in them stacking on top of each other. Any help or suggestions would be greatly appreciated, thank you! Here is the code ...

Organize objects neatly in a grid formation

I have a .test div with grid-template-columns: auto auto auto;. The column width is set to vary based on the element width, and I also used justify-content: start; to align the columns to the left. I chose to use auto instead of 1fr to prevent the columns ...

What is the best way to adjust the width of a textarea based on its content

How can I dynamically set the width of a React Semantic UI textarea based on its content? Setting min-width doesn't seem to be working. Any suggestions? <Textarea key={idx} defaultValue={formattedText} className="customInpu ...

Creating an interactive time selection tool with two dropdown lists that are dependent on each other using HTML and JavaScript

Hi everyone, I am new to JavaScript. I am currently working on creating two dropdown lists, one for 'Start Time' and another for 'End Time'. These dropdown lists will display hours in a 24-hour format with intervals of 30 minutes. In t ...

Guide on utilizing ajax to post data when the URL parameter changes, all without refreshing the page

As the URL parameter changes, the values in my HTML also change. I am passing these values to a JSON file, but they are getting erased when the page refreshes due to the post request. I have attempted to use event.preventDefault(), however, it seems to n ...

Step-by-step guide on triggering a button using another button

I have a unique question that sets it apart from others because I am looking to activate the button, not just fire it. Here is my syntax: $("#second_btn").click(function(){ $('#first_btn').addClass('active'); }) #first_btn ...

Column that adjusts to different screen sizes

In the realm of responsive web design, what methods are suggested to achieve the specified CSS display? My main requirement is to have a maximum of three columns. The content should be divided evenly among these three columns. I prefer using SCSS and wel ...

Are cookies always included in client requests?

With every interaction between the server and browser, cookies are exchanged back and forth. However, what happens when an image is requested? <img src='myPic.jpg' /> Is the browser also sending cookies during this type of request? If i ...

What is the best way to perform an AJAX request in Typescript with JSON data?

Currently, I am delving into the realm of AJAX and encountering some hurdles when attempting to execute an AJAX request with parameters. Specifically, I am facing difficulties in sending JSON data: My approach involves utilizing Typescript in tandem with ...

Troubleshooting techniques for interacting with input fields in Django-admin tabular inlines through ajax

Seeking ways to dynamically update inline entries with ajax. For instance, as the user chooses an item from the dropdown box, the associated input fields can auto-fill with data. The ajax views.py section should be relatively simple. However, one hurdle I ...

Enhancing user experience with VideoJS player overlay buttons on mobile devices

I am currently using VideoJs player version 4.2. When I launch a videojs player on Safari browser in an iOS device, it defaults to native controls. However, when I pause the player, overlay buttons (links to navigate to other pages) are displayed on the v ...

Phone Validation for Contact Form 7

Recently, I was tasked with creating a landing page for a job interview. The challenge was to include validation on the phone number field so that it has to be between 9 and 10 numbers in length, along with another validation requiring the phone number t ...

JavaScript failing to load following PHP header() redirect

I've set up a page that allows users to sign in by filling out a basic form, which then sends the data to a separate PHP script for validation. After the validation process is complete, the PHP script uses the header() function to redirect the user to ...

python selenium - Element not found on Justdial website

I've exhausted all options: Attempted both implicit and explicit wait methods Used the wait.until function Utilized the Time module I'm currently attempting to locate the "Load more reviews" link on JustDial. Here is the link. Could you please ...

When implementing afui and jQuery on PhoneGap, an error was encountered: "TypeError: Cannot read property 'touchLayer' of object function (selector, context)"

While working on deploying a web application using phonegap with afui (Intel Appframework UI) for Android, I encountered an issue when testing it in the android emulator. The debug console displayed the following error right after launching the app: Uncau ...