Here’s what I started out with,
$("a[href='#top']").click(function() {
$("html, body").animate({ scrollTop: 0 }, "slow");
return false;
});
Which works great with
<a href="#top">...</a>
However, I need something similar that works without a link, something like…
<li id="top">....</li>
I tried this
$("#top").click(function() {
$("html, body").animate({ scrollTop: 0 }, "slow");
return false;
});
But it doesn’t work on my end.
The issue is in your HTML, not your JavaScript. It is not valid to have two elements with identical
idattributes in your HTML. jQuery (actually the underlying JavaScript) will only select the first of these elements when the ID selector is used, so#topselects the<a>. Your selector ofli#topis more restrictive, but you can see a similar effect if you reverse the element order: http://jsfiddle.net/WRmPz/10/It is imperative that all of your elements have unique IDs for this and many other reasons.
By the way, the
return falseis not necessary for the<li>, (nor would it be necessary for<a>withouthref). If you were to use the latter, it would be better to pass in the event object and calle.preventDefault(): http://fuelyourcoding.com/jquery-events-stop-misusing-return-false/