jquery dynamic tooltip

為{幸葍}努か 提交于 2019-12-06 08:43:48

So, you basically want to store raw HTML into the title field? That simply does not work. It would create HTML Errors of unholy proportions.

Instead, why don't you just store the Text into the title field (but only if you must... a Javascript Object with the contents would be more practicable [AND you can store raw HTML into them ;)])

In case you store the tooltip text into the title field, you won't need any Javascript to create a tooltip... The Browser does that for you.

If you do want a custom tooltip, I would suggest creating an empty div that serves as tooltip, and then extract the text it displays from a Javascript Object.

For Instance:
HTML for the images

<img id="foo" src="http://localhost/foobar.jpg">

HTML for the tooltip. This can be anywhere as long as it is not a child of an Element it has to tip

<div id="tooltip">
   <h3></h3>
   <p></p>
   <em></em>
</div>

JavaScript

var my_object = new Object();
my_object['foo']['title'] = 'The almighty foobar';
my_object['foo']['description'] = 'Spy sappin\' mah Stack!';
my_object['foo']['source'] = 'Guide to the Universe';

Then, with jQuery

jQuery('img').hover(
   function() {
      var tip = jQuery('#tooltip');
      tip.find('h3').text(my_object[this.id]['title'];
      tip.find('p').text(my_object[this.id]['description'];
      tip.find('em').text(my_object[this.id]['source'];
      tip.show();
   },
   function() {
      jQuery('#tooltip').hide();
   }
).mousemove(function(e) {
   jQuery('#tooltip').css({
      'top': e.PageY + 10 + 'px',
      'left': e.PageX + 10 + 'px',
   })
}

This should work even without any Plugins.

Well actually you can put raw HTML into the title field. As long as you replace all quotes in the HTML with &quot; or use single quotes (like I did below).

I've used this tooltip in the past to do just that. The title contains the tooltip data that is displayed. And that script has been modified here to pull data from an assigned ID when it finds a flag in the title.

Here's an example of how to use this tooltip:

<a class="tooltip" href="http://www.google.com" title="<center><img src='http://www.google.com/logos/11th_birthday.gif'><br>Happy 11th Birthday Google!</center>">Google</a>
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!