I have the following JS code to change the color and text of a div, when clicking on each of the divs in my color palette:
var indicadorColor = document.getElementById('indicador-de-color');
var indicadorMensaje = document.getElementById('indicador-de-color-mensaje');
var color = document.getElementsByClassName('color-paleta');
function mostrarColor(){
indicadorColor.style.backgroundColor = this.style.backgroundColor;
indicadorMensaje.innerText = 'PINCEL: ' + this.style.backgroundColor;
}
function seleccionarColor(){
for(i=0; i<color.length; i++){
color[i].addEventListener('click', mostrarColor)
}
}
seleccionarColor();
This works without problems for me, the issue is that I want to pass it to JQuery to save lines of code and when I try the following code it doesn't work for me:
function seleccionarColor(){
var color = $('.color-paleta');
for(i=0; i<color.length; i++){
$(color[i]).click(function() {
$('indicador-de-color').attr('background-color', $(color[i]).css('background-color'));
$('indicador-de-color-mensaje').text($(color[i]).css('background-color'))
}
)}
}
seleccionarColor();
})
I can't see the error :( Can someone give me a hand? Thanks!
The problem is that you need to use the id's flag
#
. Try like this:You can make use of more jQuery properties, like adding a listener and changing each component to
this
, also, when you point to an element by its id, use#