I am working on a web application that adds charts dynamically on the page, there is a sidebar on the left which provides anchor points to navigate through the charts.
The sidebar anchor points and charts are appended via JQuery. I believe part of the issue here is that the event listeners are not firing on the appended elements.
The web app code is pretty big, so I am just attaching the snippets involved. My goal here is to make clicking on the anchors "SMOOTH" scroll, instead of jump from one chart to the other.
I looked at this post below to get the scrolling code:
$('a').click(function(){
$('html, body').animate({
scrollTop: $( $.attr(this, 'href') ).offset().top
}, 500);
return false;
});
Smooth scrolling when clicking an anchor link
Then combined that with this post, to add the event listener to the appended div:
Event binding on dynamically created elements?
$(document).on( eventName, selector, function(){} );
I eventually came down with this function, but it's still not working:
$(document).on('click', '#scrollAnchor', function () {
"use strict";
alert("Click event works but I still won't scroll!");
$('html, body').animate({
scrollTop: $($.attr(this, 'href')).offset().top
}, 500);
return false;
});
And finally, here is the code for the appended element.
function updateChartData() {
...
navDiv = '<a id="scrollAnchor" href="#' + chartName
+ '"> <div class="chartAnchor"><span>'
+ chartName
+ '</span></div></a>';
}
function addChartPage() {
...
$('#allNavs').append(navDiv);
}
(where allNavs is the container for the anchors)