Scroll through content using buttons in JavaScript can be utilized repeatedly as needed

I want to showcase a collection of movies on my website through a horizontal, scrollable div. Since I disabled the scrollbar, users can no longer scroll, leading me to incorporate two buttons - one for moving right and one for moving left.

However, the issue arises when users repeatedly press the buttons, causing the movies to get obstructed due to the additional margin applied through Javascript.

How can I tackle this problem? I aim to deactivate the left-button when the starting position is reached and deactivate the right-button when the end position is reached.

$('#right-button').click(function() {
event.preventDefault();
$('.movie-scroll').animate({
marginLeft: "-=200px"
}, "fast");
});
$('#left-button').click(function() {
event.preventDefault();
$('.movie-scroll').animate({
marginLeft: "+=200px"
 }, "fast");
});
::-webkit-scrollbar {
display: none;
}

.sc_content {
overflow-y: scroll;
}

.title_home {
font-size: 18px;
margin: 30px 0px -10px 30px;
}

.movie-scroll {
height: 300px;
white-space: nowrap; 
overflow-x: scroll;
margin-right: 30px;
}

.thumbnail-movie-box {
width: 130px;
margin: 30px 0px 0px 30px;
display: inline-block;
}

.thumbnail-movie-content {
display: block;
 position: relative;
}

.thumbnail-movie-poster {
width: 130px;
height: 195px;
}

.thumbnail-movie-title {
    font-size: 12px;
    font-weight: bold;
margin: 5px 0px 10px 0px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}

