I have this jQuery function:
$('.scrollToLoginBox').click(function(){
$('html, body').animate({scrollTop: $("#LoginBox").offset().top-5}, 'slow');
});
I don't want it as a class, I'd like to be able to call it like this: onClick="scrollTo(id);"
So, how can I put the function in javascript format:
function scrollTo(id){
$('html, body').animate({scrollTop: $("#'+id+'").offset().top-5}, 'slow');
}
EDITED by publisher:
I don't hate you guys ;o) I appreciate all your answers, but I'm not trying to get the id. On the other hand, I'm trying to build the same function I published above. So, that on a click I will send the id (which I have Ex. Login or LoginBox), so that the function will scroll slowly to the anchor (id=Login or LoginBox).
Now I have to call it like this: class="scrollToLoginBox", instead I'd like to call it onClick="scrollTo('LoginBox');
I have 20 identical functions like the above, one for each id. Another example of what I have and I don't want is: class="scrollToSettings", instead I'd like to call it onClick="scrollTo('LoginBox'); or onClick="scrollTo('Settings');
$('.scrollToSettings').click(function(e){
$('html, body').animate({scrollTop:$("#settings").offset().top-5}, 'slow');
return false;
});
$('.scrollToFaqs').click(function(e){
$('html, body').animate({scrollTop:$("#formCode").offset().top-5}, 'slow');
return false;
});
I would like only one function that takes the id. I just don't know how to pass the id to this jQuery function ;o)
If you want to pass id to item being clicked, then you need to use this.id
Live Demo
onClick="scrollTo(this.id);"
If you want to pass id of some other control
then you simple pass the id as string.
onClick="scrollTo('idOfHTMLElement');"
Edit based on comments, for passing values from html elements to javascript function.
Data attributes are used for hold custom attributes and could be accessed in jQuery function use data() function.
Html
<div class="scrollToCal" data-idtopass="Anchor">click me to go to Anchor</div>
Javascript
jQuery(document).ready(function($) {
$('.scrollToCal').click(function() {
$('html, body').animate({
scrollTop: $('#' + $(this).data('idtopass')).offset().top - 5
}, 'slow');
return false;
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With