theorise
theorise

Reputation: 7445

Using vars across functions with .each()

I am trying to truncate div headers. My function is buggy because of, I believe, variable scope.

Here is my function broken down:

  1. Set variables so they are scoped properly
  2. Loop through each div:
    • Save long title
    • Create truncated title
    • Set truncated title
  3. On mouse enter, use full title
  4. 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);
    });

}

Upvotes: 1

Views: 72

Answers (1)

Johan
Johan

Reputation: 35213

I would suggest using the data() method over "global" variables:

$('#event_promo .panel').each( function() {

    var $title = $(this).find('h3 a');
    var longText = title.html();

    var shortText = jQuery.trim(longText).substring(0, 50)
        .split(" ").slice(0, -1).join(" ") + "...";

    $title.html(shortText);

    $(this).data({ shortText: shortText, longText: longText });
}); 

Handle the data:

$('#event_promo .panel .trigger').mouseenter(function () {

    var longText = $(this).closest('.panel').data('longText');
    var shortText = $(this).closest('.panel').data('shortText');

    //do stuff with the texts here

});

Upvotes: 2

Related Questions