Reputation: 3650
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">
</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
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
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
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