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
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 .
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');
}
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.