Reputation:
I am new to webdevelopping and altough I've made a few onclick functions with javascript/jquery, I am having trouble making this one work. Basically, I am trying to make a 5-star rating system using JQuery and without using plugins made by others.
I have an HTML to which I add the following information
function createRating() {
var sC = $('#starContainer');
for (var i = 1; i <= MAX_RATING; i++) {
sC.append($('<span>').addClass('fa fa-star').attr('id', 'star' + i));
}
}
Afterwards I am merelly trying to change the colour of the clicked star and all the previous one without duplicating code. By calling this function whenever one of the stars is clicked, however, when I click one of the stars, nothing happens. I can't figure out what I am doing wrong. Sort of stuck for a few hours here.
$('.fa.fa-star').click(function() {
alert("fa star clicked");
var currentStar;
var clickedIndex = $('.fa.fa-star').index(this) + 1;
for (var i = 1; i <= MAX_RATING; i++) {
currentStar = $('#star' + i);
if (i <= clickedIndex) {
currentStar.css({"color" : "green"});
} else {
currentStar.css({"color" : "white"});
}
}
});
I know the click isn't working because the alert does do anything.
Would appreciate any help with the subject.
Best regards,
Upvotes: 1
Views: 820
Reputation: 300
Your event isn't firing because the Click event is registered before the HTML for stars is made. Therefor it won't be able to attach the event to it.
You can try assigning the event using the bubble technique:
$('#starContainer').on("click", ".fa.fa-star", function() {
});
This will assign the event to the StarContainer div (assuming it's created on page load) and then look for any clicks for .fa.fa-star events.
Upvotes: 3