Add Multiple Elements to Page
Hello,
I have created a JQuery tooltip plugin and I am applying it to a few A tags.
For each A tag there should be a different tooltip associated with it so I have:
- var $tooltip = $("<div>").attr("id", tooltip.id).attr("class", options.class).appendTo('body');
Where the tooltip id includes a random number created as follows:
- id: "Tooltip_" + Math.floor(Math.random() * (9999 - 2000 + 1) + 2000)
The plugin does not behave well. I checked the HTML added to the page.
Only one tooltip is being added to the page ... Always the same.
How can I fix this? What am I doing wrong?
I have an example in: http://codepen.io/mdmoura/pen/wgapv
And the plugin code is the following:
- $(document).ready(function () {
- $("table a").Tooltip();
- });
- // Tooltip
- (function ($) {
-
- $.fn.Tooltip = function (options) {
- var defaults = {
- class: 'Tooltip',
- delay: [200, 200],
- offset: [0, -10],
- hide: function ($element, $tooltip) {
- $tooltip.fadeOut(200);
- },
- show: function ($element, $tooltip) {
- $tooltip.fadeIn(200);
- }
- };
- var options = $.extend({}, defaults, options);
- var tooltip = { id: "Tooltip_" + Math.floor(Math.random() * (9999 - 2000 + 1) + 2000), ready: false, timer: null, title: '' };
- $(this).each(function (e) {
- var $this = $(this);
- tooltip.title = $this.attr('title') || '';
- $this.mouseenter(function (e) {
- if (tooltip.ready) {
- var $tooltip = $("#" + tooltip.id);
- } else {
- var $tooltip = $("<div>").attr("id", tooltip.id).attr("class", options.class).appendTo('body');
- $tooltip.html(tooltip.title);
- tooltip.ready = true;
- $this.attr('title', '');
- }
- var position = [e.clientX + options.offset[0], e.clientY + options.offset[1]];
-
- $tooltip.css({ left: position[0] + 'px', top: position[1] + 'px' });
- tooltip.timer = window.setTimeout(function () {
- options.show($this, $tooltip.stop(true, true));
- }, options.delay[0] || 0);
-
- $("#" + tooltip.id).mouseenter(function () {
- window.clearTimeout(tooltip.timer);
- tooltip.timer = null;
- }); // Tooltip enter
-
- $("#" + tooltip.id).mouseleave(function () {
- tooltip.timer = setTimeout(function () {
- options.hide($this, $tooltip);
- }, 0);
- });
-
- }), // Mouse enter
-
- $this.mouseleave(function (e) {
- tooltip.timer = setTimeout(function () {
- options.hide($this, $("#" + tooltip.id).stop(true, true));
- }, options.delay[1] || 0);
- }) // Mouse leave
- }); // Each
- }; // Tooltip
-
- })(jQuery); // JQuery
And the HTMl is the following:
- <table>
- <tr><td><a href="#" title="Tooltip 01 Text">Tooltip 01</a></td></tr>
- <tr><td><a href="#" title="Tooltip 02 Text">Tooltip 02</a></td></tr>
- <tr><td><a href="#" title="Tooltip 03 Text">Tooltip 03</a></td></tr>
- <tr><td><a href="#" title="Tooltip 04 Text">Tooltip 04</a></td></tr>
- <tr><td><a href="#" title="Tooltip 05 Text">Tooltip 05</a></td></tr>
- </table>
Thank you,
Miguel