|
Things have been busy! I’m working on a new book and site and having a blast. I’ll share more on that later, but for now I just want to get back into posting at Perishable Press. To kick it into gear, here is one of the jQuery snippets I’m using at the new book site.
jQuery Hover Swap Text
There is probably a better way to do this, but I needed a way to swap link text with the title attribute on hover. Nothing fancy, and I thought for sure there would be an easier/existing way of doing this with jQuery, but didn’t see anything so came up with this lil’ snippet:
// jQuery hover swap text @ http://perishablepress.com/jquery-hover-swap-text/
function xycss_swap_text(){
$('a').hover(function(){
var title = $(this).attr('title');
var text = $(this).text();
$(this).text(title).attr('rel', text).removeAttr('title').wrapInner('<span />');
},function(){
var title = $(this).text();
var text = $(this).attr('rel');
$(this).text(text).attr('title', title);
});
}
$(document).ready(function(){
xycss_swap_text();
});
Just drop into your JavaScript file and edit the $('a') selector with your choice. Going thru, this is just a jQuery hover function that swaps the contents of the title attribute with the anchor text. I also wrap the hover text with a <span> (for styling purposes), but you can yank that out of there if it’s not needed.
Update:
Bryan Watson extends this snippet into more of a plugin format:
(function($){
// Swap text with title attribute
$.fn.swapTitleAttr = function() {
var title = this.attr('title');
var text = this.text();
$(this).wrapInner('<span />');
$(this).hover(function(){
$(this).text(title).attr('rel', text).removeAttr('title');
},function(){
$(this).text(text).attr('title', title).removeAttr('rel');
});
};
})(jQuery);
$(document).ready(function(){
$('a').swapTitleAttr();
});
As Bryan explains, with this version “the vars are outside of the hover function (and don’t need to be redefined). Plus, it makes the function reusable for any selector with a title attribute.”
Better way?
Drop some hints if you know an easier way of doing this — I’m sure there’s a better way :)
© 2011 Perishable Press Read more: |