Verify whether the element is capable of being scrolled sideways

Is it possible to add indicators to a div to show users that they can scroll left or right within the content? I need a way to detect if the element can be scrolled to either side, so that I can display the appropriate indicator. For example, when there is content hidden on the right, show a right indicator, and once the user scrolls, show a left indicator for scrolling in the opposite direction. Here's a sample setup: https://jsfiddle.net/udv8u596/

(You can scroll horizontally, scrollbar is intentionally hidden)

HTML:

<div class="scroll-container">
    <div class="scroll-content>
        Scroll Me Horizontally Scroll Me Horizontally Scroll Me Horizontally Scroll Me Horizontally Scroll Me Horizontally Scroll Me Horizontally Scroll Me Horizontally 
    </div>
</div>

CSS:

.scroll-container {
    width: 80%;
    margin: 0 auto;
    background: cyan;
    overflow-y: hidden;
    height: 36px;
}

.scroll-content {
    padding: 10px 0;
    height: 50px;
    white-space: nowrap;
    overflow-x: scroll;
    overflow-y: hidden;
}

Answer №1

If you need to determine whether an element is overflowing horizontally, you can easily compare its calculated width using jQuery's .width() method with its scrollWidth, which is a JavaScript function:

var $element = $('.scroll-content'),
    isOverflowing = $element[0].scrollWidth > $element.width();

You can then evaluate the boolean value of isOverflowing to see if the element is indeed overflowing. Keep in mind that if you want this variable to update when the window is resized, some additional steps are required:

var $element = $('.scroll-content'),
    isOverflowing = function() {
        if($element[0].scrollWidth > $element.width()) {
            return true;
        } else {
            return false;
        }
    };

console.log(isOverflowing());

$(window).resize(function() {
    console.log(isOverflowing());
});

For a demonstration of this concept implemented with minor adjustments, you can view this fiddle: https://jsfiddle.net/teddyrised/udv8u596/5/

Answer №2

Ilya, it is important to verify the correct position of your element. One way to achieve this is by setting the inner element to have an absolute position and retrieving the right position using jQuery.

parseInt($('.scroll-content').css('right')) >= 0

I have made some modifications to your code: https://jsfiddle.net/udv8u596/4/

In this example, before animating the element, it checks if the right position is greater than 0.

It is important to note that the right position is calculated based on the parent element. While the left position is set to 0 in the CSS, the calculated right position in this example is approximately -250.

I hope this provides you with insight into how to address your issue.

Answer №3

Check out this simple guide to help you get started:

HTML

<div class="scroll-container">
    <div class="mask>
        <div class="scroll-content">
            Keep scrolling horizontally Keep scrolling horizontally Keep scrolling horizontally 
        </div>
    </div>
</div>
<div class="scrollRight">Scroll Right &raquo;</div>
<div class="scrollLeft">&raquo; Scroll Left </div>

CSS

.scroll-container {
    width: 80%;
    margin: 0 auto;
    background: cyan;
    overflow-y: hidden;
    overflow-x: hidden;
    height: 36px;
}
.mask{
    position:relative;
    overflow-x: hidden;
    overflow-y: hidden;
    height: 36px;
    width: 100%;
}
.scroll-content {
    position:absolute;
    padding: 10px 0;
    height: 50px;
    white-space: nowrap;
    overflow-x: visible;
    width:auto;
}
.scrollRight, .scrollLeft{
    font-size:10px;
    display:none;
}

JS

var contentWidth = $(".scroll-content").width();
var containerWidth = $(".scroll-container").width();

if(contentWidth>containerWidth){
    $(".scrollRight").show();
}

$("body").on("click", ".scrollRight", function(){
    var scrollValue = contentWidth-containerWidth;
    $(".scroll-content").animate({"margin-left":"-"+scrollValue+"px"});
    $(".scrollRight").hide();
    $(".scrollLeft").show();
})

$("body").on("click", ".scrollLeft", function(){
    var scrollValue = contentWidth-containerWidth;
    $(".scroll-content").animate({"margin-left":"0px"});
    $(".scrollRight").show();
    $(".scrollLeft").hide();
})

View Updated JSFiddle here

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

Using jQuery, we can replace all `<span>` elements with `<img>` elements and then verify if the images have been successfully loaded

Similar Inquiry: jQuery check if image is loaded I find myself in a scenario where the following HTML structure is utilized: <div class="image"> <img class="" src="content-images/1.jpg"> <span class="slide" rel="content-images/ ...

Exploring the functionalities of scss and minified files within Visual Studio 2017

I have very little knowledge of scss. In our Visual Studio 2017 solution explorer, there is a .scss file called Theme6.scss. When I expand it, I see a file named Theme6.css. Upon expanding that file, two more files are revealed: Theme6.css.map and Theme6. ...

