ArticleZip > Turn A Number Into Star Rating Display Using Jquery And Css

Turn A Number Into Star Rating Display Using Jquery And Css

Many websites and applications display star ratings to help users quickly gauge the popularity or quality of a product or service. If you're a developer looking to enhance your website with this feature, you're in the right place! In this guide, we'll walk you through how to turn a numerical rating into a visually appealing star rating display using jQuery and CSS.

First, let's understand the basic concept behind our approach. We will create a system where a numerical value, say from 1 to 5, will be converted into a corresponding visual representation using stars. For example, a rating of 4.5 would be shown with 4 full stars and a half star.

To begin, ensure you have both jQuery and CSS linked in your HTML file. You can include jQuery by adding the following script tag in your HTML head section:

Html

Next, let's create the HTML structure for our star rating display:

Html

<div class="star-rating">
    <span class="stars"></span>
</div>

Now, let's move on to the CSS styling. The CSS code below will help us define the appearance of the stars:

Css

.star-rating {
    font-size: 0;
}

.star-rating::before {
    content: "★★★★★";
}

.stars {
    display: block;
    width: 0;
    white-space: nowrap;
    overflow: hidden;
    font-size: 24px;
}

.stars::before {
    content: "★★★★★";
    color: gold;
    position: absolute;
    display: block;
    width: 0;
    white-space: nowrap;
    overflow: hidden;
}

.stars span {
    display: inline-block;
    position: relative;
    width: 1.2em;
}

.stars span::before {
    content: "★";
    position: absolute;
    left: 0;
    color: transparent;
    -webkit-text-stroke: 1px gold;
}

.stars span:hover::before,
.stars span:hover ~ span::before {
    color: gold;
}

The JavaScript part is where the magic happens. We will use jQuery to dynamically update the star rating based on the numerical value:

Javascript

function displayRating(rating) {
    var stars = "";
    var fullStars = Math.floor(rating);
    for (var i = 0; i &lt; fullStars; i++) {
        stars += &quot;<span>★</span>";
    }
    if (rating % 1 !== 0) {
        stars += "<span>★</span>";
    }
    $(".stars").html(stars);
}

// Call the function with the desired rating (e.g., 4.5)
displayRating(4.5);

With these snippets in place, you now have a functional star rating display on your website that transforms numerical ratings into visually appealing stars. Feel free to customize the styles or functionality further to suit your specific needs.

Implementing a star rating system using jQuery and CSS not only enhances the user experience but also adds a touch of visual flair to your website or application. Happy coding!