Jquery: applying background color to div after append method

I'm trying to create a dynamic color bookmarker just to practice jquery, however, I'm having an issue using the append method to make a new div and applying a css background method to apply the text of the div (the input) as the color of the individual div. My problem is not getting the background color applied. I'm not quite sure what I'm doing wrong or why my .css() method isn't working. Thanks for the answers so far!

var colorIn = $("#materialColorInput");
var matDes = $(".material-design");

colorIn.keypress(function (event) {
  if (event.which === 13) {
    var inVal = colorIn.val();
    var color = $(".color");
    colorIn.val("");
    function addBackColor() { 
        $("this").css('background-color', $(this).text())
    };
    var addDiv = $('<div onload="addBackColor()">' +inVal+ '</div>').addClass("color");
    matDes.append(addDiv);
  }
});

I've also made a pen for it: http://codepen.io/Aricha03/pen/KzqXmr

Answers 1

  • Remove the quotes for the color value

    var colorIn = $("#materialColorInput");
    var matDes = $(".material-design");
    
    colorIn.keypress(function(event){
        if(event.which ===13){
            var newDiv = colorIn.val();
            colorIn.val("");
            matDes.append('<div class="color">' + newDiv + '</div>');
            var color = $(".color");
            color.each(function(){
                var backColor = $(this).text();
                $(this).css('background-color', backColor);  //I removed quotes for the backcolor and r missing in background color
                            alert(backColor);
            });        
        }
    });
    

Related Articles