Skip to content
Advertisement

innerHTML containing bookmarks cannot be linked to from another page

I use JavaScript AJAX to include a file cards.html into a parent html page index.html.
The included cards.html file is a list of cards and each card has a bookmark in it in the form <li id="byx-123_shapes">. When I hyperlink to the bookmark from another page, instead of the browser positioning on the bookmark it positions on the top of the page. If I manually insert cards.html into index.html the hyperlinking works properly. It seems like the browser is unaware of the bookmarks because they were imported via AJAX rather than being there when index.html was loaded.

Cards.html included in index.html.

JavaScript

JavaScript to load cards.html

JavaScript

Example of a hyperlink that doesn’t work when include via AJAX but does work when insert cards manually.

JavaScript

Can someone explain why this happens and how to fix it.

Advertisement

Answer

When you load index.html#bookmark, it tries to scroll to the bookmark immediately after loading the page. But the AJAX request hasn’t completed yet, so the bookmark isn’t loaded.

You should put code in the xhr.onload function to scroll to the bookmark after inserting the HTML

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement