Reputation: 317
I've basically written a script that will animate the window to a selected element however I found myself writing this 5 times for each link.
e.g: This is the HTML (just a standard nav)
<nav>
<a class="nav_link1"></a>
<a class="nav_link2"></a>
<a class="nav_link3"></a>
</nav>
$('.nav_link1').click(function(event){
event.preventDefault();
$('html, body').animate({scrollTop: $('#section_link1').offset().top}, 300);
})
$('.nav_link2').click(function(event){
event.preventDefault();
$('html, body').animate({scrollTop: $('#section_link2').offset().top}, 300);
})
$('.nav_link3').click(function(event){
event.preventDefault();
$('html, body').animate({scrollTop: $('#section_link3').offset().top}, 300);
})
I was wondering how I could use a defined array (each) to consolidate this into one block.
Can this be done?
var linkitem = ['link1','link2','link3']
$('.nav_linkitem').click(function(event){
event.preventDefault();
$('html, body').animate({scrollTop: $('#section_linkitem').offset().top}, 300);
})
Upvotes: 0
Views: 54
Reputation: 7909
Try using comma delimited selectors and the "this" keyword.
$("body").on("click", "#section_link1,#section_link2,#section_link3", function(event){
event.preventDefault();
$('html, body').animate({scrollTop: $(this).offset().top}, 300);
});
Or create a common css class for all of them and just use $(".myLinkClass") to find them all in one shot.
$("body").on("click", ".myLinkClass", function(event){
event.preventDefault();
$('html, body').animate({scrollTop: $(this).offset().top}, 300);
});
Upvotes: 1
Reputation: 8029
You can use native javascript's for
loop like this:
var linkitems = ['link1','link2','link3']
for (i = 0; i < linkitems.length; i++) {
$('.nav_'+linkitems[i]).click(function(event){
event.preventDefault();
$('html, body').animate({scrollTop: $('#section_'+linkitems[i]).offset().top}, 300);
})
}
Upvotes: 0