1

I am trying to write a simple hover function (please don't suggest another, I have specific needs). I have the hover work so that it will show to the right of the list item that it is hovering. The style of the page shows a left navigation where the ul background looks like a solid block. This means that I need my hover to be to the right of the whole ul, not just the li I am over incase it is a short one. I am trying to get the parent of the li, but I am getting an error this.parent is not a function. How do I get the parent ul of a li so I can get it's position.

my li has a class of .left-nav-item

this.myhover = function () {
this.xOffset = -10; // x distance from mouse
this.yOffset = 10; // y distance from mouse       

$(".left-nav-item").unbind().hover(
function (e) {
this.top = (e.pageY + yOffset);
this.left = (e.pageX + xOffset);

alert(this.title);
this.parent().css('background-color', 'red');

$('body').append('<p id="new">My Hover Text</p>');
$('p#new').css("top", this.top + "px").css("left", this.left + "px").css("position", "absolute").fadeIn("slow");
},
function () {
//$("p#new").fadeOut("slow").remove();
}
).mousemove(
function (e) {
this.top = (e.pageY + yOffset);
this.left = (e.pageX + xOffset);
//$("p#new").css("top", this.top + "px").css("left", this.left + "px");
}
);

};

jQuery(document).ready(function ($) { myhover(); });
user957863
  • 325
  • 2
  • 4
  • 10
  • Could you post some of your code? It would be much easier than to help! – r0skar Sep 30 '11 at 16:05
  • Also, you can make sure you wrap it in a jQuery selector (since we can't see what this is): $(this).parent(). – orolo Sep 30 '11 at 16:09

3 Answers3

10

Your question:

How do I get the parent ul of a li so I can get it's position.

$('your li').closest('ul');
orolo
  • 3,951
  • 2
  • 30
  • 30
4

Try -

$(this).parent().css('background-color', 'red');

parent() is a jQuery function and will only work with a jQuery wrapped element.

ipr101
  • 24,096
  • 8
  • 59
  • 61
  • Thanks, that worked. Why do I need $(this) here, but I can also do alert(this.title) and it will work? – user957863 Sep 30 '11 at 17:00
  • It's because `this` is a normal JavaScript DOM object, which does have a `title` property. When you wrap `this` in the jQuery `$()` then you get access to all the jQuery functions. There's further info in this question - http://stackoverflow.com/questions/6965979/what-is-the-difference-between-this-and-this-in-jquery/6966030#6966030 – ipr101 Sep 30 '11 at 18:33
  • BTW, if my answer did solve your problem could you please accept it by clicking the tick? Thanks :) – ipr101 Sep 30 '11 at 18:35
0
$('li.left-nav-item').parent();
Cliff
  • 1,621
  • 1
  • 13
  • 22