Why aren't the JavaScript stars shining once I've selected one?

I recently set up a star rating feature on my website by following the tutorial "Creating an Ajaxified Star Rating System in Rails 3".

Although I managed to get everything working on the index page, I noticed that the stars do not remain lit up after being clicked. I suspect there might be an issue with my JavaScript code. Is there a way to achieve this effect using CSS alone?

If you require any additional information, please feel free to ask.

Here is a snippet of my rating_ballot.js:

$(document).ready(function() {

  ### Makes stars stay glowing after click.
  ### But after its clicked, the value is saved, But the star doesn't stay glowing. 

  $('form.rating_ballot > label').click(function() {
    $(this).siblings().removeClass("bright");
    $(this).prevAll().andSelf().addClass("bright");
  });


  ### Submits the form & saves data. 
  $(document).on('change', '.rating_button', function(){
    $(this).parent().submit();
  });
});

Here is the CSS.SCSS file:

form.rating_ballot input.rating_button { display: none; }

form.rating_ballot label.rating { cursor: pointer; display: block; height: 20px; width: 20px; float: left; }
form.rating_ballot label.rating span { display: none; }
form.rating_ballot label.rating { background-image:  image-url('star-dim.png'); }
form.rating_ballot label.rating.bright { background-image:  image-url('star-bright.png'); }
form.rating_ballot label.rating.glow { background-image:  image-url('star-glow.png'); }

A snippet from my index.hrml.erb (books) file:

<% @books.each do |book| %>
  <table id="book_<%= book.id %>">
    <tbody>  
      <tr>  
        <td>
          <%= book.title %>
        </td> 
      </tr> 

      <tr>

        <td  id="rating">                   
          <%= render :partial => 'ratings/rating', :locals =>{:book => book} %>
        </td>

      </tr>
    <tbody>
  </table>
<% end %>

_rating.html.erb contains the form structure for the ratings system.

In the create.js.erb and update.js.erb files, the updated content based on user interactions is dynamically loaded using JavaScript.

The BooksHelper module includes methods for managing the user's rating on books.

HTML CODE IN DEVELOPER TOOLS

An excerpt from the developer tools displaying HTML elements before and inside a table element.

Code before I open a table

<table class="table" id="book_1176">...</table>
<table class="table" id="book_1177">...</table>
<table class="table" id="book_1178">...</table>
<table class="table" id="book_1179">...</table>

Code After I open a Table

<table class="table" id="book_1176">   
  <tbody>  
    <tr>
      <td id="rating">    
       <!-- Form contents -->
     </td>
    </tr> 
  </tbody>
</table>

Answer №1

Regret if this solution does not directly address the issue:


CSS

To make the stars light up when they are "valued," you need to assign them an additional class beyond the default classes they already have.

The provided JS accomplishes this for you:

  $('form.rating_ballot > label').click(function() {
    $(this).siblings().removeClass("bright");
    $(this).prevAll().andSelf().addClass("bright");
  });

One problem I see is that upon page reload, there is no mechanism in place to add the bright class to your values

This issue is exacerbated by the fact that your page gets reloaded each time a star is clicked and submitted. If this process were handled via Ajax, the problem would still persist, albeit in a different manner.


Solution

You could attempt the following approach:

<%= form_for(rating_ballot(book.id), remote: true, :html => { :class => 'rating_ballot' }) do |f| %>

  <% [1..5].each do |i| %>

      <% sfx = "value_#{book.id}_#{i}" %>

      <%= f.label(sfx, content_tag(:span, i), :class => "rating") %>
      <%= radio_button_tag("rating[value]", i, current_user_rating(book.id) == i, 
      :class => 'rating_button #{bright?(i, book.id)}', :id => "rating_#{sfx}") %>
  <% end %>

  <%= hidden_field_tag("book_id", book.id) %>
  <%= f.submit :Submit, style: "display: none" %>

<% end %>

module BooksHelper

  def rating_ballot(book_id)
    if @rating = current_user.ratings.find_by_book_id(book_id)
        @rating
    else
        current_user.ratings.new
    end
  end

  def current_user_rating(book_id)
    if @rating = current_user.ratings.find_by_book_id(book_id)
       @rating.value
    end
  end

  def bright?(val, book_id)
    if(current_user_rating(book_id) < val)
        "bright"
    end
  end
end

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to use rounded divs and buttons exclusively on iOS devices? Leveraging jQuery, AJAX,

Recently, I have been developing a client application that consumes an API and dynamically generates buttons. The project has been running smoothly on various platforms, with Chrome dev tools indicating no issues on any device. However, after testing it on ...

Utilizing ng-bind-html alongside ng-controller

Injecting insecure html into a <div> is part of my current task: <div class="category-wrapper" ng-bind-html="content"></div> The angularjs "code" in this html snippet ($scope.content) includes the following: <script type='text/ ...

