In the menu, press & # 8594; animate and scroll to element dynamically

I have a navigation menu: introduction, size, playback, food. When the user clicks on the hyperlink of a menu item, I want to navigate to that item and animate.

For example, if the user clicks on the Size menu item , then I want to animate and scroll down to the element with id="Size"

.

Note: The size of the href element is irrelevant here as it is dynamic.

index.html

<nav>
    <ul>
            <li><a href="#">Intro</a></li>
            <li><a href="#">Size</a></li>
            <li><a href="#">Play</a></li>
            <li><a href="#">Food</a></li>
    </ul>
    <div class="clear"></div>
</nav>

<aside id="Size" class="sidebar">
        <h3>Size</h3>
        <img src="Images/boxer2.jpg" />
        <p>Hegyét bár érti szeret.
        </p>
</aside>

      

+1


source to share


2 answers


You can perform smooth scrolling with by $.animate(...)

passing the offset position of the element scrollTop

.

$. animate: http://api.jquery.com/animate/

HTML code:

<nav>
<ul>
    <li><a href="#">Intro</a>
    </li>
    <li><a href="#">Size</a>
    </li>
    <li><a href="#">Play</a>
    </li>
    <li><a href="#">Food</a>
    </li>
</ul>
<div class="clear"></div>
</nav>
<aside id="Intro" class="sidebar">
    <h3>Intro</h3>
    <img src="Images/boxer2.jpg" />
    <p>Hegyét bár érti szeret.</p>
</aside>
<aside id="Size" class="sidebar">
    <h3>Size</h3>
    <img src="Images/boxer2.jpg" />
    <p>Hegyét bár érti szeret.</p>
</aside>
<aside id="Play" class="sidebar">
    <h3>Play</h3>
    <img src="Images/boxer2.jpg" />
    <p>Hegyét bár érti szeret.</p>
</aside>
<aside id="Food" class="sidebar">
    <h3>Food</h3>
    <img src="Images/boxer2.jpg" />
    <p>Hegyét bár érti szeret.</p>
</aside>

      

JQUERY CODE:



$('li a').on('click', function (e) {
   var targetSec = $(this).text();
   $('html, body').animate({
      scrollTop: $('#' + targetSec).offset().top
   }, 2000);
});

      

LIVE DEMO:

http://jsfiddle.net/dreamweiver/3Xm48/11/

Happy coding :)

+2


source


You want to do something like this



$("nav ul li").click(function() {
    var liText = $(this).text();
    $('html, body').animate({
        scrollTop: $("#" + liText ).offset().top
    }, 1000);
});

      

+3


source







All Articles