I am trying to add a html snippet dynamically which contains named anchors and destinations via jquery append(‘html’) method
None of the named links work after the append. The newly added content is visible on the page, but the links dont work. Is it because these tags were added dynamically, or am I doing something wrong here? However, all server side generated named anchors work fine.
simplified html:
<a href="#tab">Foo</a>
<div id="tab"></div>
("#testButton").click(function() {
$('#mainSegmentDiv').append("html")
});
Anchors appended with JavaScript should work as anchors (in that clicking them should take you to whatever location is specified in its
hrefattribute), but if you’re trying to use an tag-name,idorclassto select them, they won’t ‘work’ because they weren’t present in the DOM when the event handlers were bound:JS Fiddle demo (demonstrates non-working code).
Without specific knowledge of your HTML, or what you’re doing, I can only offer you this suggestion:
JS Fiddle demo (demonstrates working code).
The
on()method attaches theclickevent (in this case) to thebodyelement and relies on event propagation to work, in that the click bubbles up to thebodyand then works out where it came from and if it matches the given selector (theain this case, you can useid,classor any valid jQuery selector). If it matches the selector the function the events/functions (in this case that’s the// do somethingcomment) is executed.Ideally, instead of using the
$('body')you’d use the closest parent-element to those elements you later add to the DOM that exist at the time of event-binding (usually$(document).ready()).References:
on().