After updating next.config, the NextJS + NextAuth middleware doesn't seem to be triggered

I'm currently utilizing <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b0ded5c8c49dd1c5c4d8f0849e81889e87">[email protected]</a> & <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemai ...

Tips for properly formatting the sort_by parameter in Cloudinary to avoid errors

Greetings to the helpful stack overflow community, I have encountered an issue with fetching images from cloudinary via a post request. Everything works fine until I include the sort_by parameter in the URL. This results in an error related to the format ...

Passing form data to a different route using express

I need to send the data from this form, located on the index.ejs page, to another page "/rentingForm" for rendering at the "rentingForm" page. Here is the snippet of code from my app.js file: app.use(bodyParser.urlencoded({ extended: true })); app.use( bo ...

Mastering the art of utilizing generic types efficiently within Higher Order Component structures

My parent component (Grid) passes props to a higher-order component (hoc), let me show you: <QuickBooksTable itemList={quickBooksList} /> Here is the QuickBooksTable component: export const QuickBooksTable = withIntegrationTable(props: : WithIntegra ...

Exposing external variables within the setInterval function

Here is the snippet of code I am working with: update: function(e,d) { var element = $(this); var data = element.data(); var actor = element.find('.actor'); var value = basicdesign.defaultUpdate( e, d, element, true ); var on = templateEn ...

What is the best way to add a new row in Material-UI?

I have been working on a contacts application that stores all data temporarily on the client-side. I decided to use material-ui table to showcase the contacts in a visually appealing way. https://i.sstatic.net/8K6cy.png Upon clicking the "Add New Contact ...

JavaScript function using recursion returning an undefined value

I have created a function that generates a random number and checks if it already exists in an array. If it does, the function generates a new number until a unique one is found and adds it to the array. However, I am encountering an issue where the functi ...

Maximized - Immersive Full Screen Background - Limited to Half the Size?

Looking to incorporate the Supersized Fullscreen background found at Supersized Interested in having the slider appear on the right half of the site with content on the left half. Want the content to move when scrolled while keeping the background station ...

Prompting a 401 error immediately after attempting to login through the Express REST API

Recently, I've encountered a strange issue with the controller for my login route. It was working perfectly fine yesterday without any hiccups, but suddenly it stopped functioning properly. Despite not making any changes to the code, it now consistent ...

Retrieve base64 encoded data from several content attributes

Is there a way to optimize the use of base64 data in CSS by defining it once and referencing it in multiple content properties? div#my_id1 { content: url(data:image/png;base64,...); } div#my_id2 { content: url(data:image/png;base64,...); } Using ...

Tips for capturing the text change event of a textbox within a jQuery datatable

I am currently working on a jQuery datatable that includes a textbox for the quantity field. My goal is to have the total amount calculated automatically when a value is entered into the quantity textbox. Below is the code snippet of what I have attempted ...

Achieve consistent column heights with flexbox styling

I have a solution for achieving equal height columns using the CSS property display:table. Here is an example: .row { display: table; width: 100%; } .col{ display: table-cell; } However, in my case, I am using flexbox and the row class has ...

Is it possible to make a distinctive choice from the dropdown menu?

I need help with my html page that has 10 dropdowns, each with options 1 to 10. How can I assign options uniquely to each dropdown? For example, if I select option 1 in dropdown 1, that option should be removed from the other dropdowns. If I deselect an ...

Modifying the values of Highcharts-Vue chart options does not result in any changes once they have been

I recently started incorporating Highcharts into my Vue project using the highcharts-vue library. A) Initially, in pure JavaScript, the following code snippet functions as expected: let b = 5; let data = { a: b } console.log('data', data.a) ...

When the enter key is pressed, the form will be submitted and the results will be displayed in a modal window without

Behold, my unique form! It lacks the traditional <form></form> tags. <input id="query" name="query" style="font-size: 18pt" id="text" data-email="required" type="text" placeholder="Search Here from <?php echo $row['no']."+"; ?& ...

The concept of JavaScript context within unidentified functions

I am trying to assign a function as a property of each element in an array and then call it with different arguments. My initial approach was to use an anonymous function like this: for ( var i = 0; i < object_count; i++ ) { objects[i].callback = f ...

Positioning elements on the web page using CSS tiles

Greetings! I am currently working on a website that utilizes tiles similar to this: https://i.sstatic.net/OzKQv.png Everything seems to be in place, except for one tile that is not aligning with the rest. I am struggling to figure out how to position it c ...

Learn how to implement form validation on a sliding form in just 5 easy steps using jQuery

I am new to programming and I struggle to comprehend complex JavaScript code written by others. Instead of using intricate code that I don't understand, I would like to request help in creating a simplified jQuery script for me to implement. Current ...