Search code examples
jquerytwitter-bootstraptreeview

How to add a target to the view items in bootstrap treeview


In my projetc I am using the following treeview bootstrap plugin: https://github.com/jonmiles/bootstrap-treeview

however the treeview does not support a target attribute in the generated a element.

For 'categories' nodes the content for the href attribute is '#' and for list-group item the content is an URL.

I assume with javascript I can detect which links within the treeview component has '#' as value for the href attribute and which don't. for the don'ts I have to add a target attribute to the a element.

Untill now I have not cleared to write a workable code so no use to upload it here.

Has someone fixed this before?

I added the following script to my page which adds the target attribute:

function addTarget(){
/*
function to add a target to the links in treeview
so they do not open in same page/view   
*/
    $('.treeview').find('a').each(function() {
        var href = $(this).attr('href');
        if(href != "#"){
            $(this).attr("target","_new");
        }
    });
}

Initially this works fine for the shown nodes, however when I open and close a node the treeview is re-calculated and the targets are removed as default.


Solution

  • You can prevent the link from opening with javascript, get the url and using javascript open the link in a new tab:

    $('#treeviewFolder').on('click', 'a', function () {
        event.preventDefault();
        if ($(this).attr('href')) {
           window.open($(this).attr('href'), "_blank"); 
        }
    });