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.

    <section id="cards">
    <!-- INSERT CARDS HERE -->
    <ul>
    <li id="byx-123_shapes" class="byx-book-tile byx-box">
    
        <figure>
            <img src="books/123_shapes/res/icon.png">
        </figure>
        
        <h2>
            123 Shapes
        </h2>
        <p>
            Placeholder for a book that is still being written.
        </p>
        <a href="previews/123_shapes_view.html">Preview Book</a>
    </li>

    .... more cards ...

    <li id="byx-zoo_friends" class="byx-book-tile byx-box">
        
        <figure>
            <img src="books/zoo_friends/res/icon.png">
        </figure>
        
        <h2>
            Zoo Friends
        </h2>
        <p>
            Placeholder for a book that is still being written.
        </p>
        <a href="previews/zoo_friends_view.html">Preview Book</a>
    </li>
    </ul>
    </section>
...

JavaScript to load cards.html

// Uses AJAX to load cards.html
// Works but messes up card bookmarks
const xhr = new XMLHttpRequest();
const cards = document.getElementById('cards');
xhr.onload = function() {
    if (this.status == 200) {
        cards.innerHTML = xhr.responseText;
    } else {
        console.warn('Could not load cards');
    };
};
xhr.open('get', 'cards.html');
xhr.send();

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

https://...//index.html#byx-zoo_friends

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

xhr.onload = function() {
    if (this.status == 200) {
        cards.innerHTML = xhr.responseText;
        if (window.location.hash) {
            let target = document.querySelector(window.location.hash);
            if (target) {
                target.scrollIntoView();
            }
        }
    } else {
        console.warn('Could not load cards');
    };
};
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement