Reputation: 1269
This is my navbar contents
<div class="col-md-3">
<div class="bs-docs-sidebar hidden-print affix" role="complementary">
<ul class="nav bs-docs-sidenav" id="titles">
</ul>
</div>
</div>
<script type="text/javascript">
$(function(){
var html = '';
$("td > h1 > a").each(function(){
html = html + '<li><a href="#" data-scroll="' + $(this).attr('data-anchor') + '">' + $(this).text() + '</a></li>';
});
document.querySelector('#titles').innerHTML = html;
});
$('#titles > li > a').on('click', function() {
console.log('called');
var scrollAnchor = $(this).attr('data-scroll'),
scrollPoint = $('tbody[data-anchor="' + scrollAnchor + '"]').offset().top - 28;
$('body,html').animate({
scrollTop: scrollPoint
}, 500);
return false;
});
The first function will populate data according the html content. The second function will handle the click events in the navbar content.
But, the 2nd function never gets executed.
Can somebody tell me how fix this ?
Upvotes: 0
Views: 6197
Reputation: 133453
As you are creating HTML.
You should use Event Delegation. You have to use .on() using delegated-events approach.
General Syntax
$(document).on(event, selector, eventHandler);
Ideally you should replace document
with closest static container. In your case its '#titles'
. So use
$('#titles').on('click', 'li > a', function() {
console.log('called');
var scrollAnchor = $(this).attr('data-scroll'),
scrollPoint = $('tbody[data-anchor="' + scrollAnchor + '"]').offset().top - 28;
$('body,html').animate({
scrollTop: scrollPoint
}, 500);
return false;
});
Upvotes: 3