Unexpected behavior encountered when making an AJAX request that involves CSS classes

One of the functionalities on a page involves selecting values for CSS class attributes.

Within the rails application show view, there is a style block and a div that utilizes these styles:

<style>
  #bg_<%= @promolayout.id %> {
    background-color: <%= @background.first.background_color %>;
    color: <%= @background.first.color %>;
    border-radius: <%= @background.first.border_box_radius %>;   } 
</style>
<div class='grid-x grid-padding-x'>
  <div class='cell small-3' id='bg_<%= @promolayout.id %>'>
    [...]
  </div>
  <div class='cell small-3' id='bg_newrender'>&nbsp;</div>
  </div>

Further down the page, there are form_with forms that allow for changing individual attribute values of CSS items through AJAX. The update process functions correctly. In the associated js file for rendering, there are two lines - one to display the new value with the form and the other to render a new version of the block with the updated attribute (resulting in a before-after view). The second line triggers:

$("#bg_newrender").html('<%=j (render 'promolayout') %>');

The promolayout partial also references the same CSS classes:

<style>
  #bg_<%= @promocomponent.promolayout_id %> {
    background-color: <%= @background.first.background_color %>;
    color: <%= @background.first.color %>;
    border-radius: <%= @background.first.border_box_radius %>;
  }
</style>

As expected, the div with the id='bg_newrender' renders with the updated CSS attributes.

However, an unexpected behavior occurs where the initial div with

id='bg_<%= @promolayout.id %>'
also displays the new CSS attributes.

Both classes have the same name, but the target divs have different IDs.

The question remains - why is an object with a unique ID on the page also being rendered with updated class attributes?

Answer №1

If you're looking to dynamically add styling to an individual element, consider using inline styling.

The use of the style attribute is generally discouraged as best practice dictates separating content from presentation. However, in certain scenarios where inline CSS tags are being generated with ERB, this separation may have already been compromised, leading to a cluttered view.

In a Rails application, it's recommended to create a helper or builder class that constructs the div tag with a style attribute.

Here's an example implementation:


module PromoHelper
  def promo_component_tag(promo, **opts, &block)
    options = opts.reverse_merge(
      class: 'promo-box', 
      style: hash_to_inline_style({
        background_color: promo.background_color,
        border_box_radius : promo.border_box_radius,
        color: promo.color
      })
    )
    content_tag :div, options, &block
  end

  private
  def hash_to_inline_style(hash)
    hash.map do |k,v|
      "#{k.to_s.dasherize}: #{v};"
    end.join
  end
end

This is a simplified illustration and may require adjustments based on your specific requirements.

To integrate this in your view:

<% @promotions.each do |p| %>
  <%= promo_component_tag(promo) do %>
    # ...
  <% end %>
<% end %>

When managing user interactions, you can either submit the form for Rails to re-render the view and update the DOM content, or utilize element.style or jQuery.css for real-time styling changes while submitting AJAX calls in the background to update database values. The latter approach offers a more responsive experience, especially if providing users with a preview option.

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

Using the .each method in AJAX JQUERY to iterate through callback JSON data and applying an if statement with Regular Expression to identify matches

Implementing a live search feature using ajax and jQuery involves running a PHP script that returns an array of database rows, encoded with JSON, based on the textfield input. This array is then iterated through in JavaScript after the callback function. ...

Creating a personalized meteor user registration form

Hi everyone, I'm currently working on creating a custom registration form using the accounts-password package. However, I encountered an error in the console: Error invoking Method 'insertUser': Internal server error [500], and on the server ...

Unique backgrounds with varied images on each grid block

Hi there! I'm currently exploring options to display different images for each section of a grid I've put together: Take a look at the CSS I'm using: background-image: url("my_image.jpg"); background-size: 50px auto; float: right; height: ...

PHP and AJAX can sometimes cause variable values to become lost

I've been encountering an issue while attempting to validate an email using ajax. For some reason, the mail variable seems to disappear during the process. Despite thoroughly checking for typos multiple times, I can't seem to locate any errors. T ...

Trouble with the drop-down menu displaying "string:2" in an AngularJS application

