Tooltip Recipe
An example of how to build a simple tooltip widget using can.Control. Includes jQuery, CanJS and all of its plugins. Use it as a starting point when you want to demo something.
by donejs
HTML
<script src="http://canjs.com/release/2.0.1/can.jquery.js"></script>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>
CSS
@import url(http://fonts.googleapis.com/css?family=Lato:100,400,700);
* {
font-family: 'Lato', sans-serif;
font-size: 12px;
text-shadow: 0 -1px 0 #ffffff;
}
.tooltip {
position: absolute;
width: 200px;
height: 50px;
padding: 5px;
background: #333;
text-shadow: 0 -1px 0 #666;
color: #fff;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
-moz-box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.26);
-webkit-box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.26);
box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.26);
}
.tooltip:before {
content: "";
border-top: 10px solid transparent;
border-bottom: 10px solid transparent;
border-right:10px solid #333;
display: block;
height: 0;
width: 0;
position: absolute;
top: 5px;
left: -10px;
}
li {
font-weight: bold;
width: 80px;
border: solid 1px #eee;
margin: 5px;
padding: 5px;
cursor: pointer;
position: relative;
}
li:hover {
background: #999;
color: #fff;
text-shadow: 0 -1px 0 #666;
}
JavaScript
(function() {
// Create a Tooltip control that takes:
// - html - the html for the tooltip
// - relativeTo - which element to position this tooltip relative to
var Tooltip = can.Control.extend({
init : function(){
// we'll use this offset to position this.element
var offset = this.options.relativeTo.offset();
// set the html
this.element.html(this.options.html)
// add a class for styling
.addClass("tooltip")
// append to the offsetParent so scrolling works better
.appendTo(this.options.relativeTo.offsetParent() )
// set the position of the tooltip
.offset({
left: offset.left+this.options.relativeTo.width(),
top: offset.top-this.options.relativeTo.height() / 2
})
},
// listen for any click on the window
'{window} click': function( el, ev ) {
// hide only if we clicked outside the tooltip
// or outside the relative element
if (!this.element.has( ev.target ).length &&
ev.target !== this.element[0] &&
ev.target !== this.options.relativeTo[0] ) {
this.element.remove();
}
}
})
// Listen and create a tooltip widget
$("li").bind("click", function(){
new Tooltip( $("<div>"), {
relativeTo : $(this),
html : "tooltip"
})
})
})();