Javascript .replace() same character different outcome - javascript

I have a word : google, and I'm changing each character to a specific color, but I can't figure out how to make letters "o" different colors
This is my JS:
var text = $("#typed-strings").html().replace(/e/g, '<span class="red">e</span>').replace(/g/g, '<span class="blue">g</span>').replace(/l/g, '<span class="green">l</span>').replace(/o/g, '<span class="yellow">o</span>');
$("#typed-strings").html(text);
.red {
color: rgb(219, 50, 54);
}
.blue {
color: rgb(72, 133, 237);
}
.green {
color: rgb(60, 186, 84);
}
.yellow {
color: rgb(244, 194, 13);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="typed-strings">google</div>
maybe someone has ideas?
Thanks!
EDIT:
Thanks everyone for such a rich response, my question was edited by a moderator, perhaps that's why you've seen some changes.
I uploaded this tryout on heroku, to make things easier, but yeah, I have this long text, and every time letter "o" shows up I'd like it to either be, red or yellow, html doesn't really matter since it's purely for visualisation, but I've learned a lot from the conversations - thanks!
that's the app:
https://googlefonts.herokuapp.com
EDIT 2:
also added the non-working version within the page

As others have pointed out your issue is that you are replacing g with
<span class="...">g</span>
then replacing all l's in the last string which replaces the l in class.
Another way around this is to use a function for replace. While using a function each match is replaced in turn and any replacements you make are ignored.
Besides that you can use a separate key and boolean to track whether you have replaced the first o already or not. I added this to my example using the boolean as part of the replacement-key for the letter o to simplify things.
var replacements = {
g: '<span class="blue">g</span>',
o0: '<span class="red">o</span>',
o1: '<span class="yellow">o</span>',
l: '<span class="green">l</span>',
e: '<span class="red">e</span>'
};
var ele = $("#typed-strings");
var text = ele.html();
var firstODone = false;
text = text.replace(/[gogle]/g, function (letter) {
var key = letter;
if (key === 'o') {
key = key + (+firstODone); //Convert the boolean to an integer, 0 or 1
firstODone = true;
}
return replacements[key];
})
ele.html(text);
.red {
color: rgb(219, 50, 54);
}
.blue {
color: rgb(72, 133, 237);
}
.green {
color: rgb(60, 186, 84);
}
.yellow {
color: rgb(244, 194, 13);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="typed-strings">google</div>
If you only needed jQuery for this you can easily get rid of it, too. You can use
var ele = document.getElementById("typed-strings");
to get your element and
ele.innerHTML
to get and set your html to the element.
e.g.: ele.innerHTML = text

You might want to use the following regex:
letter + '{1}(?![^<]*\>)'
The above will replace only lowercase single letter G-s that are not inside a tag <>, here is an example:
function replaceWithSpanClass( string, letter, className ){
var regex = new RegExp( letter + '{1}(?![^<]*\>)', 'g' );
return string.replace( regex, '<span class="' + className + '">' + letter + '</span>')
}
var text = 'google';
text = replaceWithSpanClass( text, 'g', 'red' );
text = replaceWithSpanClass( text, 'o', 'blue' );
text = replaceWithSpanClass( text, 'l', 'yellow' );
text = replaceWithSpanClass( text, 'e', 'green' );
document.getElementById('result').innerHTML = text;
.yellow { color: yellow; }
.green { color: green; }
.blue { color: blue; }
.red { color: red; }
<div id="result"></div>
In this case it means that a class like yellow does not get its o replaced by <span class="blue">o</span>. That way you are sure you are only modifying outside your nodes.

<script type="text/javascript">
$(document).ready(() => {
let oldStr = $("#typed-strings").html();
let newStr = '';
for(let i = 0; i < oldStr.length; i++) {
if (oldStr[i] === 'g') {
newStr += '<span class="blue">g</span>'
} else if (oldStr[i] === 'o') {
newStr += '<span class="yellow">o</span>'
}
// Add other letters here
}
$("#typed-strings").html(newStr);
});
</script>

You can create a function that would return the color by the letter and use replace method with callback function like this:
var colors = {
g: 'blue',
o: 'yellow',
l: 'green',
e: 'red'
};
function wrapTheLetter(letter) {
var colorClass = colors[letter];
if (letter == 'o') {
// update it's color for the future
colors.o = 'grey';
}
return '<span class="' + colorClass + '">'+letter+'</span>';
}
var text = $("#typed-strings").html().replace(/\w/g, wrapTheLetter);
$("#typed-strings").html(text);

Related

Find key if text matches value

I'm trying to highlight only the number between the brackets in regular js. Colors are based on value (type of fruit in this scenario).
HTML
<a class="temple" href="something # URL">LARGE FRUIT (215)</a>
<a class="temple" href="something # URL">PINEAPPLE (38)</a>
<a class="temple" href="something # URL">RED APPLE (76)</a>
My Dict
var my_dict = {'BLUE':['ORANGE'], ['GRAPE']
'YELLOW':['PINEAPPLE'], ['KIWI']}
I could do them independently using but it's messy and may break the code if a tag is removed:
let Pineapple = document.querySelector('.temple')
PINEAPPLE.innerHTML = PINEAPPLE.innerHTML.replace(/\([^\)]*\)/, '<span class="red">$&</span>')
This is what I have so far:
function color(){
let fruits = document.querySelector('.temple')
for (let i = 0; i<fruits.length; i++) {
let str = fruits.innerHTML //this gives me the text I need.
My goal is to use the results (value) to find the key and ultimately color just the number.
that ?
const my_dict =
{ BLUE: [ 'ORANGE', 'GRAPE' ]
, YELLOW: [ 'PINEAPPLE', 'KIWI' ]
, RED: [ 'APPLE' ]
};
// ES5 code
const my_dict_reverse =
Object
.keys( my_dict)
.reduce( function(r,k)
{
my_dict[k].forEach( function(fruit) { r[fruit] = k } );
return r;
},{});
// my_dict_reverse = { ORANGE: 'BLUE', GRAPE: 'BLUE', PINEAPPLE: 'YELLOW', KIWI: 'YELLOW', APPLE: 'RED' }
document
.querySelectorAll('.temple')
.forEach( function(el)
{
let pos = el.textContent.search(/\([^\)]*\)/)
, fruit = el.textContent.slice(0,pos)
, val = el.textContent.slice(pos)
, colorClass = my_dict_reverse[ fruit.replace(/^\s+|\s+$/g,'')] || ''
;
el.innerHTML = fruit
+ '<span class="' + colorClass + '">'
+ val +'</span>';
});
/* ES10 code ...
const my_dict_reverse = Object.keys( my_dict).reduce((r,k)=>
{
my_dict[k].forEach(fruit=>r[fruit]=k)
return r
},{})
document.querySelectorAll('.temple').forEach(el=>
{
let [fruit, val] = el.textContent.split(/(?=\()|(?<=\))/)
, colorClass = my_dict_reverse[ fruit.trim()] ?? ''
;
el.innerHTML = `${fruit}<span class="${colorClass}">${val}</span>`
})
*/
body { background: steelblue; }
a.temple {
color : black;
float : left;
clear : both;
text-decoration : none;
}
span.RED { color : red; }
span.BLUE { color : blue; }
span.YELLOW { color : yellow; }
<a class="temple" href="something # URL">LARGE FRUIT (215)</a>
<a class="temple" href="something # URL">PINEAPPLE (38)</a>
<a class="temple" href="something # URL">APPLE (76)</a>

Format color while typing in textarea or pre

I'm trying to create a comments section that lets users #someone. When the user types #random and then space, I want it to be highlighted. So I've created something that searches and replaces the string, but I then when the html is replaced, it places the cursor at the beginning. Any way to solve this? Any other way of doing something like this?
$('#textarea').keyup(function() {
txt = this.innerText.split(" ")
new_txt = this.innerText
for (var i = txt.length - 1; i >= 0; i--) {
if (txt[i].startsWith('#') == false) {
delete txt[i]
}
}
txt = txt.sort().join(" ").trim().split(" ")
console.log(txt)
if (txt.length > 0 && txt[0] != "") {
for (var i = 0; i < txt.length; i++) {
new_txt = new_txt.replace(txt[i], '<mark>' + txt[i] + '</mark>')
}
$('#my_console_log').text(new_txt)
this.innerHTML = new_txt
}
});
pre {
border: solid black 1px;
}
mark {
background: blue;
color: red;
}
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<title>Test page</title>
<form>
<pre id='textarea' contentEditable='true'></pre>
<div id="my_console_log"></div>
</form>
Here is a simple plugin available which can be useful to you,
Download the plugin and edit the file jquery.hashtags.js and remove the condition for #. You can also change the style as per your requirement.
(function($) {
$.fn.hashtags = function() {
$(this).wrap('<div class="jqueryHashtags"><div class="highlighter"></div></div>').unwrap().before('<div class="highlighter"></div>').wrap('<div class="typehead"></div></div>');
$(this).addClass("theSelector");
autosize($(this));
$(this).on("keyup", function() {
var str = $(this).val();
$(this).parent().parent().find(".highlighter").css("width",$(this).css("width"));
str = str.replace(/\n/g, '<br>');
if(!str.match(/(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,#?^=%&:\/~+#-]*[\w#?^=%&\/~+#-])?#([a-zA-Z0-9]+)/g) && !str.match(/(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,#?^=%&:\/~+#-]*[\w#?^=%&\/~+#-])?#([a-zA-Z0-9]+)/g) && !str.match(/(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,#?^=%&:\/~+#-]*[\w#?^=%&\/~+#-])?#([\u0600-\u06FF]+)/g) && !str.match(/(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,#?^=%&:\/~+#-]*[\w#?^=%&\/~+#-])?#([\u0600-\u06FF]+)/g)) {
// Remove below condition for hashtag.
if(!str.match(/#(([_a-zA-Z0-9]+)|([\u0600-\u06FF]+)|([ㄱ-ㅎㅏ-ㅣ가-힣]+)|([ぁ-んァ-ン]+)|([一-龯]+))#/g)) { //arabic support, CJK support
str = str.replace(/#(([_a-zA-Z0-9]+)|([\u0600-\u06FF]+)|([ㄱ-ㅎㅏ-ㅣ가-힣]+)|([ぁ-んァ-ン]+)|([一-龯]+))/g,'<span class="hashtag">#$1</span>');
}else{
str = str.replace(/#(([_a-zA-Z0-9]+)|([\u0600-\u06FF]+)|([ㄱ-ㅎㅏ-ㅣ가-힣]+)|([ぁ-んァ-ン]+)|([一-龯]+))#(([_a-zA-Z0-9]+)|([\u0600-\u06FF]+)|([ㄱ-ㅎㅏ-ㅣ가-힣]+)|([ぁ-んァ-ン]+)|([一-龯]+))/g,'<span class="hashtag">#$1</span>');
}
// Keep this condition.
if(!str.match(/#(([a-zA-Z0-9]+)|([\u0600-\u06FF]+)|([ㄱ-ㅎㅏ-ㅣ가-힣]+)|([ぁ-んァ-ン]+)|([一-龯]+))#/g)) {
str = str.replace(/#(([a-zA-Z0-9]+)|([\u0600-\u06FF]+)|([ㄱ-ㅎㅏ-ㅣ가-힣]+)|([ぁ-んァ-ン]+)|([一-龯]+))/g,'<span class="hashtag">#$1</span>');
}else{
str = str.replace(/#(([a-zA-Z0-9]+)|([\u0600-\u06FF]+)|([ㄱ-ㅎㅏ-ㅣ가-힣]+)|([ぁ-んァ-ン]+)|([一-龯]+))#(([a-zA-Z0-9]+)|([\u0600-\u06FF]+)|([ㄱ-ㅎㅏ-ㅣ가-힣]+)|([ぁ-んァ-ン]+)|([一-龯]+))/g,'<span class="hashtag">#$1</span>');
}
}
$(this).parent().parent().find(".highlighter").html(str);
});
$(this).parent().prev().on('click', function() {
$(this).parent().find(".theSelector").focus();
});
};
})(jQuery);
Instead of replacing the html just append a class with the color that you want

regex to replace strings with img - js

hey there I am currently having the issues that I want to detect strings in a text with an image.
{"a":"img1.jpg", "ab":"img2.jpg"}
my current regex is:
/(a|ab)/g
When I have a text like:
yeah abc
it replaces the "a" in the yeah with img1.jpg but it also replaces the "ab"c with "img1.jpg".
I can avoid it through switching /(ab|a)/ but this is can't be the solution, since I have a huge unsorted json list as expressions (a, ab is just for simplicity). The reason I am doing this is to replace native emojis with images.
How can I say, that it only replaces the a if there is no b following?
Sort the emoji keys in descendig order, then build your regex pattern like this:
function replaceEmojis (str) {
const emojis = {
a: { src: 'imgA.jpg', color: 'red' },
abc: { src: 'imgABC.jpg', color: 'green' },
ab: { src: 'imgAB.jpg', color: 'blue' },
bc: { src: 'imgBC.jpg', color: 'orange' }
};
const fnDescendingOrder = ([x, y]) => x > y ? -1 : +(x != y);
const keys = Object.keys(emojis).sort((x, y) =>
fnDescendingOrder(x.length == y.length ? [x, y] : [x.length, y.length])
);
const pattern = new RegExp(keys.join('|'), 'g');
const transformed = str.replace(pattern, m => {
const emoji = emojis[m];
return '<img class="' + emoji.color + '" src="' + emoji.src + '">';
});
return transformed;
};
let str = 'yeah abc ab a abca bcaba';
result.innerHTML = replaceEmojis(str);
img { width: 10px; height: 100%; }
img.red { background: red; }
img.green { background: green; }
img.blue { background: blue; }
img.orange { background: orange; }
<div id="result"></div>
You have to sort in descending order first by length, next by alphabetical order. Cause bc should be checked after abc.

javascript appending span to text [duplicate]

This question already has answers here:
How to append text to a div element?
(12 answers)
Closed 5 years ago.
I'm currently trying to build my javascript function that gives css styles to every character in an element. Specifically, this function takes in an element, takes the text content in it, stores the text into an array and then create a bunch of spans to append to the text. Right now it seems like my code runs and when I check the variables in chrome dev tools, they return the correct values. However, when I actually implement this code, nothing changes visually but in the dev tools, I get my correct value of <span style="style i chose" > text </span>. Not sure what I did wrong here
var array = [];
var spanarray = [];
var words = document.getElementsByClassName("example")[0];
function fadeInByLetter () {
for(var i = 0; i < words.innerHTML.length;i++){
array.push(words.innerHTML[i]);
var span = document.createElement("span");
var textNode = document.createTextNode(array[i]);
span.appendChild(textNode);
var spancomplete = span;
spanarray.push(spancomplete);
}
for(var i = 0; i < array.length;i++){
spanarray[i].style.color = "red";
spanarray[i].style.background = "pink";
}
}
fadeInByLetter();
var array = [];
var spanarray = [];
var words = document.getElementsByClassName("example")[0];
function fadeInByLetter () {
for(var i = 0; i < words.innerHTML.length;i++){
array.push(words.innerHTML[i]);
var span = document.createElement("span");
var textNode = document.createTextNode(array[i]);
span.appendChild(textNode);
var spancomplete = span;
spanarray.push(spancomplete);
}
words.innerHTML="";
for(var i = 0; i < array.length;i++){
spanarray[i].style.color = "red";
spanarray[i].style.background = "pink";
words.appendChild(spanarray[i]);
}
}
fadeInByLetter();
The solution above should fix the problem. However you have some performance issues. You should save words.innerHTML in a string first. Then use the string instead of words.innerHTML.
That should do the trick:
function fadeInByLetter (wordsContainer) {
// extract text from the container and transform into array
var chars = wordsContainer.innerHTML.split('')
//clear the container
while (wordsContainer.firstChild) {
wordsContainer.removeChild(wordsContainer.firstChild);
}
for(var i = 0; i < chars.length;i++){
var span = document.createElement("span");
var textNode = document.createTextNode(chars[i]);
span.appendChild(textNode);
span.style.color = "red";
span.style.background = "pink";
// append new element
wordsContainer.appendChild(span)
}
}
fadeInByLetter(document.getElementsByClassName("example")[0]);
FYI: There is a library that does this same type of thing.
It's called lettering https://github.com/davatron5000/Lettering.js
Here is a demo using this library.
The library depends upon jQuery but there is also a version of this lib that uses plain javascript. See https://github.com/davatron5000/Lettering.js/wiki/More-Lettering.js
$(document).ready(function() {
$(".example").lettering();
});
//////////////// LETTERING SOURCE BELOW /////////////////////////////
//fadeInByLetter();
/*global jQuery */
/*!
* Lettering.JS 0.7.0
*
* Copyright 2010, Dave Rupert http://daverupert.com
* Released under the WTFPL license
* http://sam.zoy.org/wtfpl/
*
* Thanks to Paul Irish - http://paulirish.com - for the feedback.
*
* Date: Mon Sep 20 17:14:00 2010 -0600
*/
(function($) {
function injector(t, splitter, klass, after) {
var text = t.text(),
a = text.split(splitter),
inject = '';
if (a.length) {
$(a).each(function(i, item) {
inject += '<span class="' + klass + (i + 1) + '" aria-hidden="true">' + item + '</span>' + after;
});
t.attr('aria-label', text)
.empty()
.append(inject)
}
}
var methods = {
init: function() {
return this.each(function() {
injector($(this), '', 'char', '');
});
},
words: function() {
return this.each(function() {
injector($(this), ' ', 'word', ' ');
});
},
lines: function() {
return this.each(function() {
var r = "eefec303079ad17405c889e092e105b0";
// Because it's hard to split a <br/> tag consistently across browsers,
// (*ahem* IE *ahem*), we replace all <br/> instances with an md5 hash
// (of the word "split"). If you're trying to use this plugin on that
// md5 hash string, it will fail because you're being ridiculous.
injector($(this).children("br").replaceWith(r).end(), r, 'line', '');
});
}
};
$.fn.lettering = function(method) {
// Method calling logic
if (method && methods[method]) {
return methods[method].apply(this, [].slice.call(arguments, 1));
} else if (method === 'letters' || !method) {
return methods.init.apply(this, [].slice.call(arguments, 0)); // always pass an array
}
$.error('Method ' + method + ' does not exist on jQuery.lettering');
return this;
};
})(jQuery);
span {
font-size: 74px;
font-family: Arial;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 11px;
display: inline-block;
}
.char1 {
color: red;
transform: rotateZ(-10deg);
}
.char2 {
color: blue;
transform: rotateZ(-12deg);
}
.char3 {
color: purple;
transform: rotateZ(12deg);
}
.char4 {
color: pink;
transform: rotateZ(-22deg);
}
.char5 {
color: yellow;
transform: rotateZ(-12deg);
}
.char6 {
color: gray;
transform: rotateZ(22deg);
}
.char7 {
color: orange;
transform: rotateZ(10deg);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="example">Example</span>

Comparing RGB colors in JavaScript

I'm trying to compare two RGB colors in a guessing game. There are 6 squares with 6 different colors. When the user clicks on the color that matches pickedColor, the result should be 'Correct!'. But I never get that result.
This is my code:
var colors = [
"rgb(255,0,0)",
"rgb(255,255,0)",
"rgb(0,255,0)",
"rgb(0,255,255)",
"rgb(0,0,255)",
"rgb(255,0,255)"
];
var squares = document.querySelectorAll(".square");
var pickedColor = colors[3];
var colorDisplay = document.getElementById("colorDisplay");
colorDisplay.textContent = pickedColor;
for (var i = 0; i < squares.length; i++) {
//add initinal colors to squares
squares[i].style.background = colors[i];
//add the click listener to the squares
squares[i].addEventListener("click", function () {
var clickedColor = this.style.background;
if (clickedColor === pickedColor) alert("Correct!");
else alert("Incorrect!");
});
}
Ok so I set up an example here and it looks like the problem is that your initial set of colours don't have spaces between the commas:
var colors = [
"rgb(255,0,0)",
"rgb(255,255,0)",
"rgb(0,255,0)",
"rgb(0,255,255)",
"rgb(0,0,255)",
"rgb(255,0,255)"
];
clickedColor has no spaces and the pickedColor does, so changing this to:
var colors = [
"rgb(255, 0, 0)",
"rgb(255, 255, 0)",
"rgb(0, 255, 0)",
"rgb(0, 255, 255)",
"rgb(0, 0, 255)",
"rgb(255, 0, 255)"
];
Should do the trick.
The trouble is that the color expression 'rgb(0,255,255)' is formatted differently by the browser. In the test clickedColor === pickedColor, you're comparing two strings that no longer look the same even if they represent the same color.
Different browsers can represent an RGB color in different ways, so it's unsafe to pick a particular format. A better approach is to extract the color components from the strings and compare the component values one by one, as in the code below.
function rgbExtract(s) {
var match = /^\s*rgb\(\s*(\d+),\s*(\d+),\s*(\d+)\)\s*$/.exec(s);
if (match === null) {
return null;
}
return { r: parseInt(match[1], 10),
g: parseInt(match[2], 10),
b: parseInt(match[3], 10) };
}
function rgbMatches(sText, tText) {
var sColor = rgbExtract(sText),
tColor = rgbExtract(tText);
if (sColor === null || tColor === null) {
return false;
}
var componentNames = [ 'r', 'g', 'b' ];
for (var i = 0; i < componentNames.length; ++i) {
var name = componentNames[i];
if (sColor[name] != tColor[name]) {
return false;
}
}
return true;
}
The rgbMatches function is demonstrated in the following snippet. You'll see that you can now click on the square with the correct color and you'll get the appropriate message even though the underlying RGB strings are formatted differently.
var colors = [
"rgb(255,0,0)",
"rgb(255,255,0)",
"rgb(0,255,0)",
"rgb(0,255,255)",
"rgb(0,0,255)",
"rgb(255,0,255)"
];
var squares = document.querySelectorAll(".square");
var pickedColor = colors[3];
var colorDisplay = document.getElementById("colorDisplay");
colorDisplay.textContent = pickedColor;
function message(s) {
document.getElementById('messageContainer').innerHTML = s;
}
function rgbExtract(s) {
var match = /^\s*rgb\(\s*(\d+),\s*(\d+),\s*(\d+)\)\s*$/.exec(s);
if (match === null) {
return null;
}
return { r: parseInt(match[1], 10),
g: parseInt(match[2], 10),
b: parseInt(match[3], 10) };
}
function rgbMatches(sText, tText) {
var sColor = rgbExtract(sText),
tColor = rgbExtract(tText);
if (sColor === null || tColor === null) {
return false;
}
var componentNames = [ 'r', 'g', 'b' ];
for (var i = 0; i < componentNames.length; ++i) {
var name = componentNames[i];
if (sColor[name] != tColor[name]) {
return false;
}
}
return true;
}
for (var i = 0; i < squares.length; ++i) {
var square = squares[i];
square.style.background = colors[i];
square.addEventListener("click", function () {
var clickedColor = this.style.background;
if (rgbMatches(clickedColor, pickedColor)) {
message('Correct! ' + clickedColor + ' matches ' + pickedColor);
} else {
message('Incorrect. ' + clickedColor + ' doesn\'t match ' + pickedColor);
}
});
}
body {
font-family: sans-serif;
}
.square {
display: inline-block;
margin: 5px;
width: 50px;
height: 50px;
border: 1px solid #888;
cursor: pointer;
}
.output {
margin: 10px 5px;
}
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="output" id="colorDisplay"></div>
<div class="output" id="messageContainer"></div>
I would be wary of comparing two rgb strings like this. Different browsers may store style background colors differently (as you have already discovered).
I would suggest writing a custom comparison function which parses two rgb strings and compares them.
Or you could convert them to hex color values and compare those instead.
Do not trust the color returned by the browser. Different browsers will use different formats.
Instead, use classes or data-* attributes to set the color, and check that:
var colors = ["red", "yellow", "lime", "cyan", "blue", "fuchsia"],
squares = document.querySelectorAll(".square"),
pickedColor = colors[Math.floor(Math.random()*colors.length)],
message = document.getElementById("messageContainer");
document.getElementById("colorDisplay").textContent = pickedColor;
for (var i = 0; i < squares.length; ++i) {
squares[i].setAttribute('data-color', colors[i]);
squares[i].addEventListener("click", function () {
var clickedColor = this.getAttribute('data-color');
message.textContent = clickedColor === pickedColor
? "Correct!" : "Incorrect!";
});
}
.square {
display: inline-block;
margin: 5px;
width: 50px;
height: 50px;
border: 1px solid #888;
cursor: pointer;
}
.output {
margin: 10px 5px;
}
[data-color=red] { background: rgb(255,0,0) }
[data-color=yellow] { background: rgb(255,255,0) }
[data-color=lime] { background: rgb(0,255,0) }
[data-color=cyan] { background: rgb(0,255,255) }
[data-color=blue] { background: rgb(0,0,255) }
[data-color=fuchsia] { background: rgb(255,0,255) }
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="output" id="colorDisplay"></div>
<div class="output" id="messageContainer"></div>

Categories