SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Wizard Wolf_22's Avatar
    Join Date
    Jul 2005
    Posts
    1,711
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question jQuery ready() and resize() in one?

    I have the following code:

    Code:
    var $parent_height = $(".group .field-item:first-child").height();//Get height of one of the containers...
    
    $(".group .field-items a").each(function(){
       //Get height of text by making temporary HTML container for it.
       var $child = $(this).html();
       var $temp = '<span>'+$child+'</span>';
       $(this).html($temp);
       delete $temp;
       var $child_height = $(this).find('span:first').height();
       $(this).html($child);
       //End get height of text...
    
       //If the link is taller than the parent, add class meant to assist with container height.
       if($child_height > $parent_height){
          $(this).addClass('addHeight');
       }
    
       //Otherwise, remove the class.
       if($child_height < $parent_height){
          $(this).removeClass('addHeight');
       }
    
    });

    Basically all it does is resize some wrapped links. It makes the list(s) I have on the page look better. Now, I would've gone down the CSS-only route, but this seemed to be a better approach.

    That aside, is it possible to run the above in both ready and resize contexts without duplication?

    Feedback is appreciated.

  2. #2
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,941
    Mentioned
    215 Post(s)
    Tagged
    12 Thread(s)
    Hi,

    Why don't you put that code in a function e.g. resizeLinks(), then you can do this:

    Code JavaScript:
    $(document).ready(function(){
      // Variables that you only need to declare once here
     
      function resizeLinks(){
        ...
      }
     
      $(window).on("resize", resizeLinks);
     
      resizeLinks();
    });

    If you put this code at the bottom of your document, just before your closing </body> tag, you can also do away with the call to $(document).ready(). See here as to why.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •