div
{
width: 100px;
height: 50px;
background-color: blue;
}
div::after
{
position: inline-block;
content: "Something";
}
<div>
</div>
Hi is it possible to import a JS function into CSS?
Say I have a JS function
funtion mytitle()
{
return "Something";
}
Is it possible to insert this funtion into CSS' content instead of hard coding it like i did in the snippet? I mean something like
div::after
{ content: mytitle();
}
The answer is NO, but there is a work around to achieve this goal. By using attributes to Show ::after content in element.
In below HTML code we are using data-content attribute, where we show are content return value from our jQuery method.
<div data-content=""></div>
In CSS replace content static content: "Something";
value to dynamic attribute value content: attr(data-content);
.
div::after {
content: attr(data-content);
}
Now, just write a simple jQuery method for returning value in data-content
attribute.
function mytitle() {
$('div').attr("data-content", "Something change");
}
mytitle();
All above mentioned changes are already implemented in below code snippet. I hope it'll help you out. Thank You
function mytitle() {
$('div').attr("data-content", "Something change");
}
mytitle();
div {
width: 100px;
height: 50px;
background-color: blue;
}
div::after {
content: attr(data-content);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-content=""></div>
No, you cannot do this. You must use preprocessors to pass variable/functions to styles.