1

How to show/hide class :before and :after pseudo elements with JavaScript?

I have arrows on both sides of div. Below is arrows style

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

I want to hide them, if, for example, there is no scroll bar in the element. And show otherwise

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

I am not using JQuery

1
  • by toggling edit-wrap class? Commented Oct 31, 2016 at 14:40

3 Answers 3

4

I think you need to use CSS and JavaScript here.

CSS

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

JavaScript

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

if (scrollableElement.scrollWidth>scrollableElement.clientWidth) {
   scrollableElement.classList.add('hide-after','hide-before');
} else {
   scrollableElement.classList.remove('hide-after','hide-before');
}
Sign up to request clarification or add additional context in comments.

Comments

2

You may remove the class which makes use of the pseudo classes :before and :after. With javascript you can achieve this by using the className property (assuming there are no other classes for the target).

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

If you want to remove the specific class, you should have a look to classList, which is supported by most modern browsers.

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');
}

Another approach for older browsers would be using regular expressions.

1 Comment

@cale_b +1 for the suggested improvement. I added an example which is using classList and linked an already answered question on SO which uses regular expressions to solve the problem.
0

Add, for example, .hide-pseudo class to element and edit your styles like this:

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

1 Comment

how do you add the class?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.