Всплывающая подсказка

Атрибут data-*

В HTML 4 крайне не хватало возможности создавать свои собственные атрибуты для хранения значений. Зачем это надо? Вот несколько задач, где это может потребоваться.

  • Создание всплывающих подсказок без применения скриптов.
  • Определение стиля элемента на основе значения атрибута.
  • Получение и изменение значений через скрипты.

В HTML5 появился новый универсальный атрибут, который можно добавлять к любому тегу. Правила написания атрибута простые:

  • всегда начинаем с data-;
  • используем только латинские буквы, дефис (-), двоеточие (:) и подчёркивание (_).

CSS и JavaScript немного по разному обращаются к таким атрибутам, так что разберём примеры для них отдельно.

CSS

В CSS есть атрибуты тегов, при наличии какого-либо атрибута или заданного значения мы задаём необходимый стиль.

Теперь можем в стилях обратиться к этому элементу как div[data-fluid] и установить для него нужное оформление. В общем, это напоминает работу классов, поэтому не является какой-то уникальной или необходимой фичей. Так что полезнее задавать значения.

В CSS после этого можем задавать разный стиль при различных значениях нашего атрибута data-columns.

div[data-columns=2] < width: 480px; >div[data-columns=3]

Опять же, это в какой-то мере является заменой классам, ничего ведь не мешает сделать классы с именами column-2, column-3 и добавлять их при необходимости.

Более изящной областью применения выступает включение функции attr() . Она получает значение заданного атрибута и вставляет его в стиль. Удобно это использовать для создания всплывающих подсказок. Текст пишем прямо внутри элемента, а вывод и оформление подсказки реализуем с помощью CSS.

     meter < position: relative; >meter:hover::after 

Температура воды

В данном примере к элементу добавляется атрибут data-description содержащий необходимый текст для вывода. Само отображение происходит с помощью псевдоэлемента ::after и свойства content , значением которого как раз и выступает функция attr() .

JavaScript

Если в CSS мы обращаемся к имени атрибута напрямую, указывая его полностью, то в JavaScript это делается через метод dataset. Само имя атрибута преобразовывается в переменную по следующим правилам:

  • data- отбрасывается;
  • любой дефис идущий перед буквой отбрасывается, а буква за ним становится заглавной.

На практике это выглядит так.

data-description превращается в description.
data-full-description превращается fullDescription.
data-description-of-tag превращается descriptionOfTag.

Традиционный способ получить доступ к элементу и его атрибутам — задать идентификатор и обратиться к элементу через getElementById , как показано в примере ниже.

      
Пользователь

Вначале добавляем к элементу идентификатор с уникальным значением. Затем получаем доступ к элементу через getElementById . Теперь мы можем обращаться к любым атрибутам data через метод dataset , причём не только получать, но и устанавливать значения. Храниться они будут до перезагрузки страницы или до установки нового значения.

См. также

Источник

Data-title/data-original-title attributes and accessibility

Reference: https://getbootstrap.com/docs/4.1/components/tooltips/ Question: In Bootstrap 4 I used the following sample code to update the title of the tooltip (where ‘statusIcon’ is the element, in this case is a font awesome icon, but same principal would apply for a button or anything else: Razor page html element: Reading the manual for Bootrap 5, they don’t appear to tell us how to achieve this with Vanilla JS What I’ve tried so far in Javascript: Am using variables in the element Id because I’m working with element in a Razor List View. Solution 1: You can update the tooltip title by changing the attribute Solution 2: Since Bootstrap 5.0 no longer requires jQuery, use , then reinitialize the tooltip after modifying the element: (updated to use your Razor page element)

Data-title/data-original-title attributes and accessibility

I have been searching for information about the attributes data-title and data-original-title. My issue is that Twitter Bootstrap converts the title-attribute into a data-original-title and I am not sure that this is what I want. What about screen readers for instance? Do they treat the data-title as a title, or do they ignore it? If I use one of those data-attributes, do I have to add a title-attribute as well?

