JSFiddle - React, Tailwind, and code Playground
by cloud8421
HTML
<img src="http://placehold.it/120x120&text=sample+text+1" alt="Sample text 1"/>
<img src="http://placehold.it/400x120&text=sample+text+2" alt="Sample text 2"/>
<img src="http://placehold.it/640x300&text=sample+text+3" alt="Sample text 3"/>
<img src="http://placehold.it/100x100&text=sample+text+4" alt="Sample text 4"/>
<img src="http://placehold.it/200x1400&text=sample+text+but+very+long+and+tedious+to+style" alt="Sample text but very long and tedious to style"/>
CSS
.tooltip {
background-color: yellow;
border: 1px solid;
position: absolute;
z-index: 3;
}
.img_container {
display: inline-block;
}
JavaScript
var Tooltip = function(){
//we store the container and the tooltip in variables accessible from within the object
var container, tooltip;
//private methods
function setup_container($image){
var image_width = $image.prop('width');
var image_height = $image.prop('height');
container = document.createElement('span');
container.className = 'img_container';
$(container).css({
width : image_width + 'px',
height: image_height + 'px'
});
$image.wrap($(container));
}
function setup_tooltip($image){
tooltip = document.createElement('span');
tooltip.textContent = $image.attr('alt');
tooltip.className = 'tooltip';
$image.before($(tooltip));
}
function remove_container($image){
$image.unwrap();
}
function remove_tooltip($image){
$image.prev('span').remove();
}
//public methods
return {
initialize: function(){
var that = this; //hacky this binding
//this is where we define all events we're tracking for user interaction
$('body')
.on('mouseenter', 'img', function(event){
if ($('.tooltip').length == 0) {
that.show_tooltip($(this));
}
})
.on('mouseleave', 'img', function(event){
if (event.relatedTarget.className !== 'tooltip') {
that.hide_tooltip($(this));
}
})
.on('click', '.tooltip', function(event){
alert('clicked tooltip:' + $(tooltip).text());
});
},
show_tooltip: function($image){
setup_container($image);
setup_tooltip($image);
},
hide_tooltip: function($image){
remove_tooltip($image);
remove_container($image);
}
}
}
...