ElementalStorm
ElementalStorm

Reputation: 828

jquery: mouseover load state

I want to have an element with a fixed, small height that expands to his full height on a mouseover and shrinks back when mouse leaves.

Doing something like:

    $(".element").each(function() {
    $.data(this, 'size', { width: $(this).width(), height: $(this).height() });
}).hover(function() {
    $(this).stop().animate({ height: $.data(this,'size').height, 
                             width: $.data(this,'size').width });
}, function() {
    $(this).stop().animate({ height: 40, 
                             width: $.data(this,'size').width });
}); 

...works, but on page load the element starts at full height.

What is the best way to have it shrinked on page load ?

Upvotes: 2

Views: 194

Answers (3)

Ken Redler
Ken Redler

Reputation: 23943

You've stated that the height of each element is not known in advance. So one of your issues is how to capture the natural height of each element at load time, but still find a way to only show that element after it's been shrunk to its fixed collapsed size (avoiding a brief display of each at its full size).

One possible strategy is to render the objects at their natural sizes, but outside the viewport -- for example, shifted -1000 pixels horizontally. Capture and store their dimensions, then shrink them to their fixed 40px height, and then finally reposition them back into their regular in-viewport positions. If all the objects are in some kind of container element, you can simply shift that element.

Upvotes: 0

dku.rajkumar
dku.rajkumar

Reputation: 18588

try it like this, it is better to understand. check fiddle example. In this way you can even add other animation effect like changing background color .....

CSS:

.div_small_height{
 height : 20px;
 width : 500px;
 background-color : red;
 overflow : hidden;
}
.div_full_height{
   width : 500px;
   background-color : blue;
}

Jquery:

$(".element").addClass('div_small_height'); // shrink it on page load
 // change on mouseenter and mouse leave
$(".element").hover(function(){
    $(this).switchClass("div_small_height","div_full_height",500);
},function(){
    $(this).switchClass("div_full_height","div_small_height",500);
});

fiddle example : http://jsfiddle.net/7PV98/

Upvotes: 2

mrtsherman
mrtsherman

Reputation: 39902

You can shrink them after page load by calling your hoverout code when the document is ready. You may want to animate them to make it look good in case they are rendered. Or you may want to just set the height directly.

$(document).ready( function() {
   $('element').each( function() {
      //store height and width
       $.data(this, 'size', { width: $(this).width(), height: $(this).height() });
      //shrink it
      $(this).animate({ height: 40, width: $.data(this,'size').width });
   });
});

I'd be curious to see if there is a way to do this without animating after load though.

Upvotes: 0

Related Questions