JS result of year-link click lands in the false column

  Kiến thức lập trình

I have a 2-columns (div) page.

Left column: the posts

right column: the respective years

The years are clickable: if a year is clicked the result should filter the posts in the left column.

**The error: after a year-click, the filtered posts land as well in the left column ( which is ok) as in the right column, and the year links disappear (wich is bad) **

The left div (posts):

<div class="fenster">
    {% if posts %}
        {% for post in posts %}
           <h3>{{ post.post_title }}</h3>
           <p id="{{ post.id }}">{{ post.post_content|safe }}</p>
           <p>Veröffentlicht am: {{ post.post_date|date:"l, j. F Y, H:i" }}</p>
           <p>Autor: {{ post.post_author.user_login }}</p>
           <button class="edit-button" data-post-id="{{ post.id }}">Bearbeiten</button>
           <hr>
        {% endfor %}
    {% else %}
        <p>Keine Posts gefunden.</p>
    {% endif %}
</div>
<div>
    {% if posts.has_previous %}
        <a href="?{{ request.GET.urlencode }}&page={{ posts.previous_page_number }}">Vorherige Seite</a>
    {% endif %}

    <span>Seite {{ posts.number }} von {{ posts.paginator.num_pages }}</span>

    {% if posts.has_next %}
        <a href="?{{ request.GET.urlencode }}&page={{ posts.next_page_number }}">Nächste Seite</a>
    {% endif %}
</div>

The right div (years):

<div class="fenster">Zeitleiste <br>
    <div class="container" style="display: flex; flex-wrap: wrap;">
        {% for jahr in jahre %}
            <div class="flex-item" style="flex-basis: 10%;">
                <a href="?action=year&year={{jahr}}" class="year-link">{{ jahr }} </a>
            </div>
            {% if jahr|divisibleby:10 %}
            <div style="flex-basis: 100%;"></div>
            {% endif %}
        {% endfor %}
    </div> <!-- end of container -->
</div> <!-- end of fenster -->

The java script code :

$(document).ready(function() {
    $(".year-link").click(function(event) {
        event.preventDefault();  
        var url = $(this).attr('href'); // or do window.location.origin + $(this).attr('href');
        $.get(url, function(data) {
            var receivedData = $(data);  // Convert the received HTML data to a jQuery object
            var posts = receivedData.find('.fenster').html();  // Extract the posts data
            $('.fenster').html(posts);  // Update the current page with the received posts data
        });
    });
});

Without the document-ready it ran as wished.

New contributor

Andreas A is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT