Search code examples
javascriptdomtooltip

Identify Objects without ID or specific attributes


I'm trying to create popups from hovering above elements. The popups shall be created / loaded after hovering for the first time.

Every hover after the initial should not create a new element, but re-open the already created one.

The elements i'm hovering about do not have an ID or a class therefore, i cannot store these in an array for example.

$( ".tooltip-enabled" ).hover(
        function() {
            // Tooltip already exists? 
            // ...
            createToolTip($(this));
        }, function() {
            closeToolTip($(this));
        }
);

The shown code will always create a new Tooltip. Is there a way to store which object I already hovered above?


Solution

  • The shown code will always create a new Tooltip. Is there a way to store which object I already hovered above?

    Yes there is. You can make use of $.fn.data which will store a counter.

    $(".tooltip-enabled").hover(function() {
        if ($(this).data('hovered'))
           createToolTip($(this));
        else {
           $(this).data('hovered', true); // set it here
           openToolTip($(this));
        }
    },  function() { closeToolTip($(this)); });
    

    Note that, to keep the code succinct, I've omitted the brackets around if and else. You need to use brackets if your code spans more than one statement.