I want to capture the value of src
and pass it to a CSS variable, which is in the inline style of the container parent named --img-url
.
The idea that I have in the html, I have this:
<figure class="img-container" style="--img-url: ;">
<img class="imagen" src="imagen.jpg"/>
</figure>
In the CSS:
.img-container .imagen{ display: none; }
.img-container { background-image: var(--img-url); }
And in jQuery:
$(document).ready(function(){
var asignarCssvar = function(selector, variable, valor) {
$(selector).css(variable,valor);
}
var capturaAtributo = function(selector, atributo) {
var valorAtributo = $(selector).attr(atributo);
var urlBkg = "url('"+valorAtributo+"')";
asignarCssvar(".img-container","--img-url",urlBkg);
}
capturaAtributo(".img-container .imagen", "src");
});
Functional example:
$(document).ready(function(){
var asignarCssvar = function(selector, variable, valor) {
$(selector).css(variable,valor);
}
var capturaAtributo = function(selector, atributo) {
var valorAtributo = $(selector).attr(atributo);
var urlBkg = "url('"+valorAtributo+"')";
asignarCssvar(".img-container","--img-url",urlBkg);
}
capturaAtributo(".img-container .imagen", "src");
});
.img-container {
background-image: var(--img-url);
background-size: cover;
background-position: center;
background-color: #dddfff;
padding: 1em;
width: 100px;
height: 100px;
}
.img-container .imagen {
width: 100%;
height: auto;
transform: translateX(200%);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<figure class="img-container" style="--img-url: ;">
<img class="imagen" src="https://picsum.photos/900/300"/>
</figure>
But as you can see, I have 2 problems:
Update
I think many do not know about the variables, which are officially known as the Custom Properties of css: Using CSS Variables | MDN documentation and I do know that they are not yet fully implemented, although they have good support according to caniuse that's why mention that I'm doing experiments:)
I have been able to use the same code in codepen and it works, why will it be? Link to watch demo in Codepen
Update 2
Yes, apparently if it works, only with the latest version of jQuery 3.2.1 and there is no official answer as to why. Thanks @ AlvaroMontoro for responding. I already update my code and it works like magic!
On whether it can be done without JavaScript (only with CSS styles)
As for if I wanted to do it only via CSS, it was not my intention in the question, but how well that by accident also gave me reason why it could not. However, because stubbornness is foolish, maybe this answer is "possible" in the future, since I remembered this article that I read but did not understand until now: Article in this super blog of css that we are going to have some" css functions "or similar, or that we already have one as calc()
well supported and that in the future attr()
and toggle
maybe.