Javascript tooltip on hover. Create custom mouseover events with javascript code. It's grouping time

Everything is simply banal. We have two areas.

  • The first one performs the script start function. On my blog, this area contains the nickname of the author and the topic of the post in which this author left a comment. Let's call her starting area
  • The second area is the same hint that should appear as a result of the script. This area will be visible only if the mouse cursor is within the boundaries of the start area, and will disappear when the cursor leaves the start area.

The essence of the script is simple, determine the position of the user's cursor ( the cursor position is the padding, top and left, from the edge of the browser in pixels) and assigning that position to the tooltip region. The hint area must naturally be an absolutely positioned object.

It's all pretty logical, right? It remains to find out how to determine the position of the mouse cursor. Well, not just to find out, but to use what it offers us jQuery, namely pageX and pageY.

event.pageX, event.pageY- Contains the horizontal/vertical coordinate of the mouse event relative to the origin of the document, namely from the left edge of the page.

Implementing jquery tooltip

I'll post you complete code pages. The script has a comment, so it is not difficult to understand it.




Tooltip






?



Hint text to show when hovering over a question mark



Please note that the jquery file is connected by a link to the official site, that is, I did not download it.

Conclusion

In general, that's all, there is nothing complicated in the code, so use it to your health ( if you need such a script of course =))

Best wishes to you! I have everything for today!

P.S.: Do you know what neuro-linguistic programming is? In simple words This is the manipulation of human consciousness with the help of speech. Pleased with a useful "thing" if you are going to work in the media, well, or advertising. You can read more about NLP at http://enlp.info/. Good luck with your studies =)

