What is the best way to implement horizontal content scrolling when an arrow is tapped in mobile view?

I recently created a JS Fiddle that seems to be working fine on desktop, but in mobile view, the square boxes have horizontal scrolling.

Here are the CSS codes I used for this particular issue:

@media only screen and (max-width: 767px)
{
.product-all-contents
{
   overflow-x: auto;
}

.product-contents .product{
  min-width: 50.795%;
  margin: 0 2%;
  padding-top: 3.91%;
  padding-left: 3.91%;    
  padding-right: 3.91%;
  }
}


The Challenge I Am Facing:

I am trying to figure out how to modify the JS Fiddle so that when arrows are clicked in the mobile view (as shown in the screenshot below with an orange arrow), the content moves left or right accordingly.

I believe using jQuery, scrollLeft(), and scrollRight() would be ideal, but I'm unsure about implementing it in the current setup of the JS Fiddle.

https://i.stack.imgur.com/UHYhA.jpg

Answer №1

When addressing your issue, there are a few key steps to take

  1. Ensure you set up two buttons to handle the listeners in your code
  2. Retrieve the initial position to calculate the slide

    let divMain = $('.product-all-contents')[0]; let position = $(divMain).children().position().left; const slideAmount = 150;

These three variables will serve as the core values for your code

  1. Lastly, establish the event listeners for the slide

    $('#arrow-right').click(function() { $(divMain).animate({ scrollLeft: position + slideAmount }, 500); position += slideAmount; })

Hopefully this explanation proves helpful :>

$(document).ready(function() {
  let divMain = $('.product-all-contents')[0];
  let position = $(divMain).children().position().left;
  const slideAmount = 150;

  $('#arrow-right').click(function() {
    $(divMain).animate({
      scrollLeft: position + slideAmount
    }, 500);
    position += slideAmount;
  })

  $('#arrow-left').click(function() {
    $(divMain).animate({
      scrollLeft: position - slideAmount
    }, 500);
    position -= slideAmount;
  })
});
.product-all-contents {
  background-color: #f0f0f0;
  width: 70%;
  margin: auto;
}

.product-contents {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
}

.product-contents .product {
  width: 10%;
  text-align: center;
  height: 150px;
  padding-top: 1%;
  padding-left: 1%;
  padding-right: 1%;
  border-style: solid;
  border-width: 3px;
  border-color: rgb(145, 147, 150);
  background-color: white;
  border-radius: 10px
}

.ipads {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
}

.tvs {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
}

.franchise-hub-text,
.cloud-based-text,
.business-analytics-text,
.tech-support-text,
.order-management-text,
.employee-management-text,
.white-label-text,
.brand-label-text,
.lead-tracking-text,
.custom-invoicing-text,
.goal-setting-text,
.customization-tools-text,
.royalty-calculator-text,
.email-marketing-text {
  width: 50%;
}

div.goal-setting,
div.customization-tools,
div.custom-invoicing,
div.lead-tracking,
div.email-marketing,
div.royalty-calculator,
div.brand-control,
div.franchisehubtv,
div.cloudbasedtextipad,
div.business-analytics,
div.tech-support,
div.employee-management,
div.order-management,
div.white-label {
  display: flex;
  margin-left: 15%;
  margin-right: 15%;
  align-items: center;
  background-color: #f0f0f0;
  padding: 2%;
  margin-bottom: 5%;
}

.product-quotes {
  display: block;
  padding: 20px 11px;
  width: 90%;
  color: #3b3b3d;
  background: white;
  border-radius: 2px;
  line-height: 1.625;
  font-family: 'Roboto';
  font-weight: normal;
  "`

}

.arrow-down {
  width: 0;
  height: 0;
  margin: auto;
  border-left: 40px solid transparent;
  border-right: 40px solid transparent;
  border-top: 40px solid #f0f0f0;
}

.white {
  display: none;
}

@media only screen and (max-width: 767px) {
  .product-all-contents {
    overflow-x: auto;
  }
  .product-contents .product {
    min-width: 50.795%;
    margin: 0 2%;
    padding-top: 3.91%;
    padding-left: 3.91%;
    padding-right: 3.91%;
  }
}

@media only screen and (max-width: 767px) {
  div.goal-setting,
  div.customization-tools,
  div.custom-invoicing,
  div.lead-tracking,
  div.email-marketing,
  div.royalty-calculator,
  div.brand-control,
  div.franchisehubtv,
  div.cloudbasedtextipad,
  div.business-analytics,
  div.tech-support,
  div.employee-management,
  div.order-management,
  div.white-label {
    display: inline-block !important;
  }
}

@media only screen and (max-width: 767px) {
  .franchise-hub-text,
  .cloud-based-text,
  .business-analytics-text,
  .tech-support-text,
  .order-management-text,
  .employee-management-text,
  .white-label-text,
  .brand-control-text,
  .lead-tracking-text,
  .custom-invoicing-text,
  .goal-setting-text,
  .customization-tools-text,
  .royalty-calculator-text,
  .email-marketing-text {
    width: 100%;
  }
}
<!doctype html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Testing</title>
  <link rel="stylesheet" href="sample.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script type="text/javascript" src="script/myscript.js"></script>

</head>

<body>

  <div class="product-all-contents">
    <div class="product-contents">
      <div class="product" id="franchisehub">

        <p style=" font-size: 15px; font-family: 'Roboto'; margin-left: 7%; margin-right: 7%; line-height: 1.2; margin-top: 20%;
         color: rgb(58, 59, 60);">A</p>
      </div>

      <div class="product" id="cloudbasedmobile" style="background-color:#81bf44;">

        <p style=" font-size: 15px;
         font-family: 'Roboto';line-height:1.2; margin-top: 27%;
         color:white;">Z</p>
      </div>
      <div class="product" id="businessanalytics">

        <p style=" font-size: 15px;
         font-family: 'Roboto';line-height:1.2; margin-top: 22%;
         color: rgb(58, 59, 60);">B</p>
      </div>
      <div class="product" id="techsupport">

        <p style=" font-size: 15px;
         font-family: 'Roboto';
         margin-right: 9%;
         line-height: 1.2;
         margin-left: 9%; margin-top: 22%;
         color: rgb(58, 59, 60);">C</p>
      </div>

      <div class="product" id="ordermanagement">

        <p style=" font-size: 15px;
         font-family: 'Roboto';line-height:1.2; margin-top: 23%;
         color: rgb(58, 59, 60);">D</p>
      </div>

      <div class="product" id="employeemanagement">
        <p style=" font-size: 15px;
         font-family: 'Roboto';line-height:1.2; margin-left: 5%; margin-top: 27%;
         color: rgb(58, 59, 60);">E</p>
      </div>
      <div class="product" id="whitelabel">
        <p style="
         font-size: 15px;
         font-family: 'Roboto';
         line-height:1.2;
         margin-left: 14%;
         margin-right: 14%; margin-top: 8%;
         color: rgb(58, 59, 60);
         ">M</p>
      </div>
    </div>
    <div class="product-contents">
      <div class="product" id="brandcontrol">

        <p style="
         font-size: 15px;
         font-family: 'Roboto';
         margin-left: 8%;
         line-height:1.2;
         margin-right: 8%; margin-top: 20%;
         color: rgb(58, 59, 60);
         ">F</p>
      </div>
      <div class="product" id="leadtracking">

        <p style="
         font-size: 15px;
         font-family: 'Roboto';
         line-height:1.2;
         margin-left: 5%;
         margin-right: 5%; margin-top: 26%;
         color: rgb(58, 59, 60);
         ">G</p>
      </div>
      <div class="product" id="custominvoicing">

        <p style=" font-size: 15px;
         font-family: 'Roboto';line-height:1.2; margin-top: 24%;
         color: rgb(58, 59, 60);">K</p>
      </div>
      <div class="product" id="goalsetting">

        <p style="font-size: 15px;
         font-family: 'Roboto';
         margin-right: 13%;
         margin-left: 13%;
         line-height: 1.2; margin-top: 24%;
         color: rgb(58, 59, 60);">H</p>
      </div>
      <div class="product" id="customizationtools">

        <p style=" font-size: 15px;
         font-family: 'Roboto';line-height:1.2; margin-top: 22%;
         color: rgb(58, 59, 60);">I</p>
      </div>
      <div class="product" id="royaltycalculator">

        <p style=" font-size: 15px;
         font-family: 'Roboto';line-height:1.2; margin-left: 5%; margin-top: 23%;
         color: rgb(58, 59, 60);">J</p>
      </div>
      <div class="product" id="emailmarketing">

        <p style="
         font-size: 15px;
         font-family: 'Roboto';
         margin-left: 5%;
         margin-right: 5%;
         line-height:1.2; margin-top: 21%;
         color: rgb(58, 59, 60);
         ">K</p>
      </div>
    </div>
  </div>


  <button id="arrow-left">&#60----</button>

  <button id="arrow-right">----&#62</button>





</body>

</html>

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

Safari on iOS 9 having trouble playing embedded YouTube videos

Recently, I discovered that my YouTube embedded videos are not playing on iOS devices when on my website unless you click in the top left corner of the video. Even after removing all extra YouTube parameters and using standard iFrame embed code, the issue ...

Creating a polyBezier or polyCurve with Canvas HTML: a step-by-step guide

Looking to connect several points with a curve rather than just a straight line. I attempted using the lineTo() and bezierCurveTo() methods to draw the points. Is there anyone who can assist me in solving this dilemma? Perhaps there is a different approac ...

Angular 5 - Creating a dynamic function that generates a different dynamic function

One of my latest projects involved creating a versatile function that generates switch-case statements dynamically. export function generateReducer(initialState, reducerName: ReducerName, adapter: EntityAdapter<any>): (state, initialState) => ISt ...

Utilizing Custom Script Tag Types in Visual Studio for Enhanced HTML Template Functionality and Improved Syntax Highlighting

Currently, I am utilizing Visual Studio 2012 for editing HTML and JavaScript. My approach involves inserting templates using partial views in inline script tags (view code below). The use of AngularJS, a Javascript framework, dictates that the type must be ...

AngularJS: Modify Z-Index on Click Event

My current project involves a navigation bar with four items, each accompanied by an icon. These icons are positioned absolutely one behind the other and are loaded into the view from different templates within the same controller. I am attempting to dyna ...

Ensure that both the div element and its contents are restricted to a maximum width of

I'm having trouble arranging the display of information next to a plant image. I want to ensure that the information stays on the right side of the image when the screen reaches a specific minimum width. The issue arises when the information includes ...

Tips for running a React custom hook selectively or within a specific function

I have created a unique custom hook to handle user redirection to the edit page. While on the index page, users can duplicate and delete items. The issue arises when deleting an item triggers the custom hook to redirect back to the edit page. I am looking ...

Troubleshooting problems with deploying an Angular app on Heroku

When I attempt to deploy my Angular app on Heroku, I am running into a 'Not found' error and getting additional information in the console ("Failed to load resource: the server responded with a status of 404"). Below is the entire Heroku build l ...

Permit the use of HTML tags within a CSS-only tooltip

I have created a unique CSS tooltip. <span data-tooltip="The security code is a 3-digit number<br />on the back of your Visa or Mastercard debit or credit card, or a 4-digit number on the front of your American Express card.">Help</span> ...

Shared items found in a pair of entities

This function currently returns the difference between two objects, but I need to modify it so that it returns the common objects instead. Any assistance on how to achieve this would be greatly appreciated. Array example: var array1 = [ { "Name": " ...

Customizing colors in React Material UI

Can colors in Material UI be overridden without the use of JS? Is it possible to override colors using CSS alone? ...

Obtain the value using jQuery from an AJAX request and display it

When I write the code below, the alert output is null: var availableSlots = ""; $.get( '', { availableSlots: userName }, function(a) { availableSlots = a; }); alert(availableSlots); Putting the alert inside the get function works fine, but ...

Tips for altering the appearance of the material-ui slider thumb design when it is in a disabled state

Through the use of withStyles, I have successfully customized the style of the Slider: const CustomSlider = withStyles(theme => ({ disabled: { color: theme.palette.primary.main }, thumb: { height: 24, width: 24, }, }))(Slider); How ...

Ways to usually connect forms in angular

I created a template form based on various guides, but they are not working as expected. I have defined two models: export class User { constructor(public userId?: UserId, public firstName?: String, public lastName?: String, ...

When a table cell is hovered over, a left border will be added

I've been working on adding a left border to the text in a way that highlights the first cell's border when hovering over a row, providing a clear indication of the current row for users. Feel free to check out my progress so far on this fiddle: ...

Sending dynamic data from PHP to jQuery flot pie chart

In my PHP code, I have defined 3 variables. $record = "283-161-151"; $rec = explode("-", $record); $win = $rec[0]; $draw = $rec[1]; $loss = $rec[2]; The variables $win, $draw, and $loss are displaying correctly, indicating they are working as intended. ...

Customize the asset path location in Webpack

I am currently working on a Vue application that utilizes Webpack for code minimization. Is there a method to dissect the chunks and adjust the base path from which webpack retrieves the assets? For example, by default webpack fetches assets from "/js" o ...

The $() function in jQuery consistently yields 'undefined' when used in conjunction with AJAX requests

I've noticed that the popup shows up before the text in the textbox gets updated. It seems like the JavaScript is being called before the page is fully rendered, which may be causing the 'undefined' popup. How can I ensure that JavaScript is ...

Styles for Material UI 5 class names

After upgrading from Mui 4 to 5, I am facing a challenge in using class names effectively. While the SX property allows me to apply styles to individual components, I am struggling with applying the same class to multiple components. In version 4, my code ...

Consecutive pair of JavaScript date picker functions

My issue involves setting up a java script calendar date picker. Here are my input fields and related java scripts: <input type="text" class="text date" maxlength="12" name="customerServiceAccountForm:fromDateInput" id="customerServiceAccountForm:from ...