user2758988
user2758988

Reputation: 139

Dynamic <ul> and <li> on hover in <ul> show <li>

I have 3 <ul> and each <ul> element have 1 hidden <li style="display:none;"> hover on 1 <ul> i want to show only <li> of which that <ul> is hover

Problem is that when i hover on 1 <ul> element it will hover on all 3 <ul> element and display all <li> element.

Below is my code

<html>
<head>
<script>
function chh()
{
    for (var i = 0; i < document.getElementsByTagName("ul").length; i++)
    {
        document.getElementsByTagName("ul")[i].onmouseover = function()
        {
            for (var i = 0; i < document.getElementsByTagName("li").length; i++)
            {
                document.getElementsByTagName("li")[i].style.display = "block";
            }
        }
    }
}
</script>
</head>
<body onLoad="chh();">
<ul>
Friend Request Sent
<li style="display:none;">Cancel Request</li>
</ul>
<ul>
Friend Request Sent
<li style="display:none;">Cancel Request</li>
</ul>
<ul>
Friend Request Sent
<li style="display:none;">Cancel Request</li>
</ul>
</body>
</html>

Demo :http://jsfiddle.net/vZeP4/

Upvotes: 0

Views: 1122

Answers (2)

3dgoo
3dgoo

Reputation: 15794

You can do this with css, without using any javascript.

HTML

<ul>
    <li class="message">Friend Request Sent</li>
    <li class="cancel">Cancel Request</li>
</ul>
<ul>
    <li class="message">Friend Request Sent</li>
    <li class="cancel">Cancel Request</li>
</ul>
<ul>
    <li class="message">Friend Request Sent</li>
    <li class="cancel">Cancel Request</li>
</ul>

CSS

ul {
    margin-bottom: 20px;
}

ul > .cancel {
    display: none;
}
ul:hover > .cancel {
    display: block;
}

Demo

Also, notice that I have put Friend Request Sent within an li. This is because all children of a ul must be an li. Having anything else in there is invalid html.

Upvotes: 5

Mohamed Khamis
Mohamed Khamis

Reputation: 8029

Your second loop goes through all the <li>s and sets their display to block. You need to pick the <li> that is inside the <ul> hovered upon.

A quick fix would be:

function chh()
{
    for (var i = 0; i < document.getElementsByTagName("ul").length; i++)
    {
        document.getElementsByTagName("ul")[i].onmouseover = function()
        {
            this.childNodes[1].style.display = "block";         
        }
    }
}    

Upvotes: 2

Related Questions