I am creating with javascript that when I select the like button it prints Hi. I don't understand why when inspecting it is not selecting the button. I don't understand what I'm doing wrong. Can it be that I do not get the javascript url?
index.hmtl
<script src="{% static 'network/index.js' %}"></script>
<form method="post">{%csrf_token%}
<button onclick="darLike()">Like</button>
<a id="resultado"></a>
<svg xmlns="http://www.w3.org/2000/svg" width="16 " height="16 " fill="currentColor " class="bi bi-heart " viewBox="0 0 16 16 ">
<path d="m8 2.748-.717-.737C5.6.281 2.514.878 1.4 3.053c-.523 1.023-.641 2.5.314 4.385.92 1.815 2.834 3.989 6.286 6.357 3.452-2.368 5.365-4.542 6.286-6.357.955-1.886.838-3.362.314-4.385C13.486.878 10.4.28 8.717 2.01L8 2.748zM8 15C-7.333
4.868 3.279-3.04 7.824 1.143c.06.055.119.112.176.171a3.12 3.12 0 0 1 .176-.17C12.72-3.042 23.333 4.867 8 15z "/>
</svg>
</form>
index.js
document.addEventListener('DOMContentLoaded', function() {
document.addEventListener('click', () => function darLike() {
const contenido = document.querySelector('#resultado')
fetch(`like/${post.id}`, {
method: 'POST',
headers: {
'X-CSRFToken': csrftoken
}
})
// Put response into json form
.then(response => response.json())
.then(data => {
console.log(data);
contenido.innerHTML = "Hi"
})
// Catch any errors and log them to the console
.catch(error => {
console.log('Error:', error);
});
});
// Prevent default submission
return false;
})
You have added click listener to whole document, which is not required. Instead you want click event only on the button, which is already added in your html code.
In the below code
document.addEventListener('click', () => function darLike() {..}))
Your callback function is returning another function with name darLike and is not executing any code.
When you use the onclick the function needs to be globally available.
Instead you can attach click event to the button using addEventListener.
The DOMContentLoaded is available on window object and not document. Link
<form method="post"> {% csrf_token %}
<button>Like </button> // Removed onclick
...
</form>
window.addEventListener('DOMContentLoaded', function () {
document.querySelector('button').addEventListener('click', darLike);
function darLike() {
const contenido = document.querySelector('#resultado')
fetch(`like/${post.id}`, {
method: 'POST',
headers: {
'X-CSRFToken': csrftoken
}
})
...
}
});