April 10, 2012
Can not insert css image into pseudo :before
Question by swan
I am trying to insert a background image into a header:before element, but jquery fails.
HTML
content
<a href="image.jpg" class="image-source">Try insert image into .header:before</a>
JS
$('.image-source').click(function() {
var src = $(this).attr('href');
// slash is okay
$('.header:before').css('backgroundImage', 'url(/' + src + ')');
return false;
});
CSS:
.header {
position: relative;
background: url(anotherimage.jpg) no-repeat;
}
.header:before {
position:absolute;
top:0;
left:0;
right:0;
bottom:0;
margin:auto;
min-width:50%;
min-height:50%;
content: "";
}
Does anyone know if I am dealing with a bug here, or missed an obvious?
Note, I can not use .header
itself, because I am working with multiple background image, thats why I need :before
.
UPDATE:
Might be this:
Answer by Starx
You cannot manipulate Pseudo Elements using jQuery. They are not part of DOM. You might want to avoid ugly workaround for this as well.
One of the most ugliest but my best workaround is this
var css = '.image:after { content: url("https://www.google.com/images/srpr/logo3w.png"); width: 400px; height: 100px; }';
$("#replaceable").html(css);
$("div").addClass('image');
$("div").click(function() {
var css = '.image:after { content: url("http://www.google.com/logos/2012/elias_lonnrot-2012-hp.jpg"); width: 400px; height: 100px; }';
$("#replaceable").html(css);
});