propcode
propcode

Reputation: 309

Scroll to div - multiple locations

I have a menu list where the user can scroll to different sections.

The problem is that with the code I'm using it refers to specific ID so I have to copy over and over changing IDs:

$('#asistentes-menu').click(function() {
    $('body,html').animate({
        scrollTop: $("#asistentes-location").offset().top - 80
    }, 800);
});
$('#evento-menu').click(function() {
    $('body,html').animate({
        scrollTop: $("#event-section").offset().top - 80 
    }, 800);
});
and so on...

Any idea how to change this code so I can use it for all the menu locations?

Upvotes: 0

Views: 57

Answers (1)

John Bupit
John Bupit

Reputation: 10618

You can use classes for menu items, and then perhaps a data attribute to the location it points to:

<a class="menu-item" data-location="asistentes-location">...</a>

...

<div id="asistentes-location">...</div>

And the corresponding script:

$('.menu-item').click(function() {
    var $menuItem = $(this);
    $('body,html').animate({
        scrollTop: $('#' + $menuItem.data('location')).offset().top - 80
    }, 800);
});

Alternatively, you can also find the location's ID using the menu item's ID using some string manupilation:

$('#' + $menuItem.attr('id').replace('menu', 'location'))

UPDATE: If your menu items are <a> tags, you could simply use their href attribute. I would recommend this as it wouldn't break your code even if javascript is disabled.

<a href="#myLocation" class="menu-item">...</a>

And the corresponding script:

$('.menu-item').click(function(e) {
    e.preventDefault();
    var $menuItem = $(this);
    $('body,html').animate({
       scrollTop: $($menuItem.attr('href')).offset().top - 80
    }, 800);
});

$(function() {
  $('.menu-item').click(function(e) {
    e.preventDefault();   // Remember to add this
    var $menuItem = $(this);
    $('body,html').animate({
      scrollTop: $($menuItem.attr('href')).offset().top - 80
    }, 800);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#location1" class="menu-item" data-location="location1">Go to 1</a>
<a href="#location2" class="menu-item" data-location="location2">Go to 2</a>
<a href="#location3" class="menu-item" data-location="location3">Go to 3</a>

<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<p id="location1">This is location 1</p>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<p id="location2">This is location 2</p>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<p id="location3">This is location 3</p>

Upvotes: 2

Related Questions