I'm working on a builder. The user is supposed to click on images that represents html components, and this inject the html in a textarea. The template comes with a main color (background, highlighted text, links etc)
I created a row of buttons, to let the user change the main color (for example #000000).
<button class="change black-color" id="black-color">Black</button>
<button class="change blue-color" id="blue-color">Blue</button>
<button class="change green-color" id="green-color">Green</button> etc....
Then with jquery the clik on button changes all occurences of black to the new color:
$("#myDiv button").click(function(){
var textarea=$('#myTextarea');
if($(this).attr('id') === 'blue-color'){
textarea.html(textarea.html().replace(new RegExp("#000000","g"),"#d20606"));
}else if($(this).attr('id') === 'green-color'){
textarea.html(textarea.html().replace(new RegExp("#000000","g"),'#ff4c00'));
}else if($(this).attr('id') === 'light-color'){
textarea.html(textarea.html().replace(new RegExp("#000000","g"),'#31B7BC'));
}
etc...for all next colors....
My question is : is there a way to shorten the function to make it more dynamic and how can I revert back to black color (the first main color) with RegExp ??
EDIT:
thanks to freedomn-m all this code can be shorten using data-attribute through html..but I still have a question
If I have an array of hexa code, how can I make the following :
I you find a color in the textarea that correspond to one of the color of the array, change all occurences of that color to the button( data-color) clicked by user.
For example :
var color =["#64A70B","#525ca3","#d20606","#ff4c00","#61b09d","#00cbf9","#31B7BC","#4EAB8E"];
$(".change").click(function() {
var colour = $(this).data("color");
var textarea = $('#myTextarea');
textarea.html(textarea.html().replace(color, colour));
});
question from:
https://stackoverflow.com/questions/66045596/how-can-i-revert-to-original-color-if-i-use-replace-and-regexp 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…