tsujp
tsujp

Reputation: 1096

Javascript Getting Span Contents Upon Mouse Event

I have the following markup that I am applying the succedding Javascript to in order to produce a tooltip, the problem is I am trying to set the contents of the tooltip to the contents of the span.

I cannot figure out a way of doing this without 500 different document.get etc...

Basically I want to know: In the showTooltip function, how can I get the contents of the span dynamically?

Markup:

<ul class="exec-List">
                    <li>
                        <img src="file:///C|/Users/tsujp/Documents/Everything/Adobe Projects/DW/KCC/Website/V8/src/committee/mirae.png" /> 

                        <span class="tooltip-span">Conten2t</span>

                    </li>
                    <li>
                        <img src="file:///C|/Users/tsujp/Documents/Everything/Adobe Projects/DW/KCC/Website/V8/src/committee/mirae.png" /> 

                        <span class="tooltip-span">Content55</span>

                    </li>
                </ul>

Javascript:

$(document).ready(function() {

var changeTooltipPosition = function(event)
{
  var tooltipX = event.pageX - 8;
  var tooltipY = event.pageY + 8;
  $('div.tooltip').css({top: tooltipY, left: tooltipX});
};

function showTooltip(event/*, index, el*/)
{
    /*alert( $(this).parent(this).get(0).tagName );*/

    $('div.tooltip').remove();
    $('<div class="tooltip">/* + tooltip_text +*/ </div>')
        .appendTo('body');
    changeTooltipPosition(event);
};

var hideTooltip = function()
{
   $('div.tooltip').remove();
};

$('span').each(function()
{
    if( $(this).hasClass( 'tooltip-span' ) )
    {                       
        //tooltip_text = $(el).html();

        $(this).parent(this).bind(
        {           
            mousemove : changeTooltipPosition,
            mouseenter : showTooltip/*( HOW DO I PASS 'EVENT' HERE)*/,
            mouseleave: hideTooltip
        });
    }
});

});

Upvotes: 1

Views: 213

Answers (1)

Olaf Dietsche
Olaf Dietsche

Reputation: 74028

You can select on $('.tooltip-span', this) and take the text()

function showTooltip(event/*, index, el*/)
{
    var text = $('.tooltip-span', this).text();
    /*alert( $(this).parent(this).get(0).tagName );*/

    $('div.tooltip').remove();
    $('<div class="tooltip">' + text + '</div>')
        .appendTo('body');
    changeTooltipPosition(event);
};

JSFiddle

Upvotes: 1

Related Questions