I am trying to truncate div headers. My function is buggy because of, I believe, variable scope.
Here is my function broken down:
- Set variables so they are scoped properly
- Loop through each div:
- Save long title
- Create truncated title
- Set truncated title
- On mouse enter, use full title
- On mouse leave, use truncated title
How can I rearrange this function so the variables are carried across correctly?
jQuery(document).ready(function($) {
eventHover();
});
function eventHover(){
// Set var scope
var title = '';
var shortText = '';
var longText = '';
// Change long titles to short version
$('#event_promo .panel').each( function() {
title = $(this).find($('h3 a'));
longText = title.html();
shortText = jQuery.trim(longText).substring(0, 50)
.split(" ").slice(0, -1).join(" ") + "...";
title.html(shortText);
});
// Add hover class and change title to long version
$('#event_promo .panel .trigger').mouseenter(function () {
$(this).parent().addClass('hover');
title.html(longText);
});
// Remove hover class and revert title to short version
$('#event_promo .panel .trigger').mouseleave(function () {
$(this).parent().removeClass('hover');
title.html(shortText);
});
}
I would suggest using the
data()method over “global” variables:Handle the data: