Creating a star rating system using jQuery involves handling user interactions and updating the visual representation of the rating. Below is a simple example of a star rating system using HTML and jQuery.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Star Rating with jQuery</title>
<style>
.rating-container {
display: inline-block;
font-size: 24px;
}
.star {
cursor: pointer;
color: #ccc;
display: inline-block;
margin: 0 4px;
}
.star.checked {
color: gold;
}
</style>
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
</head>
<body>
<div class="rating-container" data-rating="0">
<span class="star">★</span>
<span class="star">★</span>
<span class="star">★</span>
<span class="star">★</span>
<span class="star">★</span>
</div>
<script>
$(document).ready(function() {
// Initial setup: set the rating based on data-rating attribute
$('.star:lt(' + $('.rating-container').data('rating') + ')').addClass('checked');
// Handle star click events
$('.star').on('click', function() {
// Remove 'checked' class from all stars
$('.star').removeClass('checked');
// Add 'checked' class to the clicked star and previous stars
$(this).prevAll('.star').addBack().addClass('checked');
// Update the data-rating attribute with the new rating
$('.rating-container').data('rating', $(this).index() + 1);
});
});
</script>
</body>
</html>
In this example:
Stars are represented using HTML entities (★ for a solid star).
The stars are initially gray. When a user clicks on a star, it, and all the previous stars, turn gold.
The rating is stored in the data-rating attribute of the container, and it's updated dynamically as the user interacts with the stars.
Feel free to customize the styling and structure based on your design preferences. This example provides a basic foundation that you can build upon for a more sophisticated star rating system if needed.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Creating a star rating system using jQuery involves handling user interactions and updating the visual representation of the rating. Below is a simple example of a star rating system using HTML and jQuery.
In this example:
Feel free to customize the styling and structure based on your design preferences. This example provides a basic foundation that you can build upon for a more sophisticated star rating system if needed.