passing bgcolor value as parameter to TD in javascript

Viewed 26

I am using the following javascript code to populate a table , how can I pass the bgcolor value as parameter to TD ?

                let template = `
                    <tr>
                       <td bgcolor="#00FF00">${"pump"+child.val().PumpID}</td>
                       <td bgcolor="#00FF00">${child.val().StartTime}</td>
                       <td bgcolor="#00FF00">${child.val().Duration}</td>
                       <td bgcolor="#00FF00">${child.val().GalsPumped}</td>
                       <td bgcolor="#00FF00">${child.val().Cycle}</td>
                       <td bgcolor="#00FF00">${child.val().Status}</td>
                    </tr>`;
                    table.innerHTML += template;
                 })
                });

basically I want to do this :

var  color_variable = #ff00;
.
.
<td bgcolor=color_variable>${child.val().Status}</td>
1 Answers

Looks like you want to modify bgColor dynamically by altering the color_variable. If you're not using a framework like (vue, react, angular) and If this is the behavior you want you might want to do something like that:

let themeOptions = {
    color_variable: 'green'
}

function rerender() {
    let template = `
        <tr>
            <td bgcolor="${themeOptions.color_variable}">${"pump" + child.val().PumpID}</td>
            <td bgcolor="${themeOptions.color_variable}">${child.val().StartTime}</td>
            <td bgcolor="${themeOptions.color_variable}">${child.val().Duration}</td>
            <td bgcolor="${themeOptions.color_variable}">${child.val().GalsPumped}</td>
            <td bgcolor="${themeOptions.color_variable}">${child.val().Cycle}</td>
            <td bgcolor="${themeOptions.color_variable}">${child.val().Status}</td>
        </tr>`;
    table.innerHTML += template;
}

function changeColor(color) {
    themeOptions.color_variable = color;
    rerender();
}

changeColor('blue')

Of course this is not the best code sample, you might want to modify it to suit your needs, but you get the idea. You can always use objects to pass value by reference and modify the value later. But don't forget that you have to rerender the DOM.

Related