Skip to content

A Tooltipster plugin to make tooltips appear when you select / highlight a text

License

Notifications You must be signed in to change notification settings

louisameline/tooltipster-selectableText

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 

Repository files navigation

tooltipster-selectableText

A Tooltipster plugin to make a tooltip appear when you select / highlight a text. MIT license

Demo: https://jsfiddle.net/5xqqmrt6/41/

Installation

Include the plugin file in your page AFTER the Tooltipster file.

<html>
    <head>
        ...
        <script type="text/javascript" src="tooltipster/dist/js/tooltipster.bundle.min.js"></script>
        <script type="text/javascript" src="tooltipster-selectableText/tooltipster-selectableText.js"></script>
    </head>
</html>

Usage

Once the plugin is included in the page, there are two new Tooltipster core methods you can use: startSelectable and stopSelectable. The first one is in the form:

$.tooltipster.startSelectable(
	selector || jQuery collection,
	function(instance, selectedText) {
		return contentToDisplayInTheTooltip;
	},
	options
);

where instance is the instance of the tooltip which is about to be displayed and options is an object with your options for that tooltip (see Tooltipster's documentation). Just like any other Tooltipster tooltip, contentToDisplayInTheTooltip can be a string or HTML (check the documentation). The second method is in the form:

$.tooltipster.stopSelectable(selector || jQuery collection);

The selected text will be wrapped in a span that has a .tooltipster-selectedText class. So if you want to highlight it in yellow, you can write in your CSS:

.tooltipster-selectedText {
	background: yellow;
}

Limitations

This plugin works well on plain text. When you want to select cross-paragraphs text or partial HTML tags, it will not work because of how the native surroundContents method works. Also, the text is randomly unselected (in Chrome at least) when we wrap it in a span. If you want to make this plugin better with a PR, help is welcome.

Example

$.tooltipster.startSelectable(
	'p',
	function(instance, selectedText) {
		return translateInGerman(selectedText);
	},
	{ animation: 'slide' }
);

Or:

$.tooltipster.startSelectable(
	$('#myelement').next(),
	function(instance, selectedText) {
		
		// some kind of asynchronous task
		setTimeout(function() {
			instance.content('My tooltip content');
		}, 2000);
	
		return $('<span><img src="spinner.gif" /> Loading...</span>');
	}
);

And later:

$.tooltipster.stopSelectable('p');

Thanks to @macmessa and @yairneumann11 for suggesting this plugin.

About

A Tooltipster plugin to make tooltips appear when you select / highlight a text

Resources

License

Stars

Watchers

Forks

Packages

No packages published