Thursday 27 February 2014

jQuery: Animated page scroll when clicked on menu item - dynamically

Scenario:
I have a navigation menu. When user click on the hyper link of the menu item I wanted to navigate it to that element dynamically. For example, if a user click on the Size menu item then I wanted to animate the page scroll down to the item with id="Size". Note: Here size menu item href does not have any value so 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>

Solution:
Since, my hyper link text and target element id are same so if I can get the hyper link text value then I will be able to animate to the target element as well.
javascript.js
function changeMenuColor()
{
    $("nav li a").click(function () {
        var a_text = $(this).text(); //get the hyper link text value
        //a_text = '"#' + a_text + '"'; // this is example to insert inverted comma.
        $('html, body').animate({
            scrollTop: ($('#'+a_text+'').offset().top)
        }, 500);
    });
}