views:

18

answers:

1

Hi,

Am quite new to namespacing etc so hopefully this will be straightforward.

I have a variable in a jQuery hover function that needs to be made available to the global space.

To namespace my global variables i placed this code in a JS file that occurs before any other JS code:

$(function() {

    // Namespace
    jQuery.icisBoard = {};

});

I then have a tooltip function that occurs after this in a seperate JS file:

// Tooltip function
$(function() {

    $('.w_market_updates ul li a:contains("...")').addClass('tip_holder');

    $(".tip_holder").hover(function() {

        var $containerWidth = $(this).width();

        var $offset = $(this).offset();

        $.icisBoard.$thisTitle = $(this).attr('title');

        $('#icis_dashboard').prepend('<div id="tooltip">' + $thisTitle + '</div>');

        $(this).attr('title', '')        

        var $tipWidth = $('#tooltip').width();

        var $tipHeight = $('#tooltip').height();

        $('#tooltip').css({
            'display': 'block',
            'position': 'absolute',
            'top': $offset.top - ($tipHeight + 5),
            'left': $offset.left - ($tipWidth - $containerWidth) / 2
        });

    }, function() {

        $('#tooltip').remove();

        $(this).attr('title', $.icisBoard.$thisTitle) 

    });


});

This does not appear to work for me as know the hover functionality does not work. I am getting the scope all wrong? I am not even sure that the variable is available to the global scope anyway in this instance and if i just have $thisTitle instead of $.icisBoard.$thisTitle the functionality works.

+1  A: 

Change this line:

$('#icis_dashboard').prepend('<div id="tooltip">' + $thisTitle + '</div>');

to

$('#icis_dashboard').prepend('<div id="tooltip">' + $.icisBoard.$thisTitle + '</div>');

You don't have a variable $thisTitle.

See here: http://jsfiddle.net/qna7W/

(I changed it a bit, otherwise the tooltip would not have been in the view)

Felix Kling
Thanks.Sorry my eyes glazed over that one.Is there any way to extend the global object. For example if i wanted to have multiple global variables under the Tooltip function e.g.$.icisBoard.tooltip.$thisTitle
RyanP13
@RyanP13: Sure, you just have to assign an object to `$.icisBoard.tooltip`, i.e. `$.icisBoard.tooltip = {}`. One further note: You don't *have to* add this "namespace" to the jQuery object. You could just create a global variable `icisBoard`.
Felix Kling