Reputation: 3697
I am creating a single page word-press theme. I have a menu that is dynamically populated whenever a new page is created, for each menu item, a section is added to my page. When you click the menu item, the page scrolls down to the section.
Each section has a class "section" and the unique ID of the page name. Likewise, each menu item has a class "menu_item" and ID of the page name.
I'm struggling to code the right jQuery to make the page scroll to the section (currently it just jumps).
jQuery:
var $paneTarget = $("body");
var $section_name = $('.section').attr('data-slug');
var $menu_link = $('.menu_item').attr('data-slug');
$('$menu_link').click(function(){
$paneTarget.scrollTo('$section_name', 800);
return false;
});
And the outputted html for my menu:
<ul class="menu">
<li><a class="menu_item about" data-slug="about" href="#about">About</a></li>
<li><a class="menu_item portfolio" data-slug="portfolio" href="#portfolio">Portfolio</a></li>
<li><a class="menu_item services" data-slug="services" href="#services">Services</a></li>
<li><a class="menu_item test-page" data-slug="test-page" href="#test-page">Test Page</a></li>
<li><a class="menu_item home" data-slug="home" href="#home">Home</a></li>
</ul>
Lastly, the outputted html for my sections
<section class="section" id="about" data-slug="about" ><h1></section>
<section class="section" id="portfolio" data-slug="portfolio" ><h1></section>
<section class="section" id="services" data-slug="services" ><h1></section>
<section class="section" id="test-page" data-slug="test-page" ><h1></section>
<section class="section" id="home" data-slug="home" ><h1></section>
The issue I'm having is with jQuery, getting the page to scrollTo
each section when I press a menu item. Bearing in mind that all menu items and pages are created dynamically, so I need to code it so it covers new pages being added.
Upvotes: 0
Views: 1612
Reputation: 22480
The actual problem is that your jQuery code never gets called. see here as you can see on click it should alert "here"
but it never will. return false
gets called to late and better is to use preventDefault()
.
try like this:
$('.menu_item').click(function(e){
e.preventDefault();
var id = $(this).attr('data-slug');
$('html,body').animate({
scrollTop: $('#'+id).offset().top
}, 1000);
});
depending on which jQuery version you are using you can change $('.menu_item').click(function(e)...
to $('.menu_item').on('click', function(e)...
Upvotes: 1