.thumbnail-movie-year {
font-size: 12px;
margin: -5px 10px 10px 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>  
<div class="sc_content">
  <h1 class="title_home">Movies</h1>
  <a href="#" id="left-button">Left</a>
  <div class="movie-scroll">
    <div class="thumbnail-movie-box">
      <a href="">
        <div class="thumbnail-movie-content">
          <img class="thumbnail-movie-poster" src="https://image.tmdb.org/t/p/w500/ijoPd2gdt8jW982fGemySKDOGtv.jpg">
        </div>
      </a>
      <a href="">
        <p class="thumbnail-movie-title">Split</p>
      </a>
      <p class="thumbnail-movie-year">2016</p>
   </div>
   <div class="thumbnail-movie-box">
      <a href="">
        <div class="thumbnail-movie-content">
          <img class="thumbnail-movie-poster" src="https://image.tmdb.org/t/p/w500/ijoPd2gdt8jW982fGemySKDOGtv.jpg">
        </div>
      </a>
      <a href="">
        <p class="thumbnail-movie-title">Split</p>
      </a>
      <p class="thumbnail-movie-year">2016</p>
   </div>
   <div class="thumbnail-movie-box">
      <a href="">
        <div class="thumbnail-movie-content">
          <img class="thumbnail-movie-poster" src="https://image.tmdb.org/t/p/w500/ijoPd2gdt8jW982fGemySKDOGtv.jpg">
        </div>
      </a>
      <a href="">
        <p class="thumbnail-movie-title">Split</p>
      </a>
      <p class="thumbnail-movie-year">2016</p>
   </div>
   <div class="thumbnail-movie-box">
      // Repeat for other movie boxes
   </div>
</div>
<a href="#" id="right-button">Right</a>

Answer №1

Check out this Fiddle for the solution: https://jsfiddle.net/zbavtpj4/

To make the necessary changes in your javascript, use the code below:

var positionIndex = 0;

$('#right-button').click(function() {
        event.preventDefault();
    if(positionIndex <= 7){
      $('.movie-scroll').animate({
          marginLeft: "-=200px"
      }, "fast");
      positionIndex++;
    }
});
$('#left-button').click(function() {
        event.preventDefault();
    if(positionIndex >= -2){
      $('.movie-scroll').animate({
          marginLeft: "+=200px"
       }, "fast");
       positionIndex--;
     }
});

This code tracks the position with an index and adjusts the margin only within specified boundaries. In this example, the boundaries are set manually. While it is possible to set boundaries programmatically, it was not implemented in this case due to time constraints.

Answer №2

Prior to initiating any animation, it is crucial to verify the current margin-left value of .movie-scroll.

If the margin-left value is greater than or equal to 0, the action for #left-button should not be executed.

Similarly, if the margin-left value exceeds the width of .movie-scroll, the action for #right-button should be prevented from occurring.

Answer №3

This section focuses on width calculations and comparisons.

Click here for the latest Fiddle update.

console.clear();

var filmWidth = $('.movie-scroll').outerWidth();
console.log(filmWidth);
var screenWidth = $(window).outerWidth();
console.log(screenWidth);
var posterWidth = $(".thumbnail-movie-poster").outerWidth();
console.log(posterWidth);

var leftBound = false;
var rightBound = false;

$('#right-button').click(function() {

  event.preventDefault();
  if(!rightBound){
    $('.movie-scroll').animate({
      marginLeft: "-=200px"
    }, "fast");
  }
  checkScrolling("right");
});

$('#left-button').click(function() {
  event.preventDefault();
  if(!leftBound){
    $('.movie-scroll').animate({
      marginLeft: "+=200px"
    }, "fast");
  }

  checkScrolling("left");
});

function checkScrolling(direction){
  setTimeout(function(){
    var scroll = parseInt($('.movie-scroll').css("marginLeft"));
    console.log(scroll);

    leftBound = false;
    rightBound = false;

    if(scroll>screenWidth-2*posterWidth && direction=="left"){
      console.log("left "+scroll);
      leftBound = true;
    }
    if(-scroll>=screenWidth+filmWidth+0.10*posterWidth && direction=="right"){
      console.log("right "+scroll);
      rightBound = true;
    }
  },300);
}

I included numerous console logs to aid in understanding the functionality...

Answer №4

I apologize for the delay in sharing my response, but I believe this solution is scalable and will meet your requirements.

/* JavaScript Code */
var scrollWidth = parseInt($('.movie-scroll .thumbnail-movie-box').first().next().position().left) - parseInt($('.movie-scroll .thumbnail-movie-box').first().position().left);
var noOfItems = $('.movie-scroll .thumbnail-movie-box').length;
var count = 0;
$('#right-button').click(function() {
  event.preventDefault();
  var movieScroll = $('.movie-scroll');
  movieScroll.filter(function() {
    if (count == (noOfItems - 1))
      return false;
    count++;
    return true;
  }).animate({
    marginLeft: "-=" + scrollWidth + "px"
  }, "fast");
});
$('#left-button').click(function() {
  event.preventDefault();
  var movieScroll = $('.movie-scroll');
  movieScroll.filter(function() {
    if (count == 0)
      return false;
    count--;
    return true;
  }).animate({
    marginLeft: "+=" + scrollWidth + "px"
  }, "fast");
});
/* CSS Styles */
::-webkit-scrollbar {
  display: none;
}

.sc_content {
  overflow-y: scroll;
}

.title_home {
  font-size: 18px;
  margin: 30px 0px -10px 30px;
}

/* Additional CSS styles for movie-scroll and thumbnail-movie-box classes */
<!-- HTML Content -->

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="sc_content">
  <h1 class="title_home">Movies</h1>
  <a href="#" id="left-button">Left</a>
  <div class="movie-scroll">
    <div class="thumbnail-movie-box">
      <a href="">
        <div class="thumbnail-movie-content">
          <img class="thumbnail-movie-poster" src="https://image.tmdb.org/t/p/w500/ijoPd2gdt8jW982fGemySKDOGtv.jpg">
        </div>
      </a>
      <a href="">
        <p class="thumbnail-movie-title">Split</p>
      </a>
      <p class="thumbnail-movie-year">2016</p>
    </div>
    /* Additional thumbnail-movie-box elements */
  </div>
  <a href="#" id="right-button">Right</a>

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

Integrating fresh components into a JSON structure

I've been attempting to insert a new element into my JSON, but I'm struggling to do it correctly. I've tried numerous approaches and am unsure of what might be causing the issue. INITIAL JSON INPUT { "UnitID":"1148", "UNIT":"202B", "Sp ...

Using AJAX for uploading files upon a change event rather than upon submission

Below is the code I have been using to implement an iframe for ajax file upload without refreshing the page upon form submission. The current code works as expected. window.onload=init; function init() { document.getElementById('form').onsubmi ...

A guide on displaying containers with jQuery and CSS

Looking to create a smiley survey using only Front-End technologies. Once a radio button is selected, the associated content should appear for comments. Currently, I have set up my CSS with display: none. I attempted to implement this functionality using ...

Transferring multiple parameters between components using Navigate and ParamMap

My concern is that I'm unsure of how to pass multiple parameters through the component's route. I need to send two attributes. Is there a specific syntax required in defining the route? Below is my desired functionality for passing the attribut ...

How can we enforce that the input consists of digits first, followed by a space, and then

Can regex (with javascript possibly) be used to mandate numbers, followed by a space, and then letters? I'm a bit lost on where to start with this... I understand that using an HTML5 pattern would work for this... [0-9]+[ ][a-zA-Z0-9]+ However, I ...

Prevent Float Filtering in AngularJS

As I work on creating a directive in AngularJs, I am facing an issue. The directive is supposed to receive a JSON object from the app controller and display its content accordingly. To better illustrate my problem, I have created a simple demo which can b ...

Unable to locate and interact with a specific element within a dropdown menu while utilizing Protractor

I am currently facing an issue with selecting a checkbox from a dropdown in jq widgets. The code seems to work fine when the element is visible on the screen, but fails otherwise. I have tried various methods such as executeScript and scrollIntoView to bri ...

Utilizing combined selectors in styled-components: A comprehensive guide

My existing CSS code is structured like this: .btn_1 { color: #fff; background: #004dda; display: inline-block; } .btn_1:hover { background-color: #FFC107; color: #222 !important; } .btn_1.full-width { display: block; width: 100%; } I ...

Extracting information from a table containing both obscured and accessible rows

Currently, I am attempting to scrape data from this specific website by utilizing Selenium. While my code successfully loads the desired table, I encounter challenges when trying to extract data from hidden rows, even though the information is visibly pres ...

How to retrieve the output of a nested function in Node.js

I have been attempting to retrieve a value from a function nested inside another function in my Node.js application, but it always seems to return undefined. var geo = { list: function(callback){ var returnval; gapi.getcodes(function(e ...

Fixing the issue with animated scrolling in React Native's Flatlist component

I attempted to customize the default refresh indicator for a Flatlist in React Native. My goal was to create something similar to Snapchat, Instagram, or the default iOS refresh indicator instead of the unattractive Android indicator. This is what I tried: ...

"Placing the save button on top of a div - a step

I am trying to position a div with an ID below a save button in my HTML code. The current setup looks like this: <button id="item_new" data-action="create" class="floating-button mdl-button mdl-js-button mdl-button--fab mdl-js-ripple-effect mdl-button- ...

MUI-Datatable rows that can be expanded

I'm attempting to implement nested tables where each row in the main table expands to display a sub-table with specific data when clicked. I've been following the official documentation, but so far without success. Below is a code snippet that I& ...

Conditions in Controller Made Easy with AngularJS

I have recently started working on implementing a notifications feature. The service will involve making a GET request to a specific URL which will then return an array of notifications. Within the controller, I am in the process of setting up a variable ...

Angular 2 - Module 'ng-factory' not found

I am encountering an issue when trying to launch my clean UI theme using 'ng serve'. This is my first time working with Angular and I'm struggling to resolve this problem. Any assistance would be greatly appreciated. I have attempted re-inst ...

What methods can be used to protect (encrypt using Java code) the information in a login form before it is sent to a servlet for

One major concern I have involves sending encrypted data (encrypted before sending the request) to a servlet. I attempted to call a function that encrypts passwords as an example, but I encountered difficulty passing values from JavaScript to Java code in ...

How to create ::after pseudo-element with identical width as its preceding sibling

My HTML code includes a <div> container with an <img> and an ::after pseudo-element. Check it out: <div class="container" data-caption="The caption should match the width of the image and wrap accordingly"> <img> </div> . ...

`The challenge of a single web page not displaying correctly`

I was working on a website for a local computer building company, and I decided to make it a single-page applet. The HTML is mostly done, and I don't have much trouble with CSS. However, I encountered an issue with hiding and displaying different sect ...

AngularJS and KendoUI integration experiencing delays during script evaluation

At the moment, I am conducting performance measurements and analysis on our AngularJS-KendoUI application in an effort to identify any bottlenecks. Following a helpful article and an informative presentation, I am using Chrome DevTools timeline tab to anal ...

Implementing Laravel's functionality for calculating average ratings with the help of jQuery

In my database, I have two tables named Users and ratings. The Users can give ratings to consultants, and the Ratings table structure is as follows: User_id | consultant_id | rating --------------------------------- 1 1 2 ...