The custom data-* attributes are defined for HTML5. They are «intended to store custom data private to the page or application».

These attributes are not intended for use by software that is independent of the site that uses the attributes.

So other tools (like screen readers) should not make use of them.

If something is a title , you should not use a data-* attribute (like data-title ) in the first place, as the spec says «[…] for which there are no more appropriate attributes or elements»; use title .

JQuery Tools Tooltip, I’m about to do the same thing. I looked through the Tooltip plugin code, and discovered as quick and easy way to update the tooltip. The plugin removes the title attribute and puts that content into an element property called tooltipText.

Bootstrap Popover need to style data-original-title

Created a popover in bootstrap that has a title (data-original-title). How can I make it bold?

Fiddle Link http://jsfiddle.net/DivineChef/8J5w6/1/

Here are three possibilities to achieve your goal.

    Use data-html=true and wrap your title in a element

Another solution that worked for my project (Bootstrap 4.3.1):

Use html tag and put data-html=»true» attribute.

How to change an element’s title attribute using jQuery, As an addition to @Cᴏʀʏ answer, make sure the title of the tooltip has not already been set manually in the HTML element. In my case, the span class for the tooltip already had a fixed tittle text, because of this my JQuery function $(‘[data-toggle=»tooltip»]’).prop(‘title’, ‘your new title’); did not work.. When I …

Bootstrap 5 update Tooltip Title with Javascript