Currently, I am utilizing AngularJS ng-model to choose the value from a drop-down menu. Additionally, I am implementing datatable for organizing the columns. <select id="{{user.id}}" ng-model="user.commit" name="options" ng-change="update_commit_level ...

The content of xmlhttp.responseText is not being displayed in the innerHTML

As part of my ongoing effort to enhance my understanding of Ajax for work purposes, I have been following the W3Schools tutorial and experimenting with my Apache2 server. In this process, I have placed a file named ajax_info.txt on the server (in /var/www ...

What is the best way to style this specific HTML code using CSS?

Currently, I am facing an issue where two sets of text that are supposed to be inline with each other are not aligned properly. One of the texts is placed higher than the other even though they share the same CSS code. I want to be able to edit only one se ...

Resolving the Persistence Problem of Navigation Bar Fading In and Out

I've been struggling for hours trying different methods to achieve the desired outcome, but unfortunately, none of them have worked as expected. My goal is simple: I want the fixedbar to fade in when the scroll position exceeds the position of the ph ...

Instructions on how to retrieve information and transmit it to a form, and then display the customer's name in response to keyup or keydown

This is a PHP file for connecting to a MySQL database. <?php $conn = new mysqli("localhost", 'root', "", "laravel"); $query = mysqli_query($conn,"select * from customers"); while ($result2=mysqli_fetch_assoc($query)) { $dat ...

What about a Comet solution using a PHP socket server?

Is it true that PHP doesn't handle scaling with a large number of users in a comet implementation? Is this limitation due to the Apache server or the PHP language? Can a socket server resolve this issue and improve performance? Seeking advice from s ...

Achieving a Full Utilization of Available Space in Bootstrap

I'm working on an app using react-bootstrap and I'm looking for guidance on how to utilize the remaining space in the main section, excluding the header and footer. Any suggestions? import Row from "react-bootstrap/Row"; import Col from ...

Bootstrap 3 design with a full screen layout featuring three columns

I'm currently working on developing an administration dashboard for an application, and I require a layout that resembles the following: --------------------------------------------------------------------------------- | ...

Adding space between two Labels with dots in a GridPane layout using JavaFX

Initial Setup: Using a GridPane with 2 Columns Each Column containing a Label https://i.sstatic.net/EkKnl.png Desired Outcome: Filling the space between the labels with dots https://i.sstatic.net/jC7bw.png I've only found String solutions th ...

The element's width set to 100% is not functioning properly when used within a container

Struggling to create a full-width image header but the image always ends up being the width of the container, not 100%. Tried various solutions without success, and the suggested answer here did not solve the issue. Modifying the .container width in custom ...

Making sure that a footer div is consistently positioned at the bottom of the container div, regardless of the dimensions of the other elements

I am facing a challenge with a container div which has child elements. <div class='wrapper'> <div class='content'></div> <div class='footer'></div> </div> The height o ...

Explore the option of selecting linked data using AJAX and PHP

I'm attempting to automatically populate the Material Description field based on the Material Number selection. Both values are stored in the same SQL table. So, when I select a Material, the Material Description should auto-populate. The fields in t ...

Stop duplicate messages from appearing in AJAX chat feature (JavaScript, PHP, MySQL)

I developed a real-time chat system using AJAX, Javascript, PHP, and MySQL. Chat data is sent via JSON from a PHP page that retrieves information from a MySQL database. Each message is stored in an array and fetched through an AJAX call at regular interva ...

Request to api.upcitemdb.com endpoint encountering CORS issue

This code may seem simple, but for some reason, it's not working as expected. What I'm trying to achieve is to call the GET API at: I want to make this API call using either JavaScript or jQuery. I've attempted various approaches, but none ...

How can I add divs to an HTML page with a Javascript animated background?

I am currently facing an issue with my JavaScript animated background, consisting of just 3 pictures. I am trying to display some Div elements on it with content inside. Here is the code snippet I have right now: In my CSS file, I have defined styles for ...

Uploading Images Dynamically with AJAX

Can someone assist me with a multiple upload form that utilizes AJAX to upload and display an image without the need for a submit button? My issue arises when dealing with repeating forms within table rows, causing only the first form to function properly. ...