Jquery tooltips with html

Create HTML tooltips by simple jQuery plug-in: 4 demos

Generally, tooltips in HTML are created by using the title attribute in a tag like a link or an image etc. This way, a basic tooltip is created that is displayed as a user hovers the mouse over that element.

Tooltip can be a nice way for contextual help or for explaining the purpose or intention of a certain element. For example, as entering the password in a textbox, you may show a tooltip with password creation guidelines. The password must be eight characters long, must contain a special symbol and a number etc.

I have covered a few tooltips related tutorial including Bootstrap based tooltips, using a jQuery built-in tooltip plugin and another is here.

In this tutorial, HTML 5 tooltips are created by using a light-weight jQuery plug-in. The plug-in name is jquery.tooltip.js that you may download from the GitHub website here.

Have a look at live demos and how to set up this tooltip plug-in to be used for your project in the coming section.

A demo of tooltip HTML 5

The plug-in requires using the data attributes rather than using the title attribute for creating the HTML tooltips. You have to use data-tooltip attribute along with data-options for specifying the direction and content of the tooltip. Have a look at the live demo where direction is set downwards:

html tooltip

See online demo and code

For using this plug-in in your web project, follow these steps.

Include the CSS file that defines tooltip’s style in the section:

(Set the path according to your directory structure)

Write the markup where you want to create that tooltip. In the demo, I used a tag with a CSS class:

Источник

Создаем простой tooltips с помощью CSS и jQuery

CSS tooltips очень популярны в современном веб дизайне, и вопреки широко распространенному мнению их довольно легко создать, особенно с помощью различных популярных javascript-framework-ов.

Позже мы будем использовать javascript, чтобы извлечь title и вставить его в контейнер:

Это обыкновенный Tooltips

CSS для нашего tooltips будет выглядеть примерно так:

.tooltip position:absolute;
z-index:999;
left:-9999px;
background-color:#dedede;
padding:5px;
border:1px solid #fff;
width:250px;
>
.tooltip p margin:0;
padding:0;
color:#fff;
background-color:#222;
padding:2px 7px;
>

* This source code was highlighted with Source Code Highlighter .

Position должен быть absolute, для того чтобы Javascript мог установить top и left свойство для div, который будет размещаться рядом с нашим курсором мыши. Пока мы устанавливаем свойство left = -9999px. Остальная часть CSS только для визуального оформления.

Читайте также:  Php установить модуль postgresql

Создаем jQuery Tooltips: jQuery-код — краткий и простой:

