implementing a jQuery “click to expand” link in WordPress [closed]

You’ll need to load jQuery and your custom script file into WordPress first. Do this using wp_enqueue_scripts. Put this in functions.php in your theme directory. Make sure the path to the script file (I called it main.js here) is correct for your environment.

function mytheme_load_js() {

  // load in jquery
  wp_enqueue_script( 'jquery' );

  // register and load site js
  wp_register_script( 'mytheme_js', get_template_directory_uri() . '/js/main.js', '', '1.0', true );
  wp_enqueue_script( 'mytheme_js' );
  return true;
}

// load js
add_action( 'wp_enqueue_scripts', 'mytheme_load_js' );

This will load jQuery and your custom javascript into the footer. If the last argument in wp_register_script is set to true the script will be injected in place of wp_footer in your template files, otherwise it will go into the header where wp_header.

Now, the jQuery you posted is pretty close to what you need. here’s the JS to expand the div. This could be adapted to both expand and shrink the div if it needs to be toggle-able, but I’m just going to go over how to expand. All you should really have to change here is the name of the div containing the friends.

var $friends = $( '.buddypress-friends' );
$( document ).ready( function() { // wait until the DOM is loaded...
  $friends.on( 'click', function( e ) {
    var current_height = $( this ).outerHeight(); // get the current height of the friends div
    var new_height = $friends[0].scrollHeight; // get the actual height of the div as if a max-height or height were not set
    var animation_duration = 500; // duration in milliseconds for the animation to last
    $friends.css({ height: current_height, maxHeight: new_height }) // set the initial height and the max-height of the friends div. Since these are defined inline they will override properties set in your stylesheet
            .animate({ height: new_height }, animation_duration ); // animate the new height
  } );
} );

While the above JS would work just fine I’d suggest removing the .animate portion of the script and letting CSS do the animation since CSS animations are typically faster and smoother.

.buddypress-friends{
  max-height: 100px;
  -o-transition: all .5s ease;
  -ms-transition: all .5s ease;
  -moz-transition: all .5s ease;
  -webkit-transition: all .5s ease;
  transition: all .5s ease;
}