zazvorniki
zazvorniki

Reputation: 3602

Adding a css ::before to an element using jQuery

I know this sounds silly and you're going to ask why I'm just not using css, I assure you I have a reason. I'm building an app that is configurable to the user and part of that is changing the background color. Changing the background color is no problem however I have one spot where I'm gently fading an image into the background using a css shadow on a ::before.

My css kind of looks like this

-moz-box-shadow:inset 0px 0px 90px 50px rgba(230,235,242,0.98);
-webkit-box-shadow:inset 0px 0px 90px 50px rgba(230,235,242,0.98);
box-shadow:inset 0px 0px 90px 50px rgba(230,235,242,0.98);

And to try and covert it to jQuery I tried something like this

$('.titleImage .shadow::before').css('-webkit-box-shadow', "inset 0px 0px 90px 50px" + Props['BackgroundColor']);

But it doesn't want to work. Any help would be appreciated!

Upvotes: 0

Views: 319

Answers (3)

Ted
Ted

Reputation: 14937

Add an element to the dom, like:

<style id="mySpecialStyles"></style>

And a function like:

function changeColor(newColor){
    $('#mySpecialStyles').text(
        '.titleImage .shadow::before{' + 
        '-webkit-box-shadow:inset 0px 0px 90px 50px '+ newColor +';' +   
        'box-shadow:inset 0px 0px 90px 50px '+ newColor +';}'
    )    
}

// called like
changeColor('#000000'); 

That keeps it to a single style tag that you alter.

Check out this demo fiddle.

HTH

Upvotes: 0

Samir Das
Samir Das

Reputation: 1918

Pseudo selector can not select using jquery. Work around is using inline css instead like below:

$('.titleImage .shadow').append('<style> .titleImage .shadow::before {-moz-box-shadow:inset 0px 0px 90px 50px rgba(230,235,242,0.98); -webkit-box-shadow:inset 0px 0px 90px 50px rgba(230,235,242,0.98);box-shadow:inset 0px 0px 90px 50px rgba(230,235,242,0.98);}</style>');

You can remove that style as well if needed

Upvotes: 2

Adam Jenkins
Adam Jenkins

Reputation: 55792

jQuery can't target pseudo elements (don't ask for a workaround, there isn't one), but you can toggle a class on an element that adds/removes/modifies pseudo elements.

$('div').on('click',function(){ $(this).toggleClass('pseudo'); });
div:before {
  content:"Hi";
  border: 1px solid #000;
  }

div.pseudo:before { border-width: 3px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  </div>

Upvotes: 2

Related Questions