2

I am trying to create a function to update CSS based on user input and I have it working except for the CSS property parameter.

$(document).ready(function() {
  $('input').blur(function() {
    var inputName = $(this).attr("name");
    updateCSS(inputName, 'button-style-one', 'background-color');
  })

  // Function to update CSS
  function updateCSS(pInputNameAttribute, pElementClass, pCssProperty) {
    var inputName = '[name=' + pInputNameAttribute + ']',
      elementClass = '.' + pElementClass,
      inputValue = $(inputName).val();

    $(elementClass).css({
      pCssProperty: inputValue
    });
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="submit.php" method="post" id="buttonSettings">
  <input type="text" name="button_background_color" placeholder="Background Color">
</form>

<a href="#" class="button-style-one">Button</a>

This works if I replace pCssProperty: inputValue with 'background-color': inputValue, but I need the CSS property to be a parameter of the function - how can I get this to work property with a variable? JSFiddle: https://jsfiddle.net/frafgdnq/10/

Daniel Beck
  • 20,653
  • 5
  • 38
  • 53
m-use
  • 363
  • 1
  • 4
  • 16
  • When you define an object, like the one that jQuery's `.css()` method takes as an argument, you're allowed to have property names without quotes. Variables normally won't be interpolated on the left side of the colon. So, your code was trying to set a CSS property that was literally named `pCssProperty`. – Vince Mar 26 '18 at 23:54

1 Answers1

4

You can access the contents of pCssProperty for your css object by creating the object first and then assigning the key:

var cssObj = {};
cssObj[pCssProperty] = inputValue;
$(elementClass).css(cssObj);

...or use this ES6 shorthand to do the same thing:

$(elementClass).css({[pCssProperty]: inputValue})

$(document).ready(function() {
  $('input').blur(function() {
    var inputName = $(this).attr("name");
    updateCSS(inputName, 'button-style-one', 'background-color');
  })

  // Function to update CSS
  function updateCSS(pInputNameAttribute, pElementClass, pCssProperty) {
    var inputName = '[name=' + pInputNameAttribute + ']',
      elementClass = '.' + pElementClass,
      inputValue = $(inputName).val();

    $(elementClass).css({
      [pCssProperty]: inputValue
    });
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="submit.php" method="post" id="buttonSettings">
  <input type="text" name="button_background_color" placeholder="Background Color">
</form>

<a href="#" class="button-style-one">Button</a>
Daniel Beck
  • 20,653
  • 5
  • 38
  • 53
  • +1 I knew what was happening, but I didn't know you could put a variable in square brackets to get the value in an object definition. – Vince Mar 26 '18 at 23:55