Dashboards & Visualizations

How to change the header color dynamically using JavaScript?

Explorer

Hi, is there a way where i can change the table header color based on the current date?

For example the current date right now is Jan 22, 2018, then the header Jan 22 18 color should be changed to color green.

alt text

My current code can only change the color of the cells under the header "Jan 22 18"

require([
    'underscore',
    'jquery',
    'splunkjs/mvc',
    'splunkjs/mvc/tableview',
    'splunkjs/mvc/searchmanager',
    'splunkjs/mvc/simplexml/ready!'
], 
function(_, $, mvc, TableView) {


    // var cells = [
    //     'Resources'
    // ];
    var date = new Date();
    var nmonth = ["Jan", 
                "Feb", 
                "Mar", 
                "Apr", 
                "May", 
                "Jun", 
                "Jul", 
                "Aug", 
                "Sep", 
                "Oct", 
                "Nov", 
                "Dec"];
    var month = nmonth[date.getMonth()];

    var day = date.getDate().toString();
    var zero = '0';
    var ddate = zero+day;
    var slicedate = ddate.slice(-2);
    var year= date.getFullYear().toString().substr(2,2);
    var currDate= month + " "+ slicedate + " " + year
    console.log(currDate);

    var CustomTooltipRenderer = TableView.BaseCellRenderer.extend({
        canRender: function(cell) {
            // return _(cells).contains(cell.field);
            return true;

        },  
        render: function($td, cell) {
            var dfield = cell.field;


            if(currDate === dfield){
                console.log("success");
                 $td.addClass("setGreen").html();
            }

        }
    });

    mvc.Components.get('custom_styled_table').getVisualization(function(tableView) {

        // Register custom cell renderer
        tableView.table.addCellRenderer(new CustomTooltipRenderer());

        // Force the table to re-render
        tableView.table.render();
    });



});
0 Karma
1 Solution

SplunkTrust
SplunkTrust

@patricianaguit, if the current date was always the last column you could have applied Table Header style using CSS Selector :last-child. However, based on the sample data seems like this is project planner or outlook calendar where data for future date is also present. Even for your scenario, where current date column header can be at any place, you can use jQuery selector to apply CSS style based on selected Column Header in the table. TableView will still be required to ensure that Table Header CSS Style is overridden only after it is loaded.

Following is a run any where example (PS: I have tried to get other CSS Styles close to what you have however, they are not required as your CSS style should still work):

alt text

Following is the code for Simple XML Dashboard:

<dashboard script="table_decorations.js">
  <label>Table Header Custom Color Current Date</label>
  <search>
    <query>|makeresults
| eval _time=strftime(_time,"%b %d %y")</query>
    <done>
      <set token="currentDate">$result._time$</set>
    </done>
  </search>
  <row>
    <panel>
      <title>Current Date: $currentDate$</title>
      <html>
        <style>
          <!-- All Table header columns-->
          #custom_styled_table th{
            background-image: linear-gradient(to bottom, skyblue, skyblue) !important;
            font-weight: bold;
          }
          <!-- All Table header anchors -->
          #custom_styled_table th a{
            font-weight: bold;
            pointer-events: none;
            cursor: default;
            color: black;
          }
          <!-- First column components -->
          #custom_styled_table th:nth-child(1){
            background-image: linear-gradient(to bottom, #000080, #000080) !important;
          }
          #custom_styled_table th:nth-child(1) a{
            color: white !important;
          }
          <!-- Current Date Column Background Green -->
          #custom_styled_table th.tableHeaderGreen{
            background-image:linear-gradient(to bottom, #65a637, #65a637) !important
          }
          <!-- Current Date Column Text Yellow -->
          #custom_styled_table th a.tableHeaderAnchorYellow{
            color: yellow !important;
          }
        </style>
      </html>
      <table id="custom_styled_table">
        <search>
          <query>index=_internal sourcetype=splunkd log_level!=INFO component!="ConfContentsCache"
| bin _time span=1d 
| stats count by _time component
| eval _time=strftime(_time,"%b %d %y")
| chart sum(count) as Total over component by _time useother=f usenull=f limit=31</query>
          <earliest>-7d@h</earliest>
          <latest>now</latest>
          <sampleRatio>1</sampleRatio>
        </search>
        <option name="count">20</option>
        <option name="dataOverlayMode">none</option>
        <option name="drilldown">none</option>
        <option name="percentagesRow">false</option>
        <option name="refresh.display">progressbar</option>
        <option name="rowNumbers">false</option>
        <option name="totalsRow">false</option>
        <option name="wrap">true</option>
      </table>
    </panel>
  </row>
</dashboard>

Following is the code for Simple XML JavaScript Extension:

