A tooltip is a short text message with an explanation that appears as a result of hovering the mouse cursor over an element on the page. Next, we'll look at how to make a tooltip in html.

Standard method

(title) is responsible for displaying the tooltip. This attribute can be used to display tooltips for various objects, but is most often used as explanatory text for images.

To display a tooltip, you just need to add this attribute and write the necessary explanatory text in it.

Either one word or phrase, or several sentences at once can be used as a hint. Typically the HTML tooltip looks like this:

The explanatory text does not appear immediately after hovering the mouse over the image, but after a couple of seconds. This feature of tooltips is enabled by default.

The standard HTML pop-up tooltip when hovering over text has one significant drawback - the lack of styling tools. To solve this problem, you need to use other ways to create a tooltip.

Pure css method

This method is usually used to display the tooltip beautifully. It involves enclosing a picture in a container with an identifier. Thanks to this, it is possible to access this container in styles:

In the above example, the only unclear point may be. This attribute has no function. However its value is used in js and css. Thus, this attribute can also be useful. But first we need to describe the styles of the block container.

Relative positioning is used because the tooltip container will be positioned absolutely. Therefore, it is necessary to ensure that the text is positioned only relative to the parent block, and not the entire page.

#pdskzk( position: relative; display: inline-block; )

Block-line display will not prevent the parent block (including the container with the tooltip) from stretching across the entire width of the window. Now all that remains is to create explanatory text.

Tooltips in css is simpler do everything using pseudo-elements:

#pdskzk:hover:after ( content: attr(data-name); position: absolute; left: 0; bottom: 0; background: rgba(5,13,156,.55); color: #fff; text-align: center ; font-family: cursive; font-size: 14px; padding: 3px 0; width: 100%; )

Despite the abundance of code, it is very easy to understand. The #pdskzk:hover:after selector is needed to create an after pseudo-element when the user places the cursor on the image container. The content: attr(data-name) property is intended to specify a text value. It corresponds to the property that is written in the data-name attribute of the image wrapper container.

After this, all that remains is to position the object absolutely and give it the necessary parameters:

  • Color;
  • Font, etc.

Thus, we get this css tooltip when hovering over an image:


Compared to the standard tooltip, this version of the explanatory text looks more interesting and attractive when hovering over an image. In addition, a tooltip appears immediately when you hover the cursor over an element. In this case, the smooth appearance of a tooltip is impossible due to the fact that pseudo-elements do not support such functionality.

Smooth emergence

However, CSS capabilities allow you to use a smooth appearance of the tooltip. In this case, no pseudo-elements are used. This is due to the fact that they do not allow the smooth appearance option to be used. An example of implementing a smooth appearance of a tooltip in css is presented below:

Tooltip text

It is worth noting that the css code has remained virtually unchanged:

#pdskzk2( position: relative; display: inline-block; ) #pdskzk2 .text ( transition: all 0.6s; opacity: 0; position: absolute; left: 0; bottom: 0; background: rgba(5,13,156,. 55); color: #fff; text-align: center; font-family: cursive; font-size: 14px; padding: 3px 0; width: 100%; transform: scale(0); ) #pdskzk2:hover .text (opacity: 1; )

The key change is to the content property, which is not used in this example. It has lost its relevance due to the fact that it is supported only by pseudo-elements. Another change is the appearance of the transition property. It is this property that is responsible for creating smooth transitions. The attentive reader probably noticed the opacity value: 0. It makes the container with the tooltip transparent.

Now, when you hover over the parent block, it is enough to return the standard transparency to the container with the tooltip. After this, you can check the code and make sure that the explanatory text appears smoothly on the screen.

CSS3 allows you to hide an element in other ways. For example, transformation can be used. This method involves replacing full transparency with the transform: scale(0) property. You also need to reduce the container size to 0. This way it won't be visible on the page. When hovering over a container with an image, you need to specify the transform: scale(1) property. This method allows you to make the appearance of a pop-up text message not only smooth, but also impressive.

