views:

339

answers:

3

I have a function that prepends a li tag to a parent div just fine...however, after the prepend, i want to act upon this prepended list item by changing css properties when hovered on but the jQuery selector can't find it (seemingly because the .hover function is searching for list items available to act upon when the page loads..and the prepended items are nonexistent when the page loads).

My prepend code looks like this:

$("div#content-text div#sub-text").prepend(
"<li id='item1' class='contents-rec'><div class='text'></div></li>");

while my hover code (not working) looks like this:

$("div#content-text div#sub-text li.contents-rec").hover(function(){
$(this).css({border:'1px solid #fff'});
}, function(){
$(this).css({border:''});
},0);

any help would be greatly appreciated!! thanks in advance

A: 

Are you executing this line...

$("div#content-text div#sub-text li.contents-rec").hover(function(){ $(this).css({border:'1px solid #fff'}); }, function(){ $(this).css({border:''}); },0);

After this one...

$("div#content-text div#sub-text").prepend( "");

If so it should be there.

Also check out the live() method. here

ctrlShiftBryan
A: 

The code you're showing doesn't actually prepend anything, so I'm assuming that you just left it out for ease of posting. (We can help you much better if you post actual working code, though.)

Then, make sure that your hover code is running after the prepend code. If that isn't happening, you'll need to adjust things somehow. (Maybe with setTimeout(...).)

JQuery's live() could help, but version 1.3.x doesn't support "hover" in the live() binding.

John Fisher
I'm guessing the `<li>` tag that is being appended is not visible because the code text is not formatted as code.
patrick dw
f.y.i my code does prepend the entire li tag...<li id='item1' class='contents-rec'><div class='text'></div></li>
sadmicrowave
+2  A: 

If you are dynamically inserting an element after the hover event has already been assigned on the page load, you can use live() in that situation (jQuery 1.4.1 or greater required for 'hover' parameter):

$("div#content-text div#sub-text li.contents-rec").live('hover',
    function(event) { 
        if (event.type == 'mouseover') {
            $(this).css({border:'10px solid orange'}); 
        } else {
            $(this).css({border:''}); 
        }
});
patrick dw
.live() works!!!the only problem (probably because .live() changes the .hover syntax) is that hovering on the li.contents-rec changes the border to 1px solid #fff but does'nt change it back when I hover off.f.y.i - there is no need for me to post the code because it is the exact same as Patrick has above.
sadmicrowave
Sorry. I've updated my answer. I thought `live('hover',...)` would accept two functions. Apparently not. (At least 1.4.2 doesn't work that way.) See the code above.
patrick dw
AWESOME!! Thanks so much for your help..this forum rocks!
sadmicrowave