2

I have mutlilevel nested divs. Each div has a span in it.

<div>
    <span>AA</span>
    <div>
        <span>BB</span>
        <div>
            <span>CC</span>
        </div>
    </div>
</div>

If I hover a div, the spans css should get another background. This works pretty well, as long as i hover the most outer div, containting the AA span. But the problem is, if i hover the middle div, containing the BB span, the outer div hovers as well. If i hover the CC span div all three spans get the background.

What I want is, that only the one div which the mouse points at is hovered. I look preferably for a CSS solution, but jQUery would be great as well.

Here is a simplified jsfiddle of the problem: http://jsfiddle.net/FufRg/

1
  • 1
    Is it an option to use 3 seperate divs instead of nested divs? JSFiddle Commented May 15, 2013 at 8:37

3 Answers 3

1

In jquery this is easy. just stop propagation. jsFiddle

$("div").on("mouseover",function(e){
    $(this).children("span").css("background","#AAA");
    e.stopPropagation();
});
$("div").on("mouseout",function(){
    $(this).children("span").css("background","");
});
Sign up to request clarification or add additional context in comments.

Comments

0

I have create an example and it works for me. I have added jQuery and jQuery UI for background animation:

HTML:

<div class="a">
  <span>AA</span>
   <div class="b">
    <span>BB</span>
     <div class="c">
        <span>CC</span>
    </div>
</div>

CSS:

<style>

    .a{width: 400px;
         height: 400px;
         background: #000;}

    .b{width: 300px;
         height: 300px;
         background: #ddd;}

    .c{width: 200px;
         height: 200px;
         background: #efefee;}

</style>

jQuery:

<script>
$(document).ready(function(){


$('.a').hover(function(){

    $(this).find('*').animate({'backgroundColor': 'red'},400);

});

$('.b').hover(function(){

    $(this).find('*').animate({'backgroundColor': 'blue'},400);

});

$('.c').hover(function(){

    $(this).find('*').animate({'backgroundColor': 'yellow'},400);

});

});
</script>

Comments

0

Think in this way. If you enter a house, than into a room, than into the bed you are still in the house-> in the room -> in the bed. You cant say you are only in the bed, or only in the room. I think you get my point. If you hover over the CC div the hover will trigger on all the divs because you are already over the AA div and the bb div. The best solution is to use separate divs, not nested. Like Aquillo said.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.