require([
     "underscore",
     "jquery",
     "splunkjs/mvc",
     "splunkjs/mvc/tableview",
     "splunkjs/mvc/simplexml/ready!"
 ], 
 function(_, $, mvc, tableView) {

    var defaultTokenModel = mvc.Components.get("default");
    var jQuerySelectorString ="";
    // Token $currentDate$ Change Handler
    defaultTokenModel.on("change:currentDate", function(newTokenName, currentDate, options) {
        if (currentDate !== "undefined" && currentDate !=="$result._time$") {
            // Token currentDate is set
            jQuerySelectorString='#custom_styled_table th a:contains("'+currentDate+'")';
        }
    });

    mvc.Components.get("custom_styled_table").getVisualization(function(tableView) {
        tableView.on('rendered', function() {
                    // Remove table sort class as Header Column should be fixed without sorting
            $("#custom_styled_table th").removeClass("sorts");
                    // If jQuerySelector is set then apply the class
            if (jQuerySelectorString != ""){
                $(jQuerySelectorString).addClass("tableHeaderAnchorYellow")
                $(jQuerySelectorString).parents("th").addClass("tableHeaderGreen");
            }
        })
    });
});
____________________________________________
| makeresults | eval message= "Happy Splunking!!!"

View solution in original post

SplunkTrust
SplunkTrust

@patricianaguit, if the current date was always the last column you could have applied Table Header style using CSS Selector :last-child. However, based on the sample data seems like this is project planner or outlook calendar where data for future date is also present. Even for your scenario, where current date column header can be at any place, you can use jQuery selector to apply CSS style based on selected Column Header in the table. TableView will still be required to ensure that Table Header CSS Style is overridden only after it is loaded.

Following is a run any where example (PS: I have tried to get other CSS Styles close to what you have however, they are not required as your CSS style should still work):

alt text

Following is the code for Simple XML Dashboard:

<dashboard script="table_decorations.js">
  <label>Table Header Custom Color Current Date</label>
  <search>
    <query>|makeresults
| eval _time=strftime(_time,"%b %d %y")</query>
    <done>
      <set token="currentDate">$result._time$</set>
    </done>
  </search>
  <row>
    <panel>
      <title>Current Date: $currentDate$</title>
      <html>
        <style>
          <!-- All Table header columns-->
          #custom_styled_table th{
            background-image: linear-gradient(to bottom, skyblue, skyblue) !important;
            font-weight: bold;
          }
          <!-- All Table header anchors -->
          #custom_styled_table th a{
            font-weight: bold;
            pointer-events: none;
            cursor: default;
            color: black;
          }
          <!-- First column components -->
          #custom_styled_table th:nth-child(1){
            background-image: linear-gradient(to bottom, #000080, #000080) !important;
          }
          #custom_styled_table th:nth-child(1) a{
            color: white !important;
          }
          <!-- Current Date Column Background Green -->
          #custom_styled_table th.tableHeaderGreen{
            background-image:linear-gradient(to bottom, #65a637, #65a637) !important
          }
          <!-- Current Date Column Text Yellow -->
          #custom_styled_table th a.tableHeaderAnchorYellow{
            color: yellow !important;
          }
        </style>
      </html>
      <table id="custom_styled_table">
        <search>
          <query>index=_internal sourcetype=splunkd log_level!=INFO component!="ConfContentsCache"
| bin _time span=1d 
| stats count by _time component
| eval _time=strftime(_time,"%b %d %y")
| chart sum(count) as Total over component by _time useother=f usenull=f limit=31</query>
          <earliest>-7d@h</earliest>
          <latest>now</latest>
          <sampleRatio>1</sampleRatio>
        </search>
        <option name="count">20</option>
        <option name="dataOverlayMode">none</option>
        <option name="drilldown">none</option>
        <option name="percentagesRow">false</option>
        <option name="refresh.display">progressbar</option>
        <option name="rowNumbers">false</option>
        <option name="totalsRow">false</option>
        <option name="wrap">true</option>
      </table>
    </panel>
  </row>
</dashboard>

Following is the code for Simple XML JavaScript Extension:

require([
     "underscore",
     "jquery",
     "splunkjs/mvc",
     "splunkjs/mvc/tableview",
     "splunkjs/mvc/simplexml/ready!"
 ], 
 function(_, $, mvc, tableView) {

    var defaultTokenModel = mvc.Components.get("default");
    var jQuerySelectorString ="";
    // Token $currentDate$ Change Handler
    defaultTokenModel.on("change:currentDate", function(newTokenName, currentDate, options) {
        if (currentDate !== "undefined" && currentDate !=="$result._time$") {
            // Token currentDate is set
            jQuerySelectorString='#custom_styled_table th a:contains("'+currentDate+'")';
        }
    });

    mvc.Components.get("custom_styled_table").getVisualization(function(tableView) {
        tableView.on('rendered', function() {
                    // Remove table sort class as Header Column should be fixed without sorting
            $("#custom_styled_table th").removeClass("sorts");
                    // If jQuerySelector is set then apply the class
            if (jQuerySelectorString != ""){
                $(jQuerySelectorString).addClass("tableHeaderAnchorYellow")
                $(jQuerySelectorString).parents("th").addClass("tableHeaderGreen");
            }
        })
    });
});
____________________________________________
| makeresults | eval message= "Happy Splunking!!!"

View solution in original post

Explorer

