I have the following JS Code:
(".year-link").click(function(event) {
event.preventDefault();
var year = $(this).data("year");
var url = window.location.pathname + '?action=year&year=' + year;
$.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
});
});
The Code is used in a Django-Template as follows:
{% for jahr in jahre %}
<div class="flex-item" style="flex-basis: 10%;">
<a href="?action=year&year={{jahr}}" class="year-link">{{ jahr }} </a>
</div>
The Codes does what it should (!!) but produces an error, seen in the developer tools:
JS Error: Uncaught TypeError: ".year-link".click is not a function
If I wrap my year-link function with document.ready …, the error is gone, but the page looses its behavior (nothing happens after click):
$(document).ready(function() {
$(".year-link").click(function(event) {
event.preventDefault();
var year = $(this).data("year");
var url = window.location.pathname + '?action=year&year=' + year;
$.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
});
});
});
What am I to do?
Regards
Andreas
I tried with chat-gpt some days, but either the code does what it should and produces the JS error
or the code produces no error and does nothing…
2
Answers
In your first codeblock there is missing a
$
in front of your selector:(".year-link")
->$(".year-link")
Also your a tag seems to have no data attribute
year
so$(this).data("year")
will not return anything.consider to add the attribute
data-year="{{jahr}}"
.You need to modify your code like this: (get the
href
and directly use it in$.get
)A sample working snippet: