0

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

blahblah
  • 1,010
  • 15
  • 40

3 Answers3

3

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');
}
Stanley
  • 3,935
  • 2
  • 18
  • 22
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.

Community
  • 1
  • 1
secelite
  • 1,353
  • 1
  • 11
  • 19
  • @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. – secelite Oct 31 '16 at 15:26
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;
}
Eugene Tsakh
  • 2,777
  • 2
  • 14
  • 27