javabeats javabeats - 1 month ago 26
CSS Question

AngularJS tooltip without bootstrap?

I'm fairly new to AngularJS, and working on a project that is very restrictive towards external dependencies; in fact, Bootstrap is ruled out, and yet, I have to implement a "tooltip" directive.

I'm trying to do it using mouseenter and mouseleave events, but I wonder how can I use the directive's own attribute as the tooltip's content?

It'd be used like this:

<a id='someLink' my-tooltip='The content that I want to show'>Trigger</a>


Being quite green on UI development, can anyone tell me how I could add the necessary HTML/CSS to make this work through the directive?

Answer

DEMO

app.directive("tooltip", function () {
  return {
    link: function (scope, element, attrs) {

        $(element).on("mouseover", function () {
            $(this).append("<span>"+ attrs.tooltip +"</span>");
        });

        $(element).on("mouseout", function () {
            $(this).find("span").remove();
        });

        scope.$on("$destroy", function () {
            $(element).off("mouseover");
            $(element).off("mouseout");                
        });
    }
  };
});

CSS Source

a.tooltips {
  position: relative;
  display: inline;
}
a.tooltips span {
  position: absolute;
  width:140px;
  color: #FFFFFF;
  background: #000000;
  height: 30px;
  line-height: 30px;
  text-align: center;
  visibility: hidden;
  border-radius: 6px;
}
a.tooltips span:after {
  content: '';
  position: absolute;
  top: 50%;
  right: 100%;
  margin-top: -8px;
  width: 0; height: 0;
  border-right: 8px solid #000000;
  border-top: 8px solid transparent;
  border-bottom: 8px solid transparent;
}
a:hover.tooltips span {
  visibility: visible;
  opacity: 0.8;
  left: 100%;
  top: 50%;
  margin-top: -15px;
  margin-left: 15px;
  z-index: 999;
}