I have elements that are generated dynamically on the screen. I have bars and diamonds.
The problem is I have hundreds of different types of bars or diamonds that need to be rendered on the screen. The bars and diamonds are tasks and milestones on a gantt chart. There are hundreds of different types and each type has to have a certain image attached to it for the background so they can be identified a little more easily.
Instead of writing a huge css
file with background-image
style I thought it would be better to dynamically generate a css
class with the background-image: url("~/relativepath/imageName")
style.
Each one of these different types of elements have their own image file associated with them. Every element also has a Code
property such as EX0blue
. I was thinking of changing the image file names to match the code property, so when the css is generated I can give it a class name of the code and a relative path such as background-image: url("~/relativepath/code.jpg")
Is there a more optimal solution than what I am trying to implement?
Here is what I have so far
class CssGenerator {
constructor() {
this.relativeImagePath = '~/Content/images/activityTypes/';
}
createImageClass(code) {
let style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = '.' + code +' { background-image: url(' + relativeImagePath + code + '.jpg); }';
document.getElementsByTagName('head')[0].appendChild(style);
}
}
Then after that I would add the class like this
gantt.templates.task_class=function(start, end, task){
this.cssGenerator.createImageClass(task.code)
return task.code;
};
That return statement applies the string returned as a classname to the dynamic element. It's from the API
style
property on each element rather than creating a separate stylesheet for each one. \$\endgroup\$