function simple_tooltip(target_items, name) $(target_items).each( function (i) $( «body» ).append( «

+name+ «‘ >+name+i+ «‘>

» +$( this ).attr( ‘title’ )+ «

» );
var my_tooltip = $( «#» +name+i);

$( this ).removeAttr( «title» ).mouseover( function () my_tooltip.css().fadeIn(400);
>).mousemove( function (kmouse) my_tooltip.css();
>).mouseout( function () my_tooltip.fadeOut(400);
>);
>);
>
$( document ).ready( function () simple_tooltip( «a» , «tooltip» );
>);

* This source code was highlighted with Source Code Highlighter .

↑ Это может выглядеть сложным, особенно если Вы плохо знакомы с jQuery, но на самом деле все довольно просто. Прежде всего мы создаем функцию:

↑ target_items — переменная, которую мы определяем, вызывая скрипт. Например: чтобы добавить tooltips ко всем ссылкам в блоке #maincontent, необходимо ввести “#maincontent а”. Name определяет css класс, который мы применяем для нашего tooltip. Мы используем переменные здесь в целях придания гибкости скрипту, таким образом Вы можете добавить различные tooltips с различным стилями.

function simple_tooltip(target_items, name) $(target_items).each( function (i) // generates code for each tooltip
>);
>

↑ Здесь мы генерируем код для каждого пункта, который будет найден нашим скриптом. Переменная i, которую мы передаем функции, будет автоматически увеличена jQuery после каждого повторения. Таким образом мы будем в состоянии дать каждому tooltips уникальный ID.

function simple_tooltip(target_items, name) $(target_items).each( function (i) $( «body» ).append( «

+name+ «‘ >+name+i+ «‘>

» +$( this ).attr( ‘title’ )+ «

» );
>);
>

↑ Этот фрагмент создает html-код для каждого tooltip. Они все получают один и тот же сlass, но различные ID. Title добавляется между тегами р.

function simple_tooltip(target_items, name) $(target_items).each( function (i) $( «body» ).append( «

+name+ «‘ >+name+i+ «‘>

» +$( this ).attr( ‘title’ )+ «

» );

↑ Эта строка выбирает tooltip и сохраняет его в переменной для дальнейшего использования.

function simple_tooltip(target_items, name) $(target_items).each( function (i) $( «body» ).append( «

+name+ «‘ >+name+i+ «‘>

» +$( this ).attr( ‘title’ )+ «

» );
var my_tooltip = $( «#» +name+i);

$( this ).removeAttr( «title» ).mouseover( function () >).mousemove( function (kmouse) >).mouseout( function () >);

↑ Это — основная конструкция нашей функций. Прежде всего мы выбираем текущую ссылку $(this). Затем удаляем аттрибут title, так как мы не хотим что бы появлялся «нормальный» tooltip, который показывает каждый браузер, при наведении мыши на ссылку.

  • mouseover вызывается, когда мы впервые наводим на ссылку;
  • mousemove вызывается, когда мы перемещаем мышь над ссылкой;
  • mouseout вызывается, когда мышь «уходит» с сылки.
Читайте также:  Python strptime no time

* This source code was highlighted with Source Code Highlighter .

Теперь мы определяем, что будет происходить, когда будут вызваны различные функции:
На mouseover мы устанавливаем некоторые значения css для tooltip: мы определяем прозрачность и устанавливаем display:none.
На mousemove мы устанавливаем значения для top и left чтобы помещать tooltip рядом с курсором. Координаты X и Y вызываются через .pageX и .pageY. Мы также добавляем небольшое смещение на 15 px, чтобы tooltip не находился непосредственно под курсором.
На mouseout мы просто вызываем функцию fadeOut(), чтобы скрыть tooltip.

↑ Последнее что мы делаем — это вызываем скрипт, как только документ будет загружен. Как было упомянуто ранее, первый параметр — это селектор, а второй параметр — classname нашего tooltip. Таким образом Вы можете создать различные дизайны для разных tooltips.

А это результат нашей работы (См. внизу страницы и при наведении на картинку вверху страницы)

Источник

Tooltip

Customizable, themeable tooltips, replacing native tooltips.

Examples

Hover the links above or use the tab key to cycle the focus on each element.

html>
html lang="en">
head>
meta charset="utf-8">
meta name="viewport" content="width=device-width, initial-scale=1">
title>jQuery UI Tooltip - Default functionality title>
link rel="stylesheet" href="//code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
link rel="stylesheet" href="/resources/demos/style.css">
script src="https://code.jquery.com/jquery-3.6.0.js"> script>
script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"> script>
script>
$( function( )
$( document ).tooltip();
> );
script>
style>
label
display: inline-block;
width: 5em;
>
style>
head>
body>
p>a href="#" title="That's what this widget is">Tooltips a> can be attached to any element. When you hover
the element with your mouse, the title attribute is displayed in a little box next to the element, just like a native tooltip. p>
p>But as it's not a native tooltip, it can be styled. Any themes built with
a href="http://jqueryui.com/themeroller/" title="ThemeRoller: jQuery UI's theme builder application">ThemeRoller a>
will also style tooltips accordingly. p>
p>Tooltips are also useful for form elements, to show some additional information in the context of each field. p>
p>label for="age">Your age: label>input id="age" title="We ask for your age only for statistical purposes."> p>
p>Hover the field to see the tooltip. p>
body>
html>

Want to learn more about the tooltip widget? Check out the API documentation.

Interactions

Widgets

Effects

Utilities

Books

Copyright 2023 OpenJS Foundation and jQuery contributors. All rights reserved. See jQuery License for more information. The OpenJS Foundation has registered trademarks and uses trademarks. For a list of trademarks of the OpenJS Foundation, please see our Trademark Policy and Trademark List. Trademarks and logos not indicated on the list of OpenJS Foundation trademarks are trademarks™ or registered® trademarks of their respective holders. Use of them does not imply any affiliation with or endorsement by them. OpenJS Foundation Terms of Use, Privacy, and Cookie Policies also apply. Web hosting by Digital Ocean | CDN by StackPath

Источник

Tooltip Widget

Description: Customizable, themeable tooltips, replacing native tooltips.

QuickNavExamples

Options

Methods

Events

Tooltip replaces native tooltips, making them themeable as well as allowing various customizations:

  • Display other content than just the title, like inline footnotes or extra content retrieved via Ajax.
  • Customize the positioning, e.g., to center the tooltip above elements.
  • Add extra styling to customize the appearance, for warning or error fields.

A fade animation is used by default to show and hide the tooltip, making the appearance a bit more organic, compared to just toggling the visibility. This can be customized with the show and hide options.

The items and content options need to stay in-sync. If you change one of them, you need to change the other.

In general, disabled elements do not trigger any DOM events. Therefore, it is not possible to properly control tooltips for disabled elements, since we need to listen to events to determine when to show and hide the tooltip. As a result, jQuery UI does not guarantee any level of support for tooltips attached to disabled elements. Unfortunately, this means that if you require tooltips on disabled elements, you may end up with a mixture of native tooltips and jQuery UI tooltips.

Keyboard interaction

When the tooltip is open and the corresponding item has focus, the following key commands are available:

Theming

The tooltip widget uses the jQuery UI CSS framework to style its look and feel. If tooltip specific styling is needed, the following CSS class names can be used for overrides or as keys for the classes option:

  • ui-tooltip : The outer container for the tooltip.
    • ui-tooltip-content : The content of the tooltip.

    Dependencies

    Additional Notes:

    • This widget requires some functional CSS, otherwise it won't work. If you build a custom theme, use the widget's specific CSS file as a starting point.

    Источник

Оцените статью