My goal is to use the :before pseudo-element to set an image background, as I plan to overlay content on top of it.
In the past, I have dynamically set a data attribute with :before for other purposes.
Question: Is there a way to change the number using :before
, similar to how I'm attempting to do so with an image?
Here is my current approach:
<li data-image="https://via.placeholder.com/150/0000FF">hello 1</li>
background: url(attr(data-image));
Below is the full code snippet:
setInterval(function(){
var randomImages = ['https://via.placeholder.com/150/0000FF','https://via.placeholder.com/150/FF0000','https://via.placeholder.com/150/FFFF00'];
var imagIndex = Math.floor(Math.random() * 3);
$('li:eq('+imagIndex+')').attr('data-image',randomImages[imagIndex]);
// console.log(randomImages[imagIndex]);
$('#displayingWithBefore').attr('data-number',imagIndex);
},200);
ul{
list-style: none;
line-height: 43px;
}
li{position: relative;}
li:before{
content: "";
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 40px;
background: url(attr(data-image));
}
#displayingWithBefore{
position: relative;
width: 90px;
height: 90px;
background:red;
color: #fff;
}
#displayingWithBefore:before {
content: attr(data-number);
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
font-size: 30px;
text-align: center;
line-height: 92px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
<div id="displayingWithBefore"></div>
<ul>
<li>hello 1</li>
<li>hello 2</li>
<li>hello 3</li>
</ul>
</div>
I'm looking forward to receiving helpful answers.
Any assistance would be greatly appreciated - thank you in advance!