BBog
BBog

Reputation: 3650

jQuery mouseover not working for li element

I'm trying to make a menu based on an ul element that will show the link description underneath the link.

So far, I have the following code (simplified a little)

      echo '
<script>
        $("#menu_1").mouseover(function() {
            $("#description").replaceWith("test");
        });
</script>

<ul class="menu_top">
<li id="menu_1"><a href = "#">Test</a></li>
</ul>

<div id="description" class="menu_desc">&nbsp;
</div>

';

However, everytime I move the mouse over the li element, nothing happens.

Does anyone know what I'm doing wrong?

Upvotes: 3

Views: 4688

Answers (3)

nickf
nickf

Reputation: 546253

Javascript code is executed as it is encountered. This might happen before the document is actually ready. In your case, you're trying to select the #menu_1 element before it actually exists in the document. Because you almost certainly want all your jQuery code to run after the document is ready, jQuery provides a shortcut method for you:

$(function () {
    // this code is run only after the whole document is ready to go
    $("#menu_1")...
});

Upvotes: 3

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196177

#menu1 is not yet in the DOM when you run this code..

change it to

<script>
     $(function(){
        $("#menu_1").mouseover(function() {
            $("#description").replaceWith("test");
        });
      });
</script>

so that your code runs on document.ready event.

Upvotes: 4

Jamie Dixon
Jamie Dixon

Reputation: 54001

You need to make sure that your event assignment happens after the document has finished loading, otherwise your mouseover event has nothing to attach too:

$(document).ready(function(){

$("#menu_1").mouseover(function() {
            $("#description").replaceWith("test");
        });

});

Here's a working demo: http://jsfiddle.net/2mWb3/

Upvotes: 5

Related Questions