other methods

Pop-up text messages can also be created using jQuery. This library can be used both to write your own code and to create a jQuery tooltip plugin that implements the desired effect.

Good day, curious subscribers and guests of the blog. Today we'll walk you through a useful section in a prototype-based scripting language, namely the JavaScript mouseover event.

I want you to have a good understanding of events such as click, mouseup, mousedown, mouseover and others, understand the difference between them and learn how to use them to solve your problems. Of course, after each key theoretical material you can find software implementations of examples. Well, let's get started!

All information about mouse events

For the mouse, there are several events that completely cover all possible cursor actions on the page. Among them are those that are triggered when you click on an object, hover over it, or move the pointer along open window. They can all be divided into two groups: simple and complex (composite) events.

Let's start simple

First, let's get acquainted with simple events. There are only five of them. For convenience, I have included a description of each tool in the table attached below.

Name Description
mousedown The named event is called when one of the mouse buttons is pressed but not yet released.
mouseup And this one works when you release the previously pressed button.
mouseover Called when the cursor is hovered over the object being processed.
mouseout Handles the action of the cursor leaving the element area.
mousemove Any pointer movement over a specific area triggers a current event.

Well, now, to consolidate the material, let’s look at an example. I created a small program in which the emotions of a smiley change when hovering and moving the cursor away.

Hover your mouse over the image and it will change. Now take it aside and watch the changes function ChangeOver(x) ( x.src= "http://storage2.vsemayki.ru/images/0/0/514/514012/previews/sign_front_white_500.jpg"; ); function ChangeOut(x) ( x.src= "http://storage2.vsemayki.ru/images/0/0/514/514102/previews/sign_front_white_500.jpg"; )

It's time to group

Now let's move on to complex views. Each of these events includes several simple ones. In this case, all the components of a complex event do not fire simultaneously, but are lined up in a queue. Therefore, you could sometimes observe such a situation that when you quickly click on, for example, website menu items, the clicks sometimes do not work.

Why is this so? The answer is quite simple.

Events are processed at a certain maximum permissible speed. And don’t forget that events are processed one by one. This means that if you click on different elements too quickly, the processing chain may not be completed completely.

So, below are the component events.

As you already understand, complex events make the life of developers somewhat easier by immediately including a set of necessary simple events. As a result, today no one can imagine the usual processing of buttons or other elements without the same click .

For practical acquaintance with the functioning of the above events, I modified the previous application. Analyze the result of my work.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 Example of hovering over a page element

Example of hovering over a page element Click on me once and the smiley will smile! Now double-click on me and the smiley will start moving! If you want to return to the initial state, then right-click on me! function Smile() ( document.getElementById("pic").src= "http://storage2.vsemayki.ru/images/0/0/514/514012/previews/sign_front_white_500.jpg"; ); function Cry() ( document.getElementById("pic").src= "http://storage2.vsemayki.ru/images/0/0/514/514102/previews/sign_front_white_500.jpg"; ); function Move() ( document.getElementById("pic").src= "https://otvet.imgsmail.ru/download/197747824_e708b2123d2b2d745d271f15cb144dcc_800.gif"; );

As you can see, everything is very simple. These elements are easy to call in code and bind them to specific actions.

Thanks to @Blacknife, @Geyan and @dimaua for spending your time answering this question. Perhaps their solutions are not inferior in quality, but I decided to opt for the Tooltipster jQuery plugin. It solves the problem posed in the question.

Mini review
  • Advantages - wide possibilities for customization, see the plugin website. Cross-browser, does not slow down page display.
  • The disadvantage is that on this same website there are no examples of the Code - Result type, so you will have to kill a little time to master it. However, a number of demos are given in one article in Russian.
Example code

Tooltipster doesn't throw tooltips out the window, not only when they are simple. In the demonstrated example, different tooltips appear when you hover over and click on an icon with a personalized design and set the time during which the tooltip will be visible - http://codepen.io/Kristinita/pen/RGzVmK.

