Discovering every item with a scrollbar

What is the most efficient method to identify all elements with a scroll on a webpage?


My current strategy involves utilizing element.all() in conjunction with filter() to compare the values of the height and scrollHeight attributes:

element.all(by.xpath("//*")).filter(function (elm) {
    return protractor.promise.all([
        elm.getAttribute("height"),
        elm.getAttribute("scrollHeight")
    ]).then(function (heights) { 
        return heights[1] > heights[0];
    });
});

However, I am uncertain about the accuracy and efficiency of this approach.

Answer №1

This method is effective for detecting both horizontal and vertical scrollbars. It relies on determining if the content is too wide or too short, as well as checking if the computed CSS properties allow the display of a scrollbar.

var ScrollableElements = (function() {
    var getStyle = document.body && document.body.currentStyle ? function(element) {
        return element.currentStyle;
    } : function(element) {
        return document.defaultView.getComputedStyle(element, null);
    };

    function getComputedCssProperty(element, property) {
        return getStyle(element)[property];
    }

    function isHorizontalScrollable(element) {
        return element.offsetWidth < element.scrollWidth && 
            hasScrollBar(getComputedCssProperty(element, 'overflow-x'));
    }

    function isVerticalScrollable(element) {
        return element.offsetHeight < element.scrollHeight && 
            hasScrollBar(getComputedCssProperty(element, 'overflow-y'));
    }

    function hasScrollBar(text) {
        return text === 'scroll' || text === 'auto';
    }

    function containsScrollBar(element) {
        return isVerticalScrollable(element) || isHorizontalScrollable(element);
    }

    return function ElementsWithScrollBars() {
        return [].filter.call(document.querySelectorAll('*'), containsScrollBar);
    };
})();

ScrollableElements();

Answer №2

This code snippet targets elements within the body tag that have overflowed and non-overflowed scrolls:

$('body *').filter(function() {
     return ($(this).scrollTop() != 0 || $(this).css('overflow') == 'scroll');
});

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

Adapting language in real-time: DateTimePicker jQuery Plugin

I am looking to dynamically adjust the language settings of the DateTimePicker jQuery Plug-in (http://xdsoft.net/jqplugins/datetimepicker/) but I keep encountering an "undefined" error for the lang1 variable within the final plug-in function call: <!DO ...

Tips for saving JSON information into a variable using JavaScript

I am in need of a function called ** getJson () ** that can fetch and return data from a json file. Here is the JSON data (file.json): [ { "01/01/2021":"Confraternização Universal", "1 ...

``Why is it that the JavaScript code is unable to find the maximum or minimum sum? Let's

function calculateMinMaxSums(arr) { // Custom code implementation let max = Math.max(...arr); let min = Math.min(...arr); let minsum = 0; let maxsum = 0; for (let x in arr) { if (arr[x] != max) { minsum += arr[x]; }; if (arr[x ...

Angular appears to be experiencing technical difficulties

Exploring Angular as a beginner, I am working with a local REST API (Express app) and Angular code in the public folder. Currently, everything is functioning smoothly - I can add, update, and delete items in a locally running Mongo db. Check out the code h ...

The tab does not appear after it is added

Currently, I am developing a dashboard using ReactJS with Redux. One of the key features is the ability to create tabs. When a tab is created and saved through a POST request to the API for database storage, it should also be displayed in the header immedi ...

Locating a text element #text using Selenium in Python

In the HTML code provided below, I am trying to extract specific information: <div class="detailSection"> <span>Authorized Person(s) Detail</span> <span> <b>Name &amp; ...

Why is $(window).load() being executed twice?

When using $(window).load() to resize images in a thumbnail gallery and set up a slideshow, the code seems to be running twice. This can be observed by noticing that a div is being wrapped around another div twice when inspecting the HTML on page load. Af ...

Implementing mandatory object keys in TypeScript

Suppose you have these type definitions: type Panel = 'store' | 'logs' You aim to construct an object containing key => ReactChild pairs, where the keys are restricted to the values in Panel. const components = { store: StoreC ...

Using the model's value as the name for another model in AngularJS

var app = angular.module('LoginApp',[]); app.controller('dynamicController', ['$scope', function($scope) { $scope.role= "Admin"; $scope.auctionNumber = 1; $scope.itemsArray = [{ letter:"a" , number:1 }]; }]); To d ...

What are some ways to find your way without using the Navigator app?

Navigator.js const App = createStackNavigator({ screenA: { screen: ScreenA }, screenB: { screen: ScreenB } }) const Navigator = createAppContainer(App); export default Navigator; App.js return ( <SafeAreaView> <Provider store={ ...

Discovering the method to retrieve the logged-in user's text with Xpath

Upon logging in, a personalized message greets the user with their name. https://i.sstatic.net/Vorac.gif I am attempting to write an xpath expression to locate and capture that user. Here are a few strategies I have attempted: //span[@id='WhoLogged ...

Retrieving the _id of a new document in MongoDB using Node.js

I am facing a challenge understanding MongoDB after transitioning from using relational databases. Currently, I am attempting to store an image with the following code: exports.save = function ( input, image, callback) { console.log('Image P ...

When retrieving HTML from the server, the scope values are not appearing as expected

UPDATE: After extensive testing of my code, I have gained a better understanding of what is not functioning correctly, prompting me to revise my previous inquiry. When browsing to the / directory in my local environment, my HTML file loads successfully. ...

Organize information within a single column of a table according to the heading using Angular

I have been working on implementing a sorting operation in a table for one or multiple columns. Consider the following table: https://i.sstatic.net/F4BJ6.png When clicking on Heading 1, only Data 1 and Data 2 should be sorted. When clicking on Heading 2, ...

The Issue of Horizontal Scrolling - None of the elements are out of

I am facing an issue with an unwanted horizontal scroll on my website and I can't seem to identify the cause. The header of my site is quite simple, utilizing display: flex, justify-content: center, marin-top: 5vh, along with some padding on the logo ...

The addClass() and removeClass() functions in Jquery are not functioning correctly

$('.push').each(function(){ if($(':first-child',this).hasClass( "activex" )){ $(this).off().off('click').on('click',function(){ var a = $(this).attr('id'); $.ajax({ type: "POST", ...

Changing a button's value on click using PhoneGap

I've been working with phonegap and came across an issue with my buttons setup like this: <input id="my_button" type="button" onclick="my_function();"/> The goal is to capture the click event and change the button's value, my_function ( ...

What are the potential risks associated with including your backend server port number in your code?

Working on a project using React and Node.js here. My server is set up with Express and the dotenv package to keep my server configurations secure, like the PORT number where my backend server operates. For instance, my server's environment variable i ...

The route on Heroku is functional when tested locally, but encounters issues when deployed in production

I have recently deployed a node project to a Heroku app successfully. However, I am encountering a "Cannot GET" error (404) on one specific route while other routes on the same page are functioning as expected. This issue only occurs when accessing the rou ...

Deactivate the submit button using jQuery when there are validation errors present in the form inputs

I am looking for a way to use jQuery to disable the submit button if there are any validation errors in the form inputs. Below is the code snippet I have been working on: HTML: <form action="/order" id="orderForm" class="orderform" autocomplete="off" m ...