First Last
First Last

Reputation: 133

hide and show without resizing the table element

comment without flag enter image description here

if you notice, above are comments in stackoverflow, the above image shows no flag while below image shows the flag shows when the mouse is hovering the comment. The flag is hide/show without resizing the table layout. But I have tried my own way by using below code but it still resizing.

<script>
$('document').ready(function()
{
    $('#hover').hover(function()
    {
        $('#flag').show();
    });
});
<table>
<tr>
    <td>
        <div id="hover">

            <div id="flag" style="display:none">
                <img src="flag.png"/>
            </div>
            
            <div>
                Hover me
            </div>
        </div>
    </td>
</tr>

Help me out here how to resolve this matter.

Upvotes: 1

Views: 2455

Answers (4)

creanium
creanium

Reputation: 647

In your CSS, you need to set an explicit width of the #flag element, then toggle the display of the img itself.

​#flag {
    width: 16px;
    height: 16px;
    float: left;
}

#flag > img {
    display: none;
}

Then your jQuery code gets adapted:

$(document).ready(function()
{
    $('#hover').mouseenter(function()
    {
        $('#flag > img').show();
    }).mouseleave(function()
    {
        $('#flag > img').hide();
    });
});

See this jsFiddle for it in action.

Upvotes: 2

Moses
Moses

Reputation: 9173

The problem is not with the code, but with the approach. Instead of having the div with a display:none you should have an empty div and then populate the content during the hover event. This is the approach that stackoverflow does, albeit with td instead of div.

Alternatively, you can change display:none to visibility:hidden, as the latter does not remove the item from the document flow, and therefore there will be no resizing when it is made visible.

Upvotes: 1

Simon Wang
Simon Wang

Reputation: 2943

try to change your HTML like following:

<table>
    <tr>
        <td>
          <div id="hover">

            <div id="flag" style="display:none;float:left;">
                <img src="flag.png"/>
            </div>

            <div style="margin-left:18px">
                Hover me
            </div>
          </div>
</td>
</tr>
</table>

DEMO: http://jsfiddle.net/9agPb/1/

Upvotes: 1

ShankarSangoli
ShankarSangoli

Reputation: 69915

hover takes 2 handlers for mouseenter and mouseout. When you pass only one handler, the same handler is executed for both the events. So in your case the flag will always be visible. You should pass another handler to hide the flag on mouseout. Another problem is you are using document as a string. Remove the quotes from your code.

$(document).ready(function()
{
    $('#hover').hover(function()
    {
        $('#flag').show();
    },
    function()
    {
        $('#flag').hide();
    });
});

Demo

Upvotes: 1

Related Questions