简体   繁体   中英

Bootstrap tabs on hover with clickable links

I am using bootstrap tabs functionality and I would like to implement the following features:

  1. Use mouseenter instead of click to toggle between tabs
  2. To prevent clicking action on links.

Here is my jsfiddle sample code. https://jsfiddle.net/irider89/bmLpwtqb/3/

$('.nav li a').hover(function (e) {
    e.preventDefault()
    $(this).tab('show');
});

$('.nav li a').click(function (e) {
    return true;
});

How this could be achieved?

I need to be able click on mainmenu items (Home, Profile, Messages, Settings) and go to the specific url.

Don't use window.location.href = ... method! Middle mouse click will not work.


1) Toggle on hover. Bind a simple mouseenter handler on the document object:

$(document).on('mouseenter', '[data-toggle="tab"]', function () {
  $(this).tab('show');
});

2) Prevent clicking. It's better to use .off('click', ...) method to reset Bootstrap built-in handler instead of writing custom click handler dealing with custom data attribute. Like so:

$(document).off('click.bs.tab.data-api', '[data-toggle="tab"]');

Then use native href to specify external link and data-target to point to the content pane.


Also there is a small Bootstrap plugin which does all of that automatically : https://github.com/tonystar/bootstrap-hover-tabs .

Demo

Use some new "data-" attribute to mention the url, like this below

<a href="#home" aria-controls="home" role="tab" data-toggle="tab" data-href="www.google.com">Home</a>

and use the script like this

 $('.nav li a').on("click",function (e) {
          window.location.href = $(this).attr("data-href");
    });

Use this to go the url:

$('.nav li a').click(function (e) {
   window.location.href = $(this).attr("href");
});

You can simply use this code to implement that feature no 1, changing tabs on hover

$('.nav-tabs li').hover(function(){
    $('.nav-tabs li a').removeClass('active show');
    $(this).children('a').addClass('active show');
    var href = $(this).children('a').attr('href');
    href = href.substr(1);
    $('.tab-pane').removeClass('active show');
    $('#'+href).addClass('active show');
});

for next feature add this code to disable click

$('.nav-tabs li').click( function(e){
    e.prevenetDefault(); 
}

Try this:

//first, we need to show tab-content on mouseover
$(".nav-link").mouseover( function() {
    $(this).tab("show");
});

// on hovering quickly, need to remove the active class from the related tab panel
$(".nav-link").on("show.bs.tab", function(e) {
    const tabPanelId = e.relatedTarget.getAttribute("href");
    $(tabPanelId).removeClass("active");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM