Javascript changes the color of text and background to input value

I am going to use javascript to create a function to change the background color, as well as the text at the same time - based on the value of the text input. My background color is changing, but it cannot make the text work.

function changeBackground() { // The working function for changing background color. document.bgColor = document.getElementById("color").value; // The code I'd like to use for changing the text simultaneously - however it does not work. document.getElementById("coltext").style.color = document.getElementById("color").value; } 

Taking a look at the code above, the code for the text document.getElementById("coltext").style.color = x works when I enter the actual color, not the value "color".

This is the html I'm talking about (I know it is terribly optimized, but it works):

 <form id="TheForm" style="margin-left:396px;"> <input id="color" type="text" onchange="changeBackground();" /> <br/><input id="submitColor" value="Submit" type="button" onclick="changeBackground();" style="margin-left:48px; margin-top:5px;" /> </form> <span id="coltext">This text should have the same color as you put in the text box</span> 

Obviously, and unfortunately, I cannot use the code this way. But, in spite of everything, I try, besides this, to achieve some infinite complexity. It should be a kind of easy way to resolve this, right?

+4
source share
3 answers

Your question seems a bit confused in the code, so I will give you an example of what I think you are trying to do.

The first considerations are about mixing HTML, Javascript, and CSS:

Why is using onClick () in HTML a bad practice?

Unobtrusive Javascript

Inline Styles vs Classes

I delete the embedded content and split it into the corresponding files.

Then I'm going to go with the "click" event and throw out the "change" event, since it is not clear what you want or need both.

Your changeBackground function sets the background color and text color to the same value (the text will not be displayed), so I cache the color value, since we do not need to look for it in the DOM twice.

CSS

 #TheForm { margin-left: 396px; } #submitColor { margin-left: 48px; margin-top: 5px; } 

HTML

 <form id="TheForm"> <input id="color" type="text" /> <br/> <input id="submitColor" value="Submit" type="button" /> </form> <span id="coltext">This text should have the same color as you put in the text box</span> 

Javascript

 function changeBackground() { var color = document.getElementById("color").value; // cached // The working function for changing background color. document.bgColor = color; // The code I'd like to use for changing the text simultaneously - however it does not work. document.getElementById("coltext").style.color = color; } document.getElementById("submitColor").addEventListener("click", changeBackground, false); 

Jsfiddle on

Source: w3schools

Color values

CSS colors are defined using hexadecimal (hexadecimal) notation for a combination of red, green, and blue (RGB) colors. the lowest value that can be assigned to one of the light sources is 0 (hex 00). The highest value is 255 (hex FF).

Hex values ​​are written as 3 double-digit numbers, starting with the C # character.

Update : as indicated by @Ian

Hex can be 3 to 6 characters long

Source: W3C

Numeric color values

The format of the RGB value in hexadecimal notation is β€œ#” followed by either three or six hexadecimal characters. The three-digit RGB symbol (#rgb) is converted to a six-digit form (#rrggbb) by duplicating the numbers, rather than adding zeros. For example, # fb0 expands to # ffbb00. This ensures that white (#ffffff) can be specified with a short note (#fff) and removes any dependencies on the color depth of the display.

Here is an alternative function that will verify that your input is valid CSS Hex Color, it will only set the color of the text, or will raise a warning if it is invalid.

When retesting, I will use this template

 /^#(?:[0-9a-f]{3}){1,2}$/i 

but if you matched the regular expression and wanted to break the numbers into groups, you will need a different pattern

 function changeBackground() { var color = document.getElementById("color").value.trim(), rxValidHex = /^#(?:[0-9a-f]{3}){1,2}$/i; if (rxValidHex.test(color)) { document.getElementById("coltext").style.color = color; } else { alert("Invalid CSS Hex Color"); } } document.getElementById("submitColor").addEventListener("click", changeBackground, false); 

Jsfiddle on

Here is another modification that will allow colors by name along with hexadecimal.

 function changeBackground() { var names = ["AliceBlue", "AntiqueWhite", "Aqua", "Aquamarine", "Azure", "Beige", "Bisque", "Black", "BlanchedAlmond", "Blue", "BlueViolet", "Brown", "BurlyWood", "CadetBlue", "Chartreuse", "Chocolate", "Coral", "CornflowerBlue", "Cornsilk", "Crimson", "Cyan", "DarkBlue", "DarkCyan", "DarkGoldenRod", "DarkGray", "DarkGrey", "DarkGreen", "DarkKhaki", "DarkMagenta", "DarkOliveGreen", "Darkorange", "DarkOrchid", "DarkRed", "DarkSalmon", "DarkSeaGreen", "DarkSlateBlue", "DarkSlateGray", "DarkSlateGrey", "DarkTurquoise", "DarkViolet", "DeepPink", "DeepSkyBlue", "DimGray", "DimGrey", "DodgerBlue", "FireBrick", "FloralWhite", "ForestGreen", "Fuchsia", "Gainsboro", "GhostWhite", "Gold", "GoldenRod", "Gray", "Grey", "Green", "GreenYellow", "HoneyDew", "HotPink", "IndianRed", "Indigo", "Ivory", "Khaki", "Lavender", "LavenderBlush", "LawnGreen", "LemonChiffon", "LightBlue", "LightCoral", "LightCyan", "LightGoldenRodYellow", "LightGray", "LightGrey", "LightGreen", "LightPink", "LightSalmon", "LightSeaGreen", "LightSkyBlue", "LightSlateGray", "LightSlateGrey", "LightSteelBlue", "LightYellow", "Lime", "LimeGreen", "Linen", "Magenta", "Maroon", "MediumAquaMarine", "MediumBlue", "MediumOrchid", "MediumPurple", "MediumSeaGreen", "MediumSlateBlue", "MediumSpringGreen", "MediumTurquoise", "MediumVioletRed", "MidnightBlue", "MintCream", "MistyRose", "Moccasin", "NavajoWhite", "Navy", "OldLace", "Olive", "OliveDrab", "Orange", "OrangeRed", "Orchid", "PaleGoldenRod", "PaleGreen", "PaleTurquoise", "PaleVioletRed", "PapayaWhip", "PeachPuff", "Peru", "Pink", "Plum", "PowderBlue", "Purple", "Red", "RosyBrown", "RoyalBlue", "SaddleBrown", "Salmon", "SandyBrown", "SeaGreen", "SeaShell", "Sienna", "Silver", "SkyBlue", "SlateBlue", "SlateGray", "SlateGrey", "Snow", "SpringGreen", "SteelBlue", "Tan", "Teal", "Thistle", "Tomato", "Turquoise", "Violet", "Wheat", "White", "WhiteSmoke", "Yellow", "YellowGreen"], color = document.getElementById("color").value.trim(), rxValidHex = /^#(?:[0-9a-f]{3}){1,2}$/i, formattedName = color.charAt(0).toUpperCase() + color.slice(1).toLowerCase(); if (names.indexOf(formattedName) !== -1 || rxValidHex.test(color)) { document.getElementById("coltext").style.color = color; } else { alert("Invalid CSS Color"); } } document.getElementById("submitColor").addEventListener("click", changeBackground, false); 

Jsfiddle on

+6
source

Depending on which event you really want to use ( change text box or click button), you can try the following:

HTML:

 <input id="color" type="text" onchange="changeBackground(this);" /> <br /> <span id="coltext">This text should have the same color as you put in the text box</span> 

JS:

 function changeBackground(obj) { document.getElementById("coltext").style.color = obj.value; } 

DEMO: http://jsfiddle.net/6pLUh/

One of the minor issues with the button was that it was a submit button on the form. When you click a button that submits a form (which ends only with a page reload), and any changes with JavaScript reset. Just using onchange , you can change the color based on input.

+2
source
 document.getElementById("fname").style.borderTopColor = 'red'; document.getElementById("fname").style.borderBottomColor = 'red'; 
-1
source

Source: https://habr.com/ru/post/1481527/


All Articles