Can you explain the functionality of this Observable in the context of this Angular 2 example?

I'm not too familiar with JavaScript/TypeScript and I have a question about how this code snippet works: onGet() { this.serverService.getServers() .subscribe( (servers: any[]) => this.servers = servers, // an array of anythin ...

Why do my tablet media queries take precedence over mobile view media queries?

I've noticed that when I view my website on mobile devices, the tablet media queries always seem to override my mobile media queries. Can anyone explain why this is happening? Here is how I have set it up: /* X-Small devices (portrait phones, less t ...

Trick to keep horizontal element alignment intact when scroll bar appears

Currently, all my pages are designed with the standard fixed-width-margin-left-right-auto layout. .container{ width:900px; margin:0 auto; } An issue arises when some of these pages exceed the height of the window, requiring a vertical scroll ba ...

The timestamp will display a different date and time on the local system if it is generated using Go on AWS

My angular application is connected to a REST API built with golang. I have implemented a todo list feature where users can create todos for weekly or monthly tasks. When creating a todo, I use JavaScript to generate the first timestamp and submit it to th ...

Angular5+ Error: Unable to retrieve summary for RouterOutlet directive due to illegal state

When attempting to build my Angular App using ng build --prod --aot, I consistently encounter the following error: ERROR in : Illegal state: Could not load the summary for directive RouterOutlet in C:/Path-To-Project/node_modules/@angular/Router/router.d. ...

JavaScript glitch preventing fancybox functionality in Firefox browser

I'm experiencing an issue with FancyBox not working on Firefox while using js no conflict on this specific site Upon inspecting with Firebug, I encountered the following error: Error Line: 99 A similar error is also being thrown by Safari: Typ ...

What is causing the nav-link items to not change to white in this dark Bootstrap 4 Nav?

Why are the nav-link colors not turning white in this dark Bootstrap 4 Nav code snippet? They should behave like Navbars, shouldn't they? <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="_ ...

Adding / Deleting a Row in a sequence of floated divs

I have a group of div elements arranged side by side with the float:left style as shown below: <div id="container"> <div id=0" style="float:left">> Stuff </div> <div id=1" style="float:left">> Stuff </div> < ...

Enhance navigation in your HTML5 iPad app with a swipe effect for seamlessly transitioning to the next page

I am in the process of creating a mobile application for browsing products offline on the iPad. The application will be developed using HTML5 / JS and will feature offline image caching and local storage. One of the key features I want to include is swipe ...

Navigating through different states and managing the URL manually can be a breeze with AngularJS

In my current setup using the meanjs stack boilerplate, I am facing an issue with user authentication. When users log in, their state remains 'logged-in' as long as they navigate within the app starting from the base root URL '/'. This ...

Converting Callbacks to Promises in Node.js

I am facing a challenge with my node js application as I am attempting to promisify multiple callback functions without success. It has reached a point where I am unsure if it is even feasible. If you can assist me in promisifying the code provided below, ...

jQuery highlight() malfunctioning in dynamically generated table

I am currently developing a highlight function and encountering an issue. The function involves loading records from a database that match the current form data and highlighting common words between the user's input and existing records. However, I am ...

Experiencing issues with a malfunctioning Chrome extension? The CaptureVisibleTab feature seems to be failing when using

Whenever I try to use the captureVisibleTab function on a page where I have a div with preserve3d in CSS3, all I see is a blank page. How can I solve this issue? Here is my simple code for capturing the browser screen: chrome.browserAction.onClicked.addL ...

Changing the order of rows and columns with CSS3 and DOM manipulation

I have implemented the following CSS code to alternate the background color of li elements. However, I am facing an issue where I need the CSS styling to remain consistent even if the rows have the .hidden class applied to them (with .hidden class having d ...

MongoDB failing to enforce unique constraints on partial indexes

I have a set of data that looks like this: { name: "Acme co." add4: "", nationalNumber: "+13412768376" }, { name: "Acme Inc.", add4: "6345", nationalNumber: "" } My goal is to insert these records into a collection, but only if they are uni ...

Cities cannot be obscured by a rotating globe

In my latest project, I have created a jsfiddle showcasing a Bostock spinning globe implementation. After successfully plotting a few city markers, I encountered a problem where not all cities were being displayed. Additionally, the script intended to hid ...

Alter the background color of the entire document to (EDIT) in the top dialog box

<script> $(function() { $( "#dialog" ).dialog(); }); </script> </head> <body> <div id="dialog" title="Basic dialog"> <p>This default dialog box can display information. It can be moved, re-sized, and closed ...

What is the best way to run tests on this asynchronous function using Jasmine?

My role in the service is listo: function () { var promiseResolved = $q.defer(); setTimeout(function () { promiseResolved.resolve(true); }, 2000); return promiseResolved.promise; } During my testing ...