I'm trying to make a star rating system at an initial stage, the 5 star icon from font awesome deosn't seem to fire when an even litsener to add to it, i don't know what i'm doing wrong
html `
<section data-aos="fade-up">
<div >
<div id="confirm-box">{% include "message.html" %}</div>
<div >
<div >
<img src="{{product.image.url}}" alt="product image">
</div>
<div >
<p >Sale</p>
<h2>{{product.name|title}}</h2>
<p>Product id: {{product.id}}</p>
<div >
<span id="first"></span>
<span id="second"></span>
<span id="third"></span>
<span id="fourth"></span>
<span id="fifth"></span>
</div>
<p >USD ${{product.price}}</p>
<label for="">Quantity: </label>
<input type="text" readonly id="product-quantity" value="{{current_item.quantity}}">
<button id="update-cart" data-product={{product.id}} data-action="add" >Add to cart</button>
</div>
</div>
</div>
</section>
Javascript
`
const one = document.getElementById('first')
const two = document.getElementById('second')
const three = document.getElementById('third')
const four = document.getElementById('fourth')
const five = document.getElementById('fifth')
const arr = [one, two, three, four, five]
one.addEventListener('mouseover', function(event){
console.log(event.targetS)
console.log('event is working')
})
arr.forEach(function(item) {
item.addEventListener('mouseover', function(event) {
console.log(event.target)
})
})
i've tried it with just one of the element and it still doesn't fire
CodePudding user response:
You're trying to add the event listener to an element that doesn't exist in the DOM yet.
To fix this issue, you can move the code that adds the event listener to the elements to a function that gets called when the page has finished loading. You can use the window.onload
event to call this function, which will ensure that the elements have been added to the page before you try to add the event listener.
Here's an example of how you can do this:
window.onload = function() {
const one = document.getElementById('first')
const two = document.getElementById('second')
const three = document.getElementById('third')
const four = document.getElementById('fourth')
const five = document.getElementById('fifth')
const arr = [one, two, three, four, five]
arr.forEach(function(item) {
item.addEventListener('mouseover', function(event) {
console.log(event.target)
})
})
}