JQuery UI tooltip with a close link for mobile
Here is the JQuery code I use to to set up JQuery UI tool tips with a close link that only appears on mobile platforms. This is useful because on a desktop, the tool tip will close when you mouseout
from the target element, but on a touch platform it sticks around.
// Set up tool tips for images and anchors. $( document ).tooltip({ items: "a[title], img[alt], .toolTip[title], :not(.noToolTip)", track: true, position: { my: "left+15 center", at: "right center" }, content: function() { var element = $( this ); var closer = closerLink = ''; if (isMobile()) { closer = ' <br><div onClick="$(this).parent().parent().remove();" style="color: blue; text-decoration: underline; text-align: right;">Close</div>'; closerLink = ' <br>Tap link again to open it.<br><div onClick="$(this).parent().parent().remove();" style="color: blue; text-decoration: underline; text-align: right;">Close</div>'; } // noToolTip means NO TOOL TIP. if ( element.is( ".noToolTip" ) ) { return null; } // Anchor - use title. if ( element.is( "a[title]" ) ) { return element.attr( "title" ) + closerLink; } // Image - use alt. if ( element.is( "img[alt]" ) ) { return element.attr( "alt" ) + closer; } // Any element with toolTip class - use title. if ( element.is( ".toolTip[title]" ) ) { return element.attr( "title" ) + closer; } } }); function isMobile() { return (/iPhone|iPod|iPad|Android|BlackBerry/).test(navigator.userAgent); }
I am targeting three types of things here:
- Anchor tags (
a
) with atitle
attribute. - Image tags (
img
) with atitle
attribute. - Any element with class
toolTip
. - And specifically exclude any element with class
noToolTip
.
You can see this in action on my newly refreshed site: Chihuahua Rescue Victoria.