views:

181

answers:

2

I have added some code using prepend as you can see. Each of these items (the table cells) has a class called "predicate". When the user hovers over these I want to replace "predicate" with "predicate-over". I thought I had what I need below but it doesn't seem to work.

<script>
$(document).ready(function() {
  $("#leo-smart").hover(
        function() { $("#007").prepend("<img src='images/hand.gif' width='22' height='27' id='just-added' />"); },
        function() { $("#just-added").remove(); }
     );
  $("#007").hover(
        function() { $("#007").prepend("<a href='object.html' border='0'><img src='images/hand.gif' width='22' height='27' id='just-added' alt='View this object' />    </a>"); },
        function() { $("#just-added").$("#007").prepend("<img src='images/hand.gif' width='22' height='27' id='just-added' alt='View this object' />"); }
     );
  $("#leo-smart").click(
        function() { $("#more-options").prepend("<table><tr><td><div class='predicate'>is a</div></td></tr><tr><td><div class='predicate'>has famous work</div>   </td></tr><tr><td><div class='predicate'>has city (lived in)</div></td></tr><tr><td><div class='predicate'>has patron</div></td></tr><tr><td><div class='predicate'>has birthdate</div></td><tr><td><div class='predicate'>has birthcity</div></td></tr><tr><td><div class='predicate'>has nationality</div></td></tr></table>"); } 
  );
  $(".predicate").hover(
        function() { $(this).addClass("predicate-over"); },
        function() { $(this).removeClass("predicate-over"); }
     );
});

+1  A: 

You can use the prependTo function that returns a reference to the newly added element, in this way you don't need the 'just-added' id to find the element, for example:

$('<img src="images/hand.gif" width="22" height="27" />')
  .prependTo('#007')
  .hover(function () {/**/}, function () {/**/});
CMS
+2  A: 

I think the main idea is that if you're modifying the DOM (adding predicate classes) you need to be rebinding hover at that point.

$("#leo-smart").click(
  function() {  
    // do your table jazz
    $(".predicate").hover(
      function() { $(this).addClass("predicate-over"); },
      function() { $(this).removeClass("predicate-over"); }
    );
  } 
);

Some events in jQuery can be wired with the live event. When you wire up using live, jQuery will handle changes to the DOM for you. If you aren't using live and you are changing the DOM, you need to be wiring the after the DOM has been changed. The live event does support mouseover and mouseout - if you were to use those events instead of hover, you'd be able to wire them outside of the click event.

$(".predicate").live("mouseover", function() { 
  $(this).addClass("predicate-over");
});

$(".predicate").live("mouseout", function() {
  $(this).removeClass("predicate-over"); 
});
Andy Gaskell