Aero
Aero

Reputation: 317

Attaching jQuery event to more than one selector in one call

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

Answers (2)

Timeout
Timeout

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

Mohamed Khamis
Mohamed Khamis

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

Related Questions