How to make jQuery .click function more scaleable
I am having a little trouble getting this to work. I have several anchor tags on a page that use scrollTop for its animation. HTML example
link
开发者_如何学C<a id="TOS" href="#Svc">What are your terms of service?</a>
and the target
<div class="tabWrapp" name="TOS" id="Svc">
<!-- /tos tabWrapp --></div>
and the jquery
$('a#TOS').bind('click',function() {
var pos = $('#Svc').offset().top;
$('html,body').animate({scrollTop : pos}, 500);
return false; //stops navigation from adding the id to the url
});
Now this gets quite bloated having 30+ of these on the same page. Could I modify the code to apply a class to the anchor and make a variable out of the url like so
$('.foo').bind('click', function() {
var href = (this).attr('ID');
var pos = href.offset().top;
$('html,body').animate9{scrollTop : pos}, 500);
return false;
});
the issue Im having is targeting the anchor ID inside the href var and then placing that inside the pos var...thx
You can give all those links the same class, like this:
<a class="scrollTo" href="#Svc">What are your terms of service?</a>
Then make your function bind to that class, like this:
$('a.scrollTo').bind('click',function() {
var pos = $(this.hash).offset().top;
$('html,body').animate({scrollTop : pos}, 500);
return false;
});
This binds to all the links but uses the .hash
of the link you clicked on to get the scrollTop destination.
If I understand correctly what you mean, yes you can. You have to use the hash function in javascript.
So for your markup, if you have
<a class="foo" id="TOS" href="#Svc">What are your terms of service?</a>
This JS will alert "#Svc" :
$('a.foo').click(function() {
alert(this.hash);
});
So in your example, use it to make :
$('a.foo').click(function() {
var pos = $(this.hash).offset().top;
$('html,body').animate({scrollTop : pos}, 500);
return false;
});
By the way, you can use
.click(function() {});
as a shortcut for
.bind('click', function() {});
More details here
I haven't used the ID for that kind of thing before but maybe you could try using title
instead? And then you would just use it in the selector like $(my_title).offset().top
. Hope that helps.
You have to find the element by Id first:
$('.foo').bind('click', function() {
var href = $(this).attr('ID');
var pos = $('#'+href).offset().top;
$('html,body').animate({scrollTop : pos}, 500);
return false;
});
adding $('#element')
around the href
should do it, no?
Try this:
$('a[ID]').bind('click', function() {
var href = $(this).attr('href');
var pos = $(href).offset().top;
$('html,body').animate({ scrollTop : pos}, 500);
return false;
});
Worked for me. I adjusted the href var. Pretty sure that was it. a[ID]
as a selector targets any anchors with IDs.
精彩评论