In Bootstrap 4 I used the following sample code to update the title of the tooltip (where ‘statusicon’ is the element, in this case is a font awesome icon, but same principal would apply for a button or anything else:

$(statusIcon).attr('data-original-title', 'Check Error logs for details').tooltip(); 

Reading the manual for Bootrap 5, they don’t appear to tell us how to achieve this with Vanilla JS

What I’ve tried so far in Javascript:

var statusIconId = 'statusIcon:' + pluginId + ''; var statusIcon = document.getElementById(statusIconId); document.getElementById(statusIconId).setAttribute("data-bs-original-title", 'Check Error logs for details'); 

Am using variables in the element Id because I’m working with element in a Razor List View.

You can update the tooltip title by changing the data-bs-original-title attribute

Since Bootstrap 5.0 no longer requires jQuery, use document.querySelector() , then reinitialize the tooltip after modifying the element:

// initialize const tooltipElement = document.querySelector('[data-bs-toggle="tooltip"]') let bsTooltip = new bootstrap.Tooltip(tooltipElement) // update tooltipElement.title = 'New Title' bsTooltip = new bootstrap.Tooltip(tooltipElement)

(updated to use your Razor page element)

Here is example if your tooltip is in loop, and you want to update the clicked button tooltip.

Use case:

Copy button in table row using clipboard.js

before click

when click

Code:
let clipboard = new ClipboardJS('.btn-clip'); clipboard.on('success', function (e) < let trigger_button = e.trigger; // update the tooltip title, get the tooltip instance, and show it trigger_button.setAttribute('data-bs-original-title', 'Copied!'); let btn_tooltip = bootstrap.Tooltip.getInstance(trigger_button); btn_tooltip.show(); // reset the tooltip title trigger_button.setAttribute('data-bs-original-title', 'Copy to clipboard'); >); 

I had to do the following to get it working with Bootstrap 5 and ClipboardJS 2:

     

JQuery change original-title text on click?, To change an attribute on an element using jQuery, you use attr. Within an event handler hooked up with jQuery, the original DOM element is available as this. To get a jQuery wrapper around it, use $ (this). E.g.: $ (this).attr («original-title», «new text»); Side note: The attribute original-title is invalid for div …

Change Twitter Bootstrap Tooltip content on click

I have a tooltip on an anchor element, that sends an AJAX request on click. This element has a tooltip (from Twitter Bootstrap). I want the tooltip content to change when the AJAX request returns successfully. How can I manipulate the tooltip after initiation?

Just found this today whilst reading the source code. So $.tooltip(string) calls any function within the Tooltip class. And if you look at Tooltip.fixTitle , it fetches the data-original-title attribute and replaces the title value with it.

$(element).tooltip('hide') .attr('data-original-title', newValue) .tooltip('fixTitle') .tooltip('show'); 

and sure enough, it updates the title, which is the value inside the tooltip.

$(element).attr('title', 'NEW_TITLE') .tooltip('fixTitle') .tooltip('show'); 

In Bootstrap 3 it is sufficient to call elt.attr(‘data-original-title’, «Foo») as changes in the «data-original-title» attribute already trigger changes in the tooltip display.

UPDATE: You can add .tooltip(‘show’) to show the changes immediately, you need not to mouseout and mouseover target to see the change in the title

elt.attr('data-original-title', "Foo").tooltip('show'); 

Here is update for the Bootstrap 4 :

var title = "Foo"; elt.attr('data-original-title', title); elt.tooltip('update'); elt.tooltip('show'); 

But the best way is to do like this:

var title = "Foo"; elt.attr('title', title); elt.attr('data-original-title', title); elt.tooltip('update'); elt.tooltip('show'); 
var title = "Foo"; elt.attr('title', title).attr('data-original-title', title).tooltip('update').tooltip('show'); 

From the UX side you just see that text is changed with no fading or hide/show effects and there is no needs for the _fixTitle .

you can update the tooltip text without actually calling show/hide:

$(myEl) .attr('title', newTitle) .tooltip('fixTitle') .tooltip('setContent') 

Data URLs, Data URLs are composed of four parts: a prefix ( data: ), a MIME type indicating the type of data, an optional base64 token if non-textual, and the data itself: data: [] [;base64],. The mediatype is a MIME type string, such as ‘image/jpeg’ for a JPEG image file. If omitted, defaults to text/plain;charset=US …

Источник

Bootstrap: подсказки на JQuery

Вторая заметка из серии, посвященной относительно детальному знакомству с CSS-фреймворком под названием Twitter Bootstrap. Сегодня я покажу вам о том, как подключать подсказки на JQuery.

Всплывающие подсказки на JQuery с Twitter Bootstrap

Итак, tooltips в бутстрапе могут быть четырех типов в зависимости от направления их появления — right, left, top и bottom. Задаются они атрибутом data-placement у гиперссылки. С помощью data-original-title можно задавать текст во всплывающей подсказке. Ну а data-toggle=»tooltip» служит для указания скрипту, что здесь не просто линк, а tooltip, — задается свойством селектора в настройках.

К моему большому сожалению пример не работает в Internet Explorer 8, — выводится ошибка, связанная с JavaScript / JQuery. Разбираться с ней мне не захотелось. Тем более, что в официальной документации к фреймворку выводится тоже самое.

В отличие от вкладок, которыми можно было пользоваться и без явной инициализации, здесь помимо подключения JavaScript потребуется написать немного программного кода на нем же:

    

Выше были показаны два варианта инициализации скрипта подсказок. В первом случае свойство trigger указывает на срабатывание при наведении курсора мышка, а во втором — только при получении фокуса. HTML разметка будет выглядеть примерно следующим образом:

Tight pants next level keffiyeh you probably haven't heard of them. Photo booth beard raw denim letterpress vegan messenger bag stumptown. Farm-to-table seitan, mcsweeney's fixie sustainable quinoa 8-bit american apparel have a terry richardson vinyl chambray. Beard stumptown, cardigans banh mi lomo thundercats. Tofu biodiesel williamsburg marfa, four loko mcsweeney's cleanse vegan chambray. A really ironic artisan whatever keytar , scenester farm-to-table banksy Austin twitter handle freegan cred raw denim single-origin coffee viral.


А вот эта всплывающая подсказка покажется только при получении фокуса - нажимайте клавишу табуляции.

Источник

Читайте также:  Import ssh in python
Оцените статью