Today, in the light of WEB 2.0 trends, it has become fashionable to add all sorts of "chips" to sites. They are implemented, as a rule, through JavaScript libraries. And my programming soul asked me to create something like this web-based JavaScript, 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 such a script: it shows hints in a cloud, when hovering over one or another element. Similar to 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 scope, it is compressed quite well by the compressor, and judging by the sIEve tests, memory will not leak through it in IE6.

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

  1. Required. The global context, or the browser's reference to the window object.
  2. Required. NodeList of elements (eg getElementsByTagName("DIV")), or a reference to the element on which to display the tooltip (eg getElementById("tip-div")).
  3. Optional. An object with style settings like this:
    (background: "yellow", border: "solid 1px green")
  4. 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() ( // Trigger 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” added to the cloud, but I didn’t want to complicate it, I think you can do it yourself if necessary. The script also hardcodes the mouseover and mouseout event handlers by assigning functions to the corresponding properties directly. Therefore, there is still the 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 that . 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) ( // Optional argument insurance: 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 the html tip element: function addTip(element,div,textTip) ( // Position must be absolute: div .style.position = "absolute"; // Override the values ​​from the styles settings object: for (prop in styles) ( if (styles.hasOwnProperty(prop)) ( div.style = styles; ) ) // Add the tooltip element to the tree DOM element.parentNode.appendChild(div); // Adding text to the tooltip div // This is done exactly to avoid memory leaks in IE6 div.appendChild(textTip); return div; ) // Handing out cakes (handlers events) // @parament element - link to html element function addHandlers(element) ( // Create div for tooltip: var div = DOC.createElement("DIV"), // Back We get the text for the hint - we take it from the title attribute textTip = DOC.createTextNode(element.tempTitle); // Mouse over event handler: function mouseOver() ( tipDiv = addTip(element,div,textTip); // Calculate the bubble position: tipDiv.style.top = element.offsetTop + offset.y - tipDiv.offsetHeight + "px" ; tipDiv.style.left = element.offsetLeft + offset.x + element.offsetLeft + "px"; ) // Mouse exit 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) ( // Loop through the given elements: for (i = 0; i

Thank you to @Blacknife, @Geyan and @dimaua for taking the time to answer this question. Perhaps their solutions are not inferior in quality, but I decided to opt for a jQuery plugin Tooltipster. He solves the problem posed in the question.

Mini review

  • Advantages - ample opportunities for customization, see below. plugin site. Cross-browser, does not slow down page display.
  • The disadvantage is that there are no examples of the Code - Result type on the same offsite, so you have to kill a little time to master it. However, a number of demos are given in one article in Russian .

Example code

Tooltipster does not throw tooltips out of the window, not only when they are simple. In the example shown, different tooltips appear when hovering over and clicking on an icon with a personalized design, and the time during which the tooltip will be visible is set - http://codepen.io/Kristinita/pen/RGzVmK.

$(document).ready(function() ( var $SashaElement = $(".SashaTooltip"); $SashaElement.tooltipster(( content: "Maybe it's a breeze Makes your lips move", 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.
  • When the seats are side of the world does not remain, the tooltip appears on another. 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 - at the top; when there is not enough space both below and above - on the right; and finally, if she has nowhere to go from below, above and to the right, she will be displayed on the left.

During filming, not a single tooltip popped out of the border. In even more complicated mine real examples this is also in order.

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

Standard way

Responsible for showing the tooltip (title). This attribute can be used to show tooltips for various objects, but is most commonly used as explanatory text for images.

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

As a hint, one word or phrase can be used, or several sentences at once. Usually 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 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

For a beautiful hint output, this method is usually used. It encloses the image in a container with an identifier. Thanks to this, it is possible to refer to this container in styles:

In the above example, the only incomprehensible 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 block container styles.

Relative positioning is used because the tooltip container will be positioned absolutely. Therefore, it is necessary to make sure 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 a tooltip) from stretching to the full width of the window. Now it remains to create an explanatory text.

Tooltips in css are easiest to do with 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 over the image container. The content: attr(data-name) property is intended to indicate text value. It corresponds to the property that is written in the data-name attribute of the image wrapper container.

After that, it remains to position the object absolutely and set the necessary parameters for it:

  • Color;
  • Font, etc.

Thus, we get the following css tooltip when hovering over the image:


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

Smooth appearance

However, css features allow for smooth tooltip appearance. In this case, pseudo-elements are not used. This is due to the fact that they are the ones that do not allow you to apply the option of smooth appearance. An example of the implementation of the smooth appearance of a tooltip on css is presented below:

Tooltip text

It is worth noting that the css code has not changed much:

#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 concerns the content property, which is not used in this example. It has lost relevance due to the fact that it is supported only by pseudo-elements. Another change is the introduction of the transition property. This property is responsible for creating smooth transitions. The attentive reader must have noticed the opacity: 0 value. It makes the tooltip container transparent.

Now, when hovering over the parent block, it is enough to return the standard transparency to the container with a hint. After that, you can test the code to make sure that the explanatory text appears on the screen smoothly.

CSS3 allows you to hide an element in other ways as well. For example, a transformation may be used. This method replaces full transparency with the transform: scale(0) property. It is also necessary to reduce the size of the container to 0. Thus, it will not 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 spectacular.

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.

Tooltip (tooltip) - tooltip on html + javascript\jQuery

An article from the "why do-it-yourself plugins, libraries" section. This time we will consider the implementation of a very interesting tool that is very useful in any interfaces where it is important to display hints, reminders for site visitors.

In fact, the implementation of tooltips (tooltip) is very simple and does not require the intervention of any external plugins, everything is much simpler. The element to which you want to display the tooltip must be marked with a selector and an attribute that will contain the tooltip text or even html. When hovering over an element, the tooltip text will be placed in the tooltip block. The block itself using javascript/jQuery placed close to parent element. It remains only to style the tooltip.

So let's get started:

We place html with the following content:

Superman

Spiderman

iron Man

Hulk

Styling the elements and the popup tooltip:

.tool-item( /* elements */ border-bottom: 1px dashed black; display button: inline-block; margin-right: 20px; cursor: pointer; ) .tooltip-block( /* tooltip */ position: absolute; background: white; border: 1px solid rgb(230, 230, 230); padding: 5px 8px; font-size: 10px; width: 140px; line-height: 13px; color: rgb(82, 82, 82); z -index: 400; display button:none; )

Javascript/jQuery:


An example script that places the tooltip to the right of the hover element:

You can fantasize about styling the tooltip: add a corner, give a shadow, block opening effects, and so on. For example, on our site you can see the tooltip on the left panel, the work is based on the same idea that we have covered in this article.