I'm not sure why my event isn't firing? I simply want to change the list style type when the user hovers over an li. It doesn't look like I'm missing anything, but nothing is happening.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<link href="theme.css" rel="stylesheet" type="text/css" />
</head>
<script type="text/javascript">
$(".component ol li").hover(function() {
$(this).css('list-style-type', 'disc');
}
);
</script>
<body>
<form id="form1" runat="server">
<div class="component">
<ol>
<li><a href="#"></a> </li>
<li><a href="#"></a> </li>
<li><a href="#"></a> </li>
<li><a href="#"></a> </li>
<li><a href="#"></a> </li>
</ol>
</div>
</form>
</body>
</html>
<script type="text/javascript">
$(document).ready(function() {
$(".component ol li").hover(function() {
$(this).css('list-style-type', 'disc');
}
);
});
</script>
If you don't have the document.ready, that gets executed before your list items get added to the DOM, so it basically does nothing. Or move that whole section to after the list items.
EDIT: per further discussion: It is best practice to not use document.ready
, since it has to wait for everything on the page to finish loading to run. With that said, you can always put these 'initializing' blocks at the end of the html to make sure that all DOM objects are created when this is executed.
Or the second object is to use .live()
. This function will attach an event to the result of the selector whenever an element that fits the selector is created. Now you can keep this block at the top and use:
<script type="text/javascript">
$(".component ol li").live('hover', function() {
$(this).css('list-style-type', 'disc');
});
</script>
Now anytime something matches $(".component ol li")
is added to the DOM, your hover function will get attached.
First I would recommend using
$(document).ready(function(){
//your code here
});
This should solve your problem.
Besides this, to further enhance performance you can bind the event to a top level element say a UL instead of each LI. This would help you extract better performance too. Since you are using jQuery 1.4.2, you can easily use jQuery delegate for this.
Feel free to clarify any doubts.
Thanks,
Pranav Kaushik
pranavkaushik.wordpress.com
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With