0

I have a CSS say

div.borderYtoX a:before,
div.borderYtoX a:after {
  position: absolute;
  opacity: 0.5;
  height: 100%;
  width: 2px;
  content: '';
  background: #FFF;
  transition: all 0.3s;
}

I want to change the background here to some different color when I scroll down. Its affecting the navigation menus on scroll. Below is the jQuery code and also what I tried but its not working. Is there a possible way to do it here?

$(document).ready(function(){
   var scroll_start = 0;
   var startchange = $('#startchange');
   var offset = startchange.offset();
   $(document).scroll(function() {
      scroll_start = $(this).scrollTop();
      if(scroll_start > offset.top) {
          $('.header').css('background-color', 'rgb(255,255,255)');
          $('div.container a').css('color', '#063193');
          $('.borderYtoX a:before, .borderYtoX a:after').css('background', '#063193');
       } else {
          $('.header').css('background-color', 'rgba(255,255,255,0.3)');
          $('div.container a').css('color', '#fff');
          $('div.borderYtoX a:before, div.borderYtoX a:after').css('background', '#fff');
       }
   });
});
  • Create a code snippet, it will help understand the problem and give a perfect solution – Ajay Narain Mathur Feb 17 '17 at 11:24
  • No you can not target `pseudo`. You can't manipulate `:after` or `:before`, because it's not technically part of the `DOM` and therefore is inaccessible by any `JavaScript` or `jQuery`. But you can add a new class with a new `:after` or `:before` specified. Refer this [**SOAnswer**](http://stackoverflow.com/a/17789110/4763084) – vivekkupadhyay Feb 17 '17 at 11:26
  • Possible duplicate of [Access the css ":after" selector with jQuery](http://stackoverflow.com/questions/17788990/access-the-css-after-selector-with-jquery) – vivekkupadhyay Feb 17 '17 at 11:27

1 Answers1

1

You can't access pseudo elements with javascript as they don't actually exist in the DOM. If you want to manipulate them use Jquery to apply an override class to the element and add a css override for that new class

CSS

div.borderYtoX a.active:before,
div.borderYtoX a.active:after {

  background: #063193;
}

Script

$(document).ready(function(){
   var scroll_start = 0;
   var startchange = $('#startchange');
   var offset = startchange.offset();
   $(document).scroll(function() {
      scroll_start = $(this).scrollTop();
      if(scroll_start > offset.top) {
          $('.header').css('background-color', 'rgb(255,255,255)');
          $('div.container a').css('color', '#063193');
          $('.borderYtoX a, .borderYtoX a').toggleClass('active');
       } else {
          $('.header').css('background-color', 'rgba(255,255,255,0.3)');
          $('div.container a').css('color', '#fff');
          $('div.borderYtoX a:before, div.borderYtoX a:after').css('background', '#fff');
       }
   });
});
NeilWkz
  • 245
  • 1
  • 8