$(document).ready(function() ( var $SashaElement = $(".SashaTooltip"); $SashaElement.tooltipster(( content: "Maybe it's the breeze that moves your lips", theme: ["tooltipster-punk-customized "], timer: 2000, side: ["bottom", "top", "right", "left"] )); $SashaElement.tooltipster(( content: "Maybe I’m shouting to You, but You can’t hear me ", theme: "tooltipster-punk", trigger: "click", multiple: true, timer: 2000, side: ["bottom", "top", "right", "left"] )); )); body ( background: gainsboro; margin-top: 7rem; padding-left: 7rem; ) .tooltipster-sidetip.tooltipster-punk-customized .tooltipster-box ( border-radius: 5px; border: none; border-bottom: 3px solid orange; background: #2a2a2a; )

Demonstration

What we see:

  • If the tooltip text does not fit on one line, it wraps to the next line.
  • When there is no space left on the light side, the tooltip appears on the other side. The display is configured by the side parameter, in the example I set it to ["bottom", "top", "right", "left"] . The default tooltip will be at the bottom, if there is no space there, it will be at the top; when there is not enough space both below and above - on the right; and finally, if there is nowhere for it to go from below, above and to the right, it will come out on the left.

During filming, not a single tooltip jumped out of bounds. In my even more complicated real examples, this is also in order.

Nowadays, in light of WEB 2.0 trends, it has become fashionable to add all sorts of “tricks” to sites. They are usually implemented using JavaScript libraries. And my programming soul asked me to create something like a JavaScript web browser, but without using any library, in a pure language, so to speak. And in the process of my learning this amazing language, I gave birth to this script: it shows hints in a bubble when you hover over a particular element. Analogue of JQuery tooltip or tip - I don’t remember exactly.

The script is implemented as a stand-alone module, except for its name, it does not add any other variables to the global area, it is compressed well by a compressor, and judging by the sIEve tests, memory will not leak through it in IE6.

Instructions: You just need to call the hint function as a constructor, passing it the following parameters:

  • Required. Global context or in the browser a reference to the window object.
  • Required. NodeList of elements (for example getElementsByTagName("DIV")), or a link to the element on which you want to display a tooltip (for example getElementById("tip-div")).
  • Optional. An object with style settings like this:
    (background: "yellow", border: "solid 1px green")
  • Optional. An object with cloud offset settings along the X and Y axis like this:
    ( x: 20, y: -20 ) - the object must contain these two properties
  • Usage example:

    Window.onload = function() ( // Run tooltips: new Tip(window, document.getElementsByTagName("a"), ( borderRadius: "10px", background: "yellow", border: "solid 1px green", color: "green", padding: "10px" ), (x: 20, y: -20)); )

    Of course, the hint script can be improved and a “leg” can be added to the cloud, but I didn’t want to complicate it, I think you can do it yourself if necessary. The script also hard-codes the mouseover and mouseout event handlers - by assigning functions to the corresponding properties directly. Therefore, there is still a possibility of conflicts in this place, but everything is fixable, as I already indicated in one of the previous posts, you can make a “composition” with an object which . In general, whoever needs/likes it, use it to your health.

    Listing hint script (it's not that big. It has more comments):

    Function Tip(GLOBAL, elements, styles, offset) ( // Insurance for optional arguments: if (!offset) ( offset = (x: 50, y: -10) ) if(!styles) ( styles = (); ) / / Declare variables and dependencies var DOC = GLOBAL.document, length = elements.length, tipDiv, prop, i; // Add an html tip element: function addTip(element,div,textTip) ( // Position must be absolute: div .style.position = "absolute"; // Distill the values ​​from the style settings object: for (prop in styles) ( if (styles.hasOwnProperty(prop)) ( div.style = styles; ) ) // Add a tooltip element to the tree DOM element.parentNode.appendChild(div); // Add text to the tooltip div // This is done here exactly to avoid // Memory leaks in IE6 div.appendChild(textTip); return div; ) // Distribute pies (handlers events) // @parament element - link to the html element. function addHandlers(element) ( // Create a div for the tooltip: var div = DOC.createElement("DIV"), // Set the text for the tooltip - take it from the attribute title textTip = DOC.createTextNode(element.tempTitle); // Mouse hover event handler: function mouseOver() ( tipDiv = addTip(element,div,textTip); // Calculate the position of the bubble: tipDiv.style.top = element.offsetTop + offset.y - tipDiv.offsetHeight + "px" ; tipDiv.style.left = element.offsetLeft + offset.x + element.offsetLeft + "px"; ) // Mouse move event handler: function mouseOut() ( tipDiv.parentNode.removeChild(tipDiv); tipDiv = null; ) // Assign event handlers: element.onmouseover = mouseOver; element.onmouseout = mouseOut; ) // If elements is a NodeList if (elements.item) ( // Iterate through the given elements: for (i = 0; i

    Task

    Make a tooltip when you hover over an image; the design of the tooltip should be controlled through styles.

    Solution

    Tooltip added to images via the tag's title attribute , is a system element, so the type of tooltip depends on the browser used, operating system and its settings. While you can't directly change the tooltip's appearance, it's possible to take a workaround and simulate a tooltip using JavaScript.

    First, let's create an empty element with the identifier floatTip and define its style. Three style properties must be required - position with the value absolute , it sets the absolute positioning of the element, display with the value none hides the element, and width sets the width of the tooltip. The remaining properties are at the request of the developer and are intended to change the design of the layer (example 1).

    Example 1: Tooltip style

    #floatTip ( position: absolute; /* Absolute positioning */ width: 250px; /* Block width */ display: none; /* Hiding from display */ border: 1px solid #000; /* Frame parameters */ padding: 4px ; /* Margins around text */ font-family: sans-serif; /* Serif font */ font-size: 9pt; /* Font size */ color: #333; /* Text color */ background: #ffe5ff; /* Background color */ )

    The script itself consists of two functions - moveTip tracks mouse movement and changes the position of the element in accordance with the cursor coordinates, and toolTip controls the visibility of the element and displays the desired text in it (example 2).

    Example 2. Script for displaying a layer

    Document.onmousemove = moveTip; function moveTip(e) ( floatTipStyle = document.getElementById("floatTip").style; w = 250; // Tooltip width // For IE6-8 browser if (document.all) ( x = event.clientX + document.body .scrollLeft; y = event.clientY + document.body.scrollTop; // For other browsers ) else ( x = e.pageX; // X coordinate of the cursor y = e.pageY; // Y coordinate of the cursor ) // Show layer to the right of the cursor if ((x + w + 10)< document.body.clientWidth) { floatTipStyle.left = x + "px"; // Показывать слой слева от курсора } else { floatTipStyle.left = x - w + "px"; } // Положение от верхнего края окна браузера floatTipStyle.top = y + 20 + "px"; } function toolTip(msg) { floatTipStyle = document.getElementById("floatTip").style; if (msg) { // Выводим текст подсказки document.getElementById("floatTip").innerHTML = msg; // Показываем подсказку floatTipStyle.display = "block"; } else { // Прячем подсказку floatTipStyle.display = "none"; } }

    For convenience and versatility, the script should be placed in separate file and connect it via the src attribute of the tag. The final code is shown in Example 3.

    Example 3: Creating a tooltip

    HTML5 CSS 2.1 IE Cr Op Sa Fx

    Tooltip #floatTip ( position: absolute; width: 250px; display: none; border: 1px solid #000; padding: 4px; font-family: sans-serif; font-size: 9pt; color: #333; background: # ffe5ff; )

    Lens: Canon EF 24-105 f/4L IS USM
    Flash: Canon Speedlite 580 EX
    Shutter speed: 1/125
    Aperture: 5.6")" onMouseOut="toolTip()">

    Result this example shown in Fig. 1.

    Rice. 1. Tooltip rendered using JavaScript