Dashboards & Visualizations

Assistance with Javascript code to accommodate an "onclick" used in a div tag for executing a hyperlink

beetlejuice
Explorer

Back in the older Splunk days, I was able to configure a dashboard panel to allow a user the ability to click on the panel and go to another URL, using code similar to this in my dashboard XML:

 <div class="dashboard-panel" onclick="urlrd('http://www.xyz.com');">

 <script type="text/javascript">
   function urlrd(dest_url){
   window.location.href = dest_url;}
 </script>

I'm currently working on a dashboard that uses a PNG image as a background, with div tags used to define an area on the background (a rectangle) that will change color based on input read from a lookup table. The idea is for the consumer to click on the rectangle in order to be directed to a URL with more information; I'm just at the "demo" stage right now.

Here's a sample of the XML code I'm using:

<form stylesheet="alpha.css" refresh="30" script="drilldown.js">
    <label>Dashboard Test</label>
    <fieldset submitButton="false" autoRun="true">
        <input type="time" token="field1" searchWhenChanged="false">
            <label></label>
            <default>
                <earliest>rt-1m</earliest>
                <latest>rt</latest>
            </default>
        </input>
    </fieldset>
    <row>
        <panel id="image_panel">
            <search>
                <query>| inputlookup data.csv | head 1 | table value color_value</query>
                <earliest>0</earliest>
                <progress>
                    <set token="color_alpha">$result.color_value$</set>
                </progress>
            </search>
            <html>
                <div id="alpha" class="singleValue" style="color: $color_alpha$; background-color: $color_alpha$; width: 155px; height: 70px; top: 218px; left: 210px; cursor: pointer"/>
            </html>
        </panel>
    </row>
</form>

I am using this code for my JavaScript (called "drilldown.js"):

 var components = [
     "splunkjs/ready!",
     "splunkjs/mvc/simplexml/ready!",
     "jquery"
 ];

  require(components, function(
     mvc,
     ignored,
     $
 ) {

     $('#alpha').click(function() {
       window.open(
                   'http://www.google.com',
                   '_blank' 
                 );
     });
 });

While the background and singleValue "rectangle" work correctly on the dashboard, my configuration attempts to make the rectangle "clickable" in order to go to Google are not successful.

What to I need to tweak (or add) in order to make the click event successful?

0 Karma
1 Solution

jeffland
SplunkTrust
SplunkTrust

When you create some html elements inside a <html>-tag in Simple XML and use tokens in it, that entire section of the DOM is re-created every time the tokens change. Since you only add the event listener once in your js, it is lost after the first update of $color_alpha$ when the first progess-event is fired, and the new DOM elements no longer have your event listener.
What you want to do is use event bubbling and filtering the click events to specific origins like this (Simple XML unchanged from your example):

$(document).on("click", "#alpha", function() {
    window.open(
        'http://www.google.com',
        '_blank' 
    );
});

This listens to all click events, but does nothing unless they originate from an element with the id alpha. Check jquery docs here. The second argument can be any css selector, which is pretty neat for adding event listeners to multiple elements (think classes or data-foo attributes).

EDIT: just to clarify, the jquery selector can be any css selector as well - it may be wiser not to choose document and instead go for some element that is closer to your actual click origin but stable, such as your Simple XML panel or row containing the html-panel.

View solution in original post

jeffland
SplunkTrust
SplunkTrust

When you create some html elements inside a <html>-tag in Simple XML and use tokens in it, that entire section of the DOM is re-created every time the tokens change. Since you only add the event listener once in your js, it is lost after the first update of $color_alpha$ when the first progess-event is fired, and the new DOM elements no longer have your event listener.
What you want to do is use event bubbling and filtering the click events to specific origins like this (Simple XML unchanged from your example):

$(document).on("click", "#alpha", function() {
    window.open(
        'http://www.google.com',
        '_blank' 
    );
});

This listens to all click events, but does nothing unless they originate from an element with the id alpha. Check jquery docs here. The second argument can be any css selector, which is pretty neat for adding event listeners to multiple elements (think classes or data-foo attributes).

EDIT: just to clarify, the jquery selector can be any css selector as well - it may be wiser not to choose document and instead go for some element that is closer to your actual click origin but stable, such as your Simple XML panel or row containing the html-panel.

beetlejuice
Explorer

Thank you for the explanation and configuration, Jeff. This has solved my issue perfectly!

0 Karma

vinothn
Path Finder

@jeffland & @beetlejuice just an additional question related to the same post.
Now i am able to provide link to the particular id (ie: for example this solution gives href or link to all the rows) , but is there a way to enable the click to only specific row values.

Before providing the windows.open how to perform some conditions or check the row values..

0 Karma

niketn
Legend

@vinothn if you are coding click handler based on id then it will be unique for the DOM so in the above example there is only one node which will have id alpha. If you have multiple rows then you may have to chose ids like alpha, beta, gamma or alpha1, alpha2, alpha3 etc.

 $(document).on("click", "#alpha", function() {
        if (<yourcondition goes here>){
           //perform some pre-requisite operations before windows open here
           window.open( 'http://www.google.com', '_blank' );
        }else{
           // if your condition does not match execute else condition here or do nothing.
        }
 });

Refer to w3schools to learn if else condition block in JavaScript/jQuery: https://www.w3schools.com/js/js_if_else.asp

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

vinothn
Path Finder

@niketn i am relating your previous answer with this post. "https://answers.splunk.com/answers/809414/issue-with-css-html-js-formatting-search-output.html?child..."

Based on this display_token_with_html_content .js Based on this values are stored in the "#html_table" . Now i want to enable the windows.open to only one of the div element (ie:- Printer).
So i tried the below codes.

require(
     [
         'jquery',
         'splunkjs/mvc'
     ],
     function ($, mvc) {
         var unsubmittedTokenModel=mvc.Components.get("default");
         $(document).on('click','#html_table',function () {
            if ($('div.html_column_printer html_div_center').text() === "printer4") {
                  window.open('http://www.google.com','_blank');
                }
         });
     });




Try 2:

require(
     [
         'jquery',
         'splunkjs/mvc'
     ],
     function ($, mvc) {
         var unsubmittedTokenModel=mvc.Components.get("default");
         $(document).on('click','.html_column_printer html_div_center',function () {
            if ($(this).text() === "printer4") {
                  window.open('http://www.google.com','_blank');
                }
         });
     });


Since i am naive to jquery i am not sure about the incorrect part. 

Thanks in Advance

0 Karma

niketn
Legend

@vinothn I will post the reply to this on your previous thread. However, if you would have read the suggested docs you would have been able to solve this on your own.

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

kamlesh_vaghela
SplunkTrust
SplunkTrust

Hi,
Can you please try below XML and Javascript?

<form script="my.js">
  <row>
    <html>
      <div id="mydivId">Click Me</div>
    </html>
  </row>
</form>



require(['jquery', 'splunkjs/mvc/simplexml/ready!'], function ($) {
    var utils = require("splunkjs/mvc/utils");
    $(document).ready(function () {
        $("#mydivId").on("click", function (){
            utils.redirect("http://google.com", "_blank");
        });
    });
});

Thanks

0 Karma

beetlejuice
Explorer

UPDATE: Your Javascript code works if I replace "#mydivId" in the code with the panel ID I'm using ("image_panel"). If I replace "#mydivId" with the div ID I'm using ("alpha"), though, it does not work. Please reference my updated XML code in my question to see how I'm using the div element.

0 Karma

kamlesh_vaghela
SplunkTrust
SplunkTrust

Hi
Can you please update javscript with below code and try again ??

var components = [
  "splunkjs/ready!",
  "splunkjs/mvc/simplexml/ready!",
  "jquery"
];

require(components, function(
  mvc,
  ignored,
  $
) {
  $('#alpha').on("click",function() {
      window.open('http://www.google.com','_blank');
    });
});

Thanks

beetlejuice
Explorer

Hi Kamlesh...

I tried your suggestion, but to no avail. I updated my question to reflect a more detailed look into my dashboard's XML. Hopefully, that will clarify exactly what I'm looking for a bit better.

0 Karma

niketn
Legend

@beetlejuice, what is the content of panel you are clicking for drilldown? is the dashboard you want to open static or dynamic based on some token value set in your dashboard? Also is your current dashboard Simple XML or HTML?

Refer to one of the answers to one of the answers on similar lines, which sets an ID for panel and then uses jQuery Selector to select the panel and trigger JavaScript code on click() event.
https://answers.splunk.com/answers/471329/is-it-possible-to-drilldown-from-an-status-indicat.html

Also, if you want drilldown to open a new window based on clicking of a visualization rather than panel, you can code drilldown event directly from Splunk UI Editor(6.6 onward) or through Simple XML Chart configuration reference(without having to use JavaScript). Get the Splunk Dashboard Examples App from Splunkbase which covers several types of drilldown examples: https://splunkbase.splunk.com/app/1603/

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

beetlejuice
Explorer

Hi niketnilay...

I've revised my question to provide more detail and to answer your questions. I'm familiar with the Dashboard Examples App, but I couldn't find any examples that would fit my situation.

0 Karma
Get Updates on the Splunk Community!

Extending Observability Content to Splunk Cloud

Register to join us !   In this Extending Observability Content to Splunk Cloud Tech Talk, you'll see how to ...

What's new in Splunk Cloud Platform 9.1.2312?

Hi Splunky people! We are excited to share the newest updates in Splunk Cloud Platform 9.1.2312! Analysts can ...

What’s New in Splunk Security Essentials 3.8.0?

Splunk Security Essentials (SSE) is an app that can amplify the power of your existing Splunk Cloud Platform, ...