Search code examples
javascripthtmljquerytooltipjquery-events

JQuery HasAttribute Selector with Attribute Length


Currently I'm developing a custom tooltip for my website. It's a heavy one, so it has around 300 elements with title on every page. And It's working well with this code:

var title="";
$( document ).delegate( "[title]", "mouseover", function ( event ) {
    title = $( this ).attr( "title" );
    $( "#tooltip-div" ).delay( 250 ).animate( { top: newTop, opacity: 1 }, 'fast' );
 } );
    

But the problem I'm facing is: Unfortunately, there are many elements in the page which have the title attribute, but empty. For example:

<input type="image" id="clearBtn" title="" src="../../Images/unsearch.png" onclick="clearFilter();">
    

For this element, my custom tooltip is showing up with an empty value. So I was wondering if there is any way to select elements which have the 'title' attribute and that attribute is not empty.

So I want to exclude the elements like the one I show above. Is there a way to do that directly using a JQuery Selector, to make sure that I bind the event only to my desired elements, other that checking the length of title attribute inside the event handler.


Solution

  • Here's a possible solution, requiring a [title], and a [title!=''].

    var title="";
    $( document ).delegate("[title][title!='']", "mouseover", function ( event ) {
        title = $( this ).attr( "title" );
        $( "#tooltip-div" ).delay( 250 ).animate( { top: newTop, opacity: 1 }, 'fast' );
    });