Putting data from DOMStringMap into css url

85 views Asked by At

Attempting to make a generalized css modification for a webpage element that looks like

<button data-action="link" class="cardImageContainer coveredImage cardContent itemAction lazy lazy-image-fadein-fast" data-blurhash="long string that IDK if is identifying or not" aria-label="sample_video" style="background-image: url("http://localhost:8096/Items/7215c9b47ed950ddeb42219e4b4091a1/Images/Primary?);"></button>

The Program allows for css customization, and the following works so long as I manually type in that long string(dataset:id) in the url part.

.card:hover .cardImageContainer,
.card.show-animation:focus .cardImageContainer {
    background-image: url("/Items/   that long id  /Images/Logo?") !important;

the long id is viewable via inspect element under dataset: DOMStringMap id:
Is there a way to pull that into the url for the hover background image url.
full disclosure my knowledge of css + (im assuming its js) is limited

.card:hover .cardImageContainer,
.card.show-animation:focus .cardImageContainer {
    background-image: url("/Items/dataset:id/Images/Logo?") !important;
1

There are 1 answers

0
Liam On

CSS cannot concatenate the pieces of the url that you need to pass to url(), so this is not possible in CSS alone. (More info)

Try this JavaScript:

let blurhash = document.querySelector('.cardImageContainer').dataset.blurhash;
let e = document.querySelector('.cardImageContainer');
e.style.background = 'url("/Items/' + blurhash + '/Images/Logo?") no-repeat scroll 0 0 transparent';
console.log(e.style.backgroundImage);

This example shows how to get the data-blurhash attribute from the html, and how to combine it with other data to set the background image.

You may have to modify it more depending on how complex your page is to narrow the selectors and to handle more than one of these per page.