skip to Main Content

My goal is to keep track of an element that has an active Twitter Bootstrap popover. There can be only one such element at the same time. Here’s the relevant code:

$(document).ready(function() {

    $(".word").on("click", function(e) {
        e.stopPropagation();
        if (!$(this).hasClass("popover-active")) {
            $(".popover-active").popover("hide");
            $(".popover-active").removeClass("popover-active");
            $(this).popover("show");
            $(this).addClass("popover-active");
        }
    });

});

As you can see above, I’m using $().addClass and $().removeClass to add and remove a popover-active class to the element with the active popover. But perhaps there’s a better solution. I was thinking about using a variable to keep track of the selected element, as such:

$(document).ready(function() {

    var $activePopover = $();

    $(".word").on("click", function(e) {
        e.stopPropagation();
        if ($(this) !== $activePopover) {
            $activePopover.popover("hide");
            $(this).popover("show");
            $activePopover = $(this);
        }
    });

});

So my question is: Which method is better to use and why? Are there any other solutions that you can think of that are better than both of these?

2

Answers


  1. You can simplify it a bit, and let the popover init happen either via javascript, or entirely via data attributes, with something like this which uses the built in events (note that I removed the hyphen from your variable name. JS would interpret it as a minus, not a hyphen):

    $(document).ready(function () {
    
        var $activePopover;
    
        $(document).on('show.bs.popover', function (e) {
            if ($activePopover) { $activePopover.popover('hide') }
            $activePopover = $(e.target);
        });
    
    });
    

    See it in action here

    Login or Signup to reply.
  2. I think keeping track with a class is the best solution, because the popover is bind to the element. If you introduce a variable you have to sync it to be sure it is relevant to the popover state. Also it allows you to switch to a different popover plugin which supports multiple instances.

    I would do this:

    $(".word").on("click", function(e) {
        e.stopPropagation();
        $(this).toggleClass("popover-active");
    
        if ($(this).hasClass("popover-active")) {
            $(this).popover("show");
    
            return;
        }
    
        $(this).popover("hide");
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search