Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery Show Div on Hover

Tags:

jquery

I'm trying to figure out how to use JQuery to display some tools when the user is hovering over a content block. For example, the blocks are displayed as follows with the tools initially hidden:

<div id="block_1">
    <div class="tools" style="display:none;">Tools Here</div>
</div>

<div id="block_2">
    <div class="tools" style="display:none;">Tools Here</div>
</div>

I need it to show the tools for block_1 when the user is hovering over anything in block_1.

I see that you can use wildcards to do something like:

$("*[id^=block_]").hover(
    function () {
        // somehow toggle div.tools for this block
    },
    function () {
       // somehow toggle div.tools for this block
    }

I just can't figure out how you can specifically toggle just the div.tools for that block...

like image 480
Frank Avatar asked Nov 01 '10 22:11

Frank


1 Answers

EDIT: Ultimately, if you're just doing simple style changes, you should use CSS to accomplish this. Not javascript.

This CSS won't work for IE6, but it will for pretty much all other modern browsers.

Give the parent block_ elements a class like block, remove the inline styles from tools, then do this:

.block .tools {
    display: none;
}
.block:hover .tools {
    display: block;
}

You could do this:

$(function() {
    $("div[id^=block_]").hover( function ( e ) {
        $(this).children('.tools').toggle(e.type === 'mouseenter');
    });
});

Although I think I'd add a common class to the block_ elements and select by that class:

$(function() {
    $("div.block").hover( function ( e ) {
        $(this).children('.tools').toggle(e.type === 'mouseenter');
    });
});

HTML

<div class="block" id="block_1">
    <div class="tools" style="display:none;">Tools Here</div>
</div>

<div class="block" id="block_2">
    <div class="tools" style="display:none;">Tools Here</div>
</div>

Inside event handlers, the keyword this refers to the element that received the event. In this case, the element with the block_n ID.

Then you use the .children() method to select child element(s) that have the tools class.

The .toggle() method can be used to show/hide elements. I've given it an argument that is the result of testing the type of event that took place. If the event was 'mouseenter', the .tools will be shown, otherwise it will be hidden.

The outer $(function() {...}); is a shortcut for wrapping your code in jQuery's .ready() method, which makes sure that your code doesn't run until the DOM is ready.

You can give the .hover() method two functions if you prefer. Then I'd use the .show() and .hide() methods instead of .toggle().

$(function() {
    $("div[id^=block_]").hover( function () {
        $(this).children('.tools').show();
    }, function () {
        $(this).children('.tools').hide();
    });
});
like image 184
user113716 Avatar answered Oct 27 '22 05:10

user113716