0

I'm trying to follow the DRY principle by changing a bunch of repeated functions, but I'm stuck here. I want to change this scroll to function that is repeated 4 times with different classes and ids to a more generic way (I'm using jQuery):

  $('.empresa').click(function(event){
    $('html, body').animate({
        scrollTop: $("#empresa").offset().top
    }, 500);
    return false;
  });
  $('.nosotros').click(function(event){
    $('html, body').animate({
        scrollTop: $("#nosotros").offset().top
    }, 500);
    return false;
  });

the classes are elements of a navigation within a ul which looks something like this.

<ul class="nav">
    <li><a href="index#nosotros" class="nosotros">Link to the anchor</a></li>
    <li><a href="index#empresa" class="empresa">Link to the anchor</a></li>
</ul>

and the scroll to tags are div elements with this tags.

<div class="some-random-class" id="empresa" name="empresa">
<div class="some-random-class" id="nosotros" name="nosotros">

I was using this new selector to grab the class of the list with the proper anchor but I'm having trouble with the scroll part of the function, I don't know to use/convert the class or name of the object extracted to an id so I can keep use it the same way I was doing before.

$('.nav li').children('a').click(function() {
    alert( $(this).attr('class') );
});

hope you guys can help me!

2 Answers 2

2
$('.nav > li > a').click(function(e){
    e.preventDefault();
    $('html,body').animate({
       scrollTop: $('#'+$(this).prop('class')).offset().top
    });
});
Sign up to request clarification or add additional context in comments.

Comments

0

You also can use:

$('.fluidJump').on('click', function(event) {
    event.preventDefault();
    var offset = $($(this).attr('href')).offset().top;
    $('html, body').animate({scrollTop:offset}, 500);
});

Add "fluidJump" class on hiperlink to go to that section with animation. (number value)

<a href="#sectionid">Go to section</a>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.