Search code examples
jqueryreplacecircular-reference

jQuery - removing part of text in table on smaller screens


I'm trying to create jQuery to abbreviate a part of my text in a table so it fits more easily on smaller devices. I've tried something like this:

jQuery(function($) {
$(window).load(function() {
    $(window).resize(function() {
        if ($(window).width() < 480) {
            $('td:contains("Hertford Hotshots")').text(function() {
                return $(this).text().replace("Hertford Hotshots", "Hotshots");
            });
        }
    });
});
});

But it doesn't revert back to the original string when I resize the window over 480px (I have to refresh the page) which is not ideal.

So I have tried:

jQuery(function($) {
$(window).load(function() {
    $(window).resize(function() {
        if ($(window).width() < 480) {
            $('td:contains("Hertford Hotshots")').text(function() {
                return $(this).text().replace("Hertford Hotshots", "Hotshots");
            });
        }
        if ($(window).width() >= 480) {
            $('td:contains("Hotshots")').text(function() {
                return $(this).text().replace("Hotshots", "Hertford Hotshots FC");
            });
        }
    });
});
});

But because the text I am changing to at <480px contains the same word (hotshots), it is creating a circular reference when resizing the page back up! Is there anything else I can try? (Maybe append?)

Thanks for your help!


Solution

  • Try

    $(function() {
      $(window).resize(function() {
        $('td:contains("Hotshots")').text(function() {
          return $(window).width() < 480?"Hotshots":"Hertford Hotshots";
        });
      });
    });
    

    This is likely a better idea:

    $(function() {
      $(window).resize(function() {
        $('.resizable').text(function() {
          return $(window).width() < 480 ? 
            $(this).data("short") :  
            $(this).data("long");
        });
      });
    });
    

    and have

    <td class="resizable" data-short="Hotshots" data-long="Hertford Hotshots">Hertford Hotshots</td>