-1

Q1.

I have a total of 7 divs (class name: scale-up-center0 ~ 7), I want to represent numbers 1 through 7 using a javascript variable.

I tried the for statement, but it did not work.

I want scale-up-center7 to change color when scale-up-center0-6 is clicked.

How do I use a javascript variable for a css class name?

not working code

$(document).ready(function() {
        for(var i=0; i<7; i++) {
        $(".scale-up-center-<%=i%>").click(function() {
            var color = $(".scale-up-center-<%=i%>).css("background-color");
            $(".scale-up-center7").css("background-color", color);
            $("#post_color").val(color);
        }

    })
})

Q2.

I imported the css property (background-color) through jquery and stored it in the color column.

And displays the color through the input of the form. However, it is expressed in the form of rgb (255,0,0).

I have a color column in the DB, but it is a string type, and rgb () does not.

I want to import the color name rather than rgb. (ex) return "red", instead of rgb (255,0,0)

_form.html.erb

  <div class="field">
    <%= form.label :color %>
    <%= form.text_area :color, id: 'post_color' %>
  </div>
dsfdsf2fafad
  • 321
  • 2
  • 12

1 Answers1

0

Q1. Try to use $(".scale-up-center-" + i) instead of $(".scale-up-center-<%=i%>")

Q2. Saving a color as CSS color name could be a little bit tricky. I suggest you to convert RGB to HEX (this question could help) and convert it to color name with CSS colors list (e.g from here css-color-names).

Igor
  • 809
  • 5
  • 16
  • thank you! However, if you type a direct value (".scale-up-center" + i) as var i = 2 ;, for (var i = 0; i <7; i ++) does not work. – dsfdsf2fafad Aug 23 '18 at 08:45
  • Is it `(".scale-up-center" + i)` or `(".scale-up-center-" + i)`? – Igor Aug 23 '18 at 09:07
  • My class names consist of .scale-up-center0 ~ 7! ex)
    And I used it. (".scale-up-center" + i) //// var i = 2; $ (". scale-up-center2"). click ..... This works fine It does not work when using the for statement using the variable i.
    – dsfdsf2fafad Aug 23 '18 at 09:10
  • You mustn't change `i` value inside the cycle. If you want to do something specific with the 2nd element better do something like: `for(var i=0; i<7; i++) { if (i === 2) { do something } ... }` – Igor Aug 23 '18 at 09:15
  • Yes. I did a test on scale-up-center2. //// for(var i=0; i<7; i++) { (i === 2) {code ... include $ (". scale-up-center" + i) .click (function () {... I used ... but it does not work. – dsfdsf2fafad Aug 23 '18 at 09:27