The code doesnt work well for me. The header would change color to yellow at first, BUT every time the table completely loads up the header will be back to blue again.

Here's my code right now:

require([
    'underscore',
    'jquery',
    'splunkjs/mvc',
    'splunkjs/mvc/tableview',
    'splunkjs/mvc/searchmanager',
    'splunkjs/mvc/simplexml/ready!'
], 
function(_, $, mvc, TableView) {




    var CustomTooltipRenderer = TableView.BaseCellRenderer.extend({
        canRender: function(cell) {
            // return _(cells).contains(cell.field);
            return true;

        },  
        render: function($td, cell) {
            if(cell.value!==null){
                    var message = cell.value.split("#")[0];
                    var tip = cell.value.split("#")[1]; 


                if(cell.field !== 'Resources'){ 
                        if(tip !== undefined && tip !== "N/A"){
                            var rounded=Math.round(message*10)/10;
                            var n = rounded.toString();
                            var l = n.length;
                            if(l == "1"){
                                rounded = rounded+".0";
                            }else{
                                rounded = rounded;
                            }
                            $td.html(_.template('<a href="#" data-toggle="tooltip" style="color:#ffffff"  data-placement="top" title="<%- tip%>"><%- rounded%></a>', {
                                tip:tip,
                                rounded: rounded,
                            }));
                            // console.log(rounded);
                            $td.addClass("setGreen").html();
                            // $td.css({"background-color": "#00A000", "color": "#ffffff"});


                            // This line wires up the Bootstrap tooltip to the cell markup
                            $td.children('[data-toggle="tooltip"]').tooltip();

                        }else{
                            if(message !== "-" && message !== "EH" && message !== "H"){
                                // var rounded = Math.round(message*10)/10;
                                var round =parseFloat(message);

                                                                                                       // var rounded=message;
                               var rounded=round.toFixed(1);
                                // var rounded = rounded+".0";
                                // console.log(rounded);
                            }else{
                                var rounded = message;
                            }
                            $td.html(_.template('<%- rounded%>', {
                                tip:tip,
                                rounded: rounded    
                            }));
                        }
                }else{
                    $td.html(_.template('<%- message%>', {
                        tip:tip,
                        message: message    
                    }));
                }

            }

        }
    });

          var defaultTokenModel = mvc.Components.get("default");
     var jQuerySelectorString ="";
     // Token $currentDate$ Change Handler
     defaultTokenModel.on("change:currentDate", function(newTokenName, currentDate, options) {
         if (currentDate !== "undefined" && currentDate !=="$result._time$") {
             // Token currentDate is set
             jQuerySelectorString='#custom_styled_table th a:contains("'+currentDate+'")';
             console.log(currentDate + " SUCCESS");
         }else{

             console.log("NOT SUCCESS JQUERY SEELCTOR");
         }

     });


    mvc.Components.get('custom_styled_table').getVisualization(function(tableView) {

         tableView.on('rendered', function() {
                     // Remove table sort class as Header Column should be fixed without sorting
             $("#custom_styled_table th").removeClass("sorts");
                     // If jQuerySelector is set then apply the class
             if (jQuerySelectorString != ""){
                $(jQuerySelectorString).addClass("tableHeaderAnchorYellow")
                 $(jQuerySelectorString).parents("th").addClass("tableHeaderGreen");
                 console.log("insertclass");
             }else{

                 console.log("class not inserted");
             }

         })


        // Register custom cell renderer
        tableView.table.addCellRenderer(new CustomTooltipRenderer());

        // Force the table to re-render
        //tableView.table.render();
    });

});
0 Karma

New Member

Hi @niketnilay is this a bug in Splunk why does the table flicker and remove the header styles even in the .on('rendered')? I am having the same issue and would rather not using a setTimeout workaround which works inconsistently. The rendered event should have been sufficient. Please let me know thank you!

0 Karma

SplunkTrust
SplunkTrust

@skahal_personal if you have setTimeout() after Table render, it should work as the delay seems to be just before actual table render.

Refer to answer on similar lines to what you have asked. If you still face the issue please share your code, issue screenshot and further details as a new question so that it gets proper attention from the community.

https://answers.splunk.com/answers/782763/how-to-add-a-header-for-row-numbers-in-a-column.html

____________________________________________
| makeresults | eval message= "Happy Splunking!!!"
0 Karma

SplunkTrust
SplunkTrust

@patricianaguit, your code to apply blue color seems to override mine. It is not in your JavaScript, so you have to make sure Blue is applied first. Also you would not need $("#custom_styled_table th").removeClass("sorts"); as sorting was already disabled in your original code (as per screenshot).

One of the crude ways to apply the Green Table Header would be to add classes for Yellow Text Color and Green Background color inside setTimeOut() function with a delay of 1 or 2 seconds.

____________________________________________
| makeresults | eval message= "Happy Splunking!!!"
0 Karma

Explorer

THANK YOU SO MUCH FOR THE HELP! the code is working already!

SplunkTrust
SplunkTrust

🙂 Wow good to know!

____________________________________________
| makeresults | eval message= "Happy Splunking!!!"
0 Karma