1

I'm trying to change the background color of my :before element with a php variable. The variable neatly returns a hex code like #123456. I tried this piece of jQuery/javascript to get this working, but it isn't. Does anyone know what I'm doing wrong?

<script>
    $(document).ready(function(){
        $('#tpl-contact:before').css("background", "<?=$sColor;?>");
    });
</script>
Frank Kluytmans
  • 533
  • 2
  • 10
  • 25
  • Can you show us HTML code too where you want to apply background color / – Devang Rathod May 02 '13 at 11:08
  • You can't. `:before` and `:after` are pseudo elements and don't exist in the DOM. – ahren May 02 '13 at 11:11
  • @ahren: jQuery is not the DOM and it might have super-powers. So you never know. ;) (at least OP could have a plugin that offers this as you know we can extend the selectors) – hakre May 02 '13 at 11:12
  • @hakre *jQuery is not the DOM* ... Thanks for the tip `;-)` – ahren May 02 '13 at 11:14
  • But what you wrote about :before and :after is totally right, not part of the DOM. No need to delete your answer, just wanted to upvote it. Also class is a better fallback than attr. Just thinking about the jquery way to do this... . – hakre May 02 '13 at 11:14
  • @hakre - nah I deleted my answer because it didn't let the OP change the color based on a PHP variable... Therefore it didn't help. – ahren May 02 '13 at 11:15
  • 1
    possible duplicate of [Manipulating CSS pseudo-elements using jQuery (e.g. :before and :after)](http://stackoverflow.com/questions/5041494/manipulating-css-pseudo-elements-using-jquery-e-g-before-and-after) – ahren May 02 '13 at 11:17

1 Answers1

2

Try not using jQuery for that. HTML and CSS should suffice.

Another way to quickly find out how it works is to do this step by step, e.g. does:

$('#tpl-contact:before').css("background", "#123456");

already does what you want to do? If yes, continue, if not, you have excluded PHP as the culprit. I normally do it that way.

The question"How do I access style properties of pseudo-elements with jQuery?" might have some additional pointers as well.

Community
  • 1
  • 1
hakre
  • 193,403
  • 52
  • 435
  • 836