1

I can't get $(target) to work.

If I click on a link with href=#top, alert(target) displays #top, but $(target).offset returns null.

$("[href^='#']").click( function() {
    var target = $(this).attr('href');
    alert(target);
    $("#body-wrapper").animate( {scrollTop: $(target).offset().top} ,300);
    return false
    })
};
2
  • I assume there's an element on your page <div id="top" /> and you're trying to retrieve the offset of that element? Commented Aug 10, 2011 at 0:55
  • Also, check out stackoverflow.com/questions/6993172/… for using data-elements instead of 'href'. The href-attribute should be reserved for true HTML hyperlink. Commented Aug 10, 2011 at 0:58

3 Answers 3

2

When you do:

$(target).offset()

You're essentially doing:

$("#top").offset()

But, you apparently don't have an object in your page with an ID of "top" (thus why it returns null). So, this could work if you gave the link with the name of top that ID also like this:

<a name="top" id="top"></a>

Or, instead, you could use this jQuery to look for the link tag with name="top":

target = target.slice(1);               // remove # from start of the name
$("[name='" + target + "']").offset()   // construct $("[name='top']");

Here you look for a tag with an attribute of name='top'.

Sign up to request clarification or add additional context in comments.

6 Comments

Just to say, it's probably easier to ask questions in comments rather than blindly guess what the issue is..
@jfriend00 - WOW! I never thought of that--and that's it. Spot on.
@jfriend00 - Would that mean this post should be deleted since the question is irrelevant?
@Alien Robert - I'm not sure what you think should be deleted. I was able to figure out what you were doing in your question (it took a few edits for me to get it right) and now you've got an answer. I don't think there's anything to delete here.
@jfriend00 - Fair. I'm still wondering if there's anyway to update the post so someone with my problem could find it in - but if they're as oblivious as I was, I guess that would defeat the purpose.
|
0

Use $(this).offset(). Your target var is just a string, not a jQuery object or a DOM node.

3 Comments

he has target wrapped in $() so it should be the same as doing $('#top').
The OP is not using target as a jquery object. He is doing $(target).
In his code, target is a string ("#top"), and the post doesn't say he also has an HTML element with id="top". I assumed he was looking for the offset of the link itself.
0

May be the element #top does not exist on the page. Try to alert $(target).length and see what you get.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.