Hero Image using “base64string” and dynamically created css class as div background-image

I want to create multiple dynamically generated hero images from multiple base64string using “plain” JavaScript. I don´t want to use jquery or any library.

How I load the images from a database or from disk as a base64string is no problem. I have already found out that a hero image only works with the property background-image: url(“heroimage.png”); and a DIV element. The properties I need to set in the CSS class to make it a HeroImage are also unproblematic.

Example Hero Image: https://www.w3schools.com/howto/howto_css_hero_image.asp

My questions are:

1.) How do I create multiple “dynamically” generated CSS classes for multiple hero images (i.e. 1 CSS class for 1 hero image)? 2.) How do I assign the Base64String to the CSS class / property “background-image”? 3.) Is this the best solution to create a gallery of hero images dynamically?

Additional info: Why Hero Image? Answer: I always want to display an image in very specific ratios / proportions. I.e. a certain area (e.g. 80px x 60px) should always be filled with an image and centered vertically as well as horizontally.

Answer

Answering your first question: it would be possible to assign all hero images one single CSS class (not one class for every hero) without specifying the background image inside of the class. Then loop over every hero image in JavaScript and assign them the CSS background-image property using the data URL. An Example:

var dataURLs= [YOUR DATA URLs];
var heros = document.querySelectorAll("hero-image");
var count = 0;
for (i of heros) {
  i.style.backgroundImage = "url('"+ dataURLs[count] +"')";
  count++;
}

This code iterates over every hero in your page, sets the background image to the corresponding dataURL and increments the counter to sync both urls and heros. IMPORTANT: the list needs to have the EXACT same amount of dataURLs like you have hero classes in your page.

You need to format your base64 strings like following to dataURLs:

data:image/[YOUR MIME TYPE];base64,[YOUR BASE64 STRING]