Conceal pseudo-elements using JavaScript

How can I control the visibility of the :before and :after pseudo elements using JavaScript?

I currently have arrows displayed on both sides of a div. Here is the CSS styling for the arrows:

 .edit-wrap:before,
 .edit-wrap:after {
     @media (max-width: 768px) {
         content: '';
         ....
     }
 }

I would like to hide these arrows if there is no scroll bar present in the element, and show them otherwise.

var scrollableElement = document.getElementById('scrollable-element');
if(scrollableElement.scrollWidth > scrollableElement.clientWidth){
               //display arrows
            } else{
               //hide arrows
            }

Note: I am not utilizing JQuery for this functionality.

Answer №1

In my opinion, utilizing both CSS and JavaScript is necessary in this scenario.

CSS

.hide-before:before, .hide-after:after { display:none; }

JavaScript

var scrollElement = document.getElementById('scrollable-element');

if (scrollElement.scrollWidth>scrollElement.clientWidth) {
   scrollElement.classList.add('hide-after','hide-before');
} else {
   scrollElement.classList.remove('hide-after','hide-before');
}

Answer №2

To eliminate the class that utilizes the pseudo classes :before and :after, you can use JavaScript to manipulate the className property (assuming there are no other classes for the target element).

var scrollableElement = document.getElementById('scrollable-element');
if (scrollableElement.scrollWidth > scrollableElement.clientWidth) {
    document.getElementById('yourElementId').className = 'edit-wrap';
} else {
    document.getElementById('yourElementId').className = '';
}

If you need to specifically remove a class, consider using the classList property, which is widely supported by modern browsers (check compatibility here).

var scrollableElement = document.getElementById('scrollable-element');
if (scrollableElement.scrollWidth > scrollableElement.clientWidth) {
    document.getElementById('yourElementId').classList.add('edit-wrap');
} else {
    document.getElementById('yourElementId').classList.remove('edit-wrap');
}

For older browser support, you may resort to using regular expressions.

Answer №3

To demonstrate, include the .hide-pseudo class on the element and adjust your styles as follows:

.edit-wrap.hide-pseudo:before,
.edit-wrap.hide-pseudo:after {
    display: none;
}

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

What is the best way to keep track of dynamically inserted input fields?

I've created a form with two text boxes: one for entering people's "name" and another for their "surname." By clicking on the page, you can add additional pairs of text boxes for both "name" and "surname," allowing users to input as many pairs as ...

Angular Nested Interface is a concept that involves defining an

Looking for guidance on creating a nested interface for JSON data like this: Any help is appreciated. JSON Structure "toto": { "toto1": [], "toto2": [], "toto3": [], } Interface Definition export interface Itot ...

Errors occur when Axios fails to send the correct response [React]

I've been encountering an issue while handling error responses from Axios in React. When I attempt to log the error, it shows as Network error and error.response is undefined. The request involves a simple POST with the Authorization header correctly ...

Leveraging Google Cloud Functions with Next.js (Client-Side Rendering)

Having trouble incorporating firebase cloud functions into my Next.js project, encountering an unfamiliar error. firebase-config.js const firebaseConfig = { apiKey: '~~~', authDomain: '~~', projectId: '~~~', storageBu ...

reconstructing the JSON array

// Here is an initial JSON object to work with var originalJson = { "rows": [{ "ID": 123, "Data": 430910, "VersionNum": 0, "RowSeqNum": 1, "IterationNum": 1, "FirstName": "Aqwemara", "LastName": "Seweqweebi", "Location": " ...

When I attempt to open a file with a double click in my Electron app, Argv[1] gives me an unexpected value

When attempting to open a file by double-clicking, I encounter an issue while using electron-packager to build the application for the Mac App Store. Although I have set up the electron app to launch when a file is double-clicked, it appears that the file ...

When attempting to import an async function from a separate JavaScript file in NodeJS, it may not be properly

I have a dilemma with two files in my project: getPopular.js and getPlayListByBPM.js. The issue arises when I try to import a function from getPopular.js into getPlayListByBPM.js. Within getPopular.js, I have defined two asynchronous functions: var getPop ...

Stop the background from scrolling and prevent auto-jumping to the top on mobile devices

When users click on the hamburger icon in the top right of our mobile site, I want the drop-down menu to appear and be scrollable without the background scrolling. I tried using JavaScript to set the body to fixed when the menu icon is clicked, but this ca ...

Adding a Click class can cause significant disruption to the entire CSS layout

I am facing an issue with transforming the X position and appending an additional class to create a slide effect in React. It seems to be working differently compared to using vanilla JavaScript. Below is the code snippet: .inputModal { position: absolut ...

Tips for breaking out of an infinite loop while loading HTML containing a carousel into a blank <div> within another HTML file using jQuery's $(document).ready() function

Currently, I am studying HTML, CSS, Bootstrap 4, jQuery3, and JavaScript (ES6+), and to enhance my skills, I have devised an exercise for practice and consolidation. I have created 4 HTML files, all featuring responsive design based on Bootstrap 4: inde ...

JavaScript array with more than 4 elements

I am working on a program where I have created an array and now want to display all the words that contain more than 4 letters. Check out my code snippet below: function oppC(){ var ord = ["Apple", "Two", "Yesterday", "mother", "lol", "car", "co ...

Having trouble with your jQuery AJAX function not receiving the text returned from your PHP file?

After extensive searching, I have come across several individuals facing the same issue as me, but unfortunately, none of them seem to have found a solution. The problem at hand is that PHP is not providing any data to the AJAX function. When I try to dis ...

Prevent automatic image blurring within an SVGZ file

Utilizing SVGZ images on my HTML pages for their ability to be resized. These SVGZ images consist of enlarged PNGs that have been altered in specific ways that I desire to maintain, pixelation and all. Firefox is rendering them correctly (as designed in In ...

Exploring the Differences: innerHTML versus appendChild for Loading Scripts

Struggling to dynamically load scripts onto the DOM? function addScript(fileName) { document.body.innerHTML += `<script src='components/${fileName}/${fileName}.js'></script>` } addScript('message-interface') I prefer th ...

The controller persists in its loop as it utilizes $state.go

As a newcomer to Angular, I am uncertain if this is the most effective solution. Within my state/route, there is a button that triggers the following function when clicked: _this.foo = function () { save(); $state.go("next"); } The issue arises w ...

Tips for incorporating Angular2 into Eclipse using TypeScript

Recently, I delved into the world of Angular 2 and noticed that TypeScript is highly recommended over JavaScript. Intrigued by this recommendation, I decided to make the switch as well. I came across a helpful guide for setting up everything in Eclipse - f ...

"Nested list elements - The art of stylishly organizing content

Is there a way to apply a gray background color to alternate items in a list, even if they are nested, without affecting the styling of consecutive elements in the nested list? If anyone has any suggestions on how to achieve this using CSS or jQuery, plea ...

Generate unique Prometheus gauge names on the fly

Incorporating prom-client into my node application allows me to send statistics to our prometheus platform. To check the availability of different applications, I am initiating a series of requests. In this process, I aim to customize the name of the gauge ...

What type does a React stateless functional component Flow return?

If I have a structure like this const RandomComponent = (props) => ( <div> <SomeSubComponent id={props.id} /> <AnotherSubComponent type={props.type} /> </div> ) How do I specify the return type using Flow, i.e., wha ...

Creating a Bootstrap header to counteract a collapsible sidebar

Utilizing bootstrap 4, I have successfully implemented a partially collapsible sidebar that is functioning as intended. However, my current challenge lies in incorporating a top header/nav bar that includes the toggle for collapsing the sidebar, and on th ...