Reputation: 153
I'm new to jQuery, and have found a code snippet that will scroll to a certain part of a page pointed to by local, or 'anchor' links.
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 500);
return false;
}
}
});
I understand that it must select links with local hrefs, but was wondering exactly what the difference is between the two 'clauses' of the selector.
Upvotes: 1
Views: 491
Reputation: 42304
The asterisk (*
) character after the attributes in jQuery denotes the attribute contains selector.
$('a[href*=#]:not([href=#])')
Breaking this down:
a
: Target all the <a>
tags[href*=#]
: Target all the href
attributes that contain #
.:not([href=#])
: Do not target href
attributes that have an href
value of exactly #
.So, in short, the selector targets any <a>
tags that contain a #
in their href
attribute where #
is not the only part of the href
attribute.
Considering URIs use hashes to denote IDs on the page, this allows the jQuery to scroll to an element on the page, rather than simply 'jump' to it.
Hope this helps!
Upvotes: 1
Reputation: 1913
a[href*=#]
gets all links that contains #
, but :not([href=#])
excludes links with exactly #
in their href
attribute.
This link will be selected:
<a href="http://www.example.com/here#top" title="">Link</a>
But this one not:
<a href="#" title="">Link</a>
Upvotes: 3
Reputation: 38318
The first rule will match any URL with a hash component, e.g. <a href="#jump-to-id">
The second not
rule filters out any URLs that are just an empty hash, e.g., <a href="#">
Upvotes: 3
Reputation: 4095
It matches anchors with an href
attribute that includes #
but is not only #
.
Upvotes: 3