kosmičák
kosmičák

Reputation: 1043

jstree: differentiate between left/middle mouse click

The following code sets up my tree (the s:property tags are struts2 stuff):

$(function () {
       $("#networkTree").jstree({ 
          "json_data" : {
             "ajax" : {
                "url" : "<s:property value='networkTreeDataUrl'/>"
             }
          },
          "plugins" : [ "themes", "json_data", "ui" ],
          "themes" : {
                "theme" : "default",
                "dots" : true,
                "icons" : false
          },
          "core" : {
              "html_titles" : true
           }
       }).bind("select_node.jstree", function (event, data) {
              window.location.href = "<s:property value='companyDetailsUrl'/>" + "?companyId=" + data.rslt.obj.attr("id");
              })
});

When the user left clicks a tree item the window URL changes depending on the companyDetailsUrl. So far correct but I'd like the browser (chrome) to open the link in a new tab when I click the middle mouse button as usual. It seems any mouse click selects the tree node and this triggers the bound event which replaces the window.location. What's the best way to prevent this?

Upvotes: 2

Views: 1425

Answers (1)

KeyNone
KeyNone

Reputation: 9150

I'd go for the which-property of the eventhandler.
This provides an easy way to distinguish buttons, according the jQuery-documentation:

event.which also normalizes button presses (mousedown and mouseupevents), reporting 1 for left button, 2 for middle, and 3 for right.

//rest of the code omitted
.bind("select_node.jstree", function (event, data) {
    if(event.which == 1) {
        //open link in current window
        window.location.href = YOURURL;
    } else if (event.which == 3) {
        //open link in new window
        window.open(YOURURL, '_blank');
    }
 })

Note that you have to replace YOURURL (obviously). I omitted it for readability.

Further note that this will most likely open a new window, instead of a new tab. For further reading on why it opens a new window and how you can open a new tab I recommend reading this question.

Upvotes: 2

Related Questions