Basic
Basic

Reputation: 26766

JQuery Selector issue (I think)

I've got the script below

<script type="text/javascript">
    $(document).ready(function () {
        var ChildMenusFound = $(".menu_Child").hover(function () {
            //Mouse Over
                            alert('ok');
            $(this).toggleClass("menu_hover");
        }, function () {
            //Mouse Out
                            alert('ok');
            $(this).toggleClass("menu_hover");
        });
    });
</Script>

The html I'm outputting is as follows:

<ul alt="" class="menu_Root">
<li class="menu_Child>"
<a href="/Admin" alt="">Admin</a>
<ul alt="" class="menu_Child">
<li class="menu_SubMenu>"
<a href="/Admin/Statistics" alt="">Statistics</a></li>
<li class="menu_SubMenu>"
<a href="/Admin/Database" alt="">Database</a></li>
</ul></li>

<li class="menu_Child>"
<a href="/MyAccount" alt="">My Account</a>
<ul alt="" class="menu_Child">
<li class="menu_SubMenu>"
<a href="/MyAccount/Profile" alt="">Profile</a></li>
</ul></li>

</ul>

after the call to hover(),ChildMenusFound contains 2 elements, firefox shows no JS errors, yet mouseover/out of the li elements doesn't cause anything to happen.

Can someone please identify my mistake?

Upvotes: 0

Views: 73

Answers (4)

Patrick Ferreira
Patrick Ferreira

Reputation: 2053

Be careful, you have inverted two characters :

<li class="menu_Child>"

needs to became

<li class="menu_Child">

Upvotes: 1

user113716
user113716

Reputation: 322492

Other answers noted your broken HTML markup.

One thing to consider may be to use CSS instead of javascript to do your hover. It won't work in IE6 unless it is on an <a> element, but it will in most other browsers.

.menu_Child {
   background: yellow;
}

.menu_Child:hover {
   background: orange;
}

Not sure what the effect is you're going for, but if you can change the hovered element to the <a>, it will work in IE6 as well.

Upvotes: 1

Nick Craver
Nick Craver

Reputation: 630409

Your HTML is a bit off, you have classes unclosed (or wrongly closed) like this:

<li class="menu_Child>"
                      ^ here

It should be:

<li class="menu_Child">

Here's the fixed/working version, you can slim your code down though, like this:

$(function () {
  $(".menu_Child").hover(function () {
    $(this).toggleClass("menu_hover");
  });
});

With a single callback passed to .hover() it's called in both in/out directions, and since you're toggling you can save code here.

Upvotes: 2

Pointy
Pointy

Reputation: 413717

Your markup is broken. You've got quote marks outside the tags. It also looks like you're missing a </li> somewhere for that first outer </li> but it's hard to tell.

Upvotes: 4

Related Questions