Javascript change color of text and background to input value
Asked Answered
S

4

9

I'm going to use javascript to make a function for changing color of background, as well as text simultaneously - based on the value of a text input. I've got the background color to change, but can't manage to get the text working as well.

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;
}

Looking into the code above, the code for the text document.getElementById("coltext").style.color = x works when I input an actual color, and not the "color" value.

This is the html which of I'm referring to (I know it's horribly optimized, but it's a work in progress):

<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 can't use the code this way. But no matter have hard I try, beyond this, I reach a sort of infinite complexity. It should be a sort of easy way to resolve this, right?

Shagbark answered 18/5, 2013 at 14:55 Comment(3)
With your example, when fixed, then you set the background color and the text color to the same thing, is that what you wanted? Your text will not be visibleBicolor
Also you have an "onchange" handler attached to the text box, and an "onclick" attached to the button. What exactly are you trying to achieve there?Bicolor
@Bicolor As mentioned, the code is a bit of a mess - "a work in progress", I've tried to refer to both of them and I rarely clean up unnecessary stuff until I get it to work. However, keep in mind that I'm referring to the body background (which isn't very clear from the code, but yet irrelevant). My content is white.Shagbark
B
9

Things seems a little confused in the code in your question, so I am going to give you an example of what I think you are try to do.

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 will be removing inline content and splitting these into their appropriate files.

Next, I am going to go with the "click" event and displose of the "change" event, as it is not clear that you want or need both.

Your function changeBackground sets both the backround color and the text color to the same value (your text will not be seen), so I am caching the color value as we don't need to look it up 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);

On jsfiddle

Source: w3schools

Color Values

CSS colors are defined using a hexadecimal (hex) notation for the combination of Red, Green, and Blue color values (RGB). The lowest value that can be given 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 a # sign.

Update: as pointed out by @Ian

Hex can be either 3 or 6 characters long

Source: W3C

Numerical color values

The format of an RGB value in hexadecimal notation is a ‘#’ immediately followed by either three or six hexadecimal characters. The three-digit RGB notation (#rgb) is converted into six-digit form (#rrggbb) by replicating digits, not by adding zeros. For example, #fb0 expands to #ffbb00. This ensures that white (#ffffff) can be specified with the short notation (#fff) and removes any dependencies on the color depth of the display.

Here is an alternative function that will check that your input is a valid CSS Hex Color, it will set the text color only or throw an alert if it is not valid.

For regex testing, I will use this pattern

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

but if you were regex matching and wanted to break the numbers into groups then you would require 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);

On jsfiddle

Here is a further modification that will allow colours by name along with by hex.

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);

On jsfiddle

Bicolor answered 18/5, 2013 at 15:23 Comment(9)
I only ran it in jsfiddle right now and it doesn't function as I'd like it, I can clearly follow your script and I think it should work, as it's essentially the same as mine. Just that you cached the "color" value. However, the text remain unchanged until I give it a non-dynamic value, say "red", then it changes to red when pressing the button. But if you use the value from "color", it does not. This was the problem I had in the first run as well.Shagbark
It's totally my fault. I forgot to specify that it should work with hexadecimal values. And to be honest, I never tried inputting ordinary colors to my code either. However, the background accepts hexadecimal values "ff0000" - for example, whilst the text doesn't. What does that depend on?Shagbark
If I enter "#ff0000" into the text box and then submit, the background turns red and so does the text.Bicolor
You're right, I missed that. The background never required the "#", where of I sort of got used to that. Thank you so much for your help! I'll play around a little with my code to see if I can get everything to work properly.Shagbark
Good, I have one last function that may help you if you need to use color by name along with hexBicolor
If you actually want to get a valid hex, you should use /^#([0-9a-f]{3})([0-9a-f]{3})?$/iChalcopyrite
@Chalcopyrite True, the W3C states 3 (shorthand, repeated twice to give 6) or 6 (the full web colour range). I will update, thanks.Bicolor
In the end, both you and Ian's answer helped me with this, thank you both of you! But your answer really gave a lot more than I was initially going for. It all works now. Cheers!Shagbark
Would the fly by down voter care to comment as to why?Bicolor
C
4

Depending on which event you actually want to use (textbox change, or button click), you can try this:

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 minor problem with the button was that it was a submit button, in a form. When clicked, that submits the form (which ends up just reloading the page) and any changes from JavaScript are reset. Just using the onchange allows you to change the color based on the input.

Chalcopyrite answered 18/5, 2013 at 15:22 Comment(7)
Thank you Ian. However it seems as I forgot to mention, it should work with hexadecimal values. However those do work on the background, even with your code, which seems quite strange to me.Shagbark
@user2395622 What do you mean? What are you actually inputting? You'll have to precede it with a "#"Chalcopyrite
Yes, sorry, that worked. The background never needed me to input the "#". So it seems my initial code worked as well, However I've encountered another problem that I suppose is due to something entirely else - The code doesn't really change to the inputted color, but only flashes it, then return to native color (even if native color is not set/white). Thank you so much for taking your time anyway!Shagbark
@user2395622 Like I said, the button on your page was a submit button inside of a form. When you click that, it submits the form - basically, the page is reloaded and everything is reset. The jsFiddle works because I don't use a submit button/form. So do you actually need to submit a form?Chalcopyrite
However I do need a button. But maybe I can do that by making a button (not in a form), that refers to the function via onclick to run in parallel with with the "onchange" that's set to the text form? Or do I have to decide for either?Shagbark
You can definitely use a button, and you could still use a form. But <input /> elements have a type attribute. Important here, the types are "button" and "submit". Obviously, the "submit" type submits a form when clicked. And yeah, just stick to either the click event of the button, or the change event of the textbox.Chalcopyrite
Ok, I spent about an hour to fiddle around, and ended up with a solution that worked for me. So I removed the form, the button, and got on with Xotic's code, combined it with some suggestions from your side, added a div (as button) with reference to the script. And well, now I can both press enter and use a "button". Thank you, again!Shagbark
B
0

I think if you're changing the style you have to put the value in quotes. So:

document.getElementById("coltext").style.color = `${document.getElementById("color").value}`;

(Don't forget back ticks)

Bluma answered 16/4, 2022 at 1:13 Comment(0)
E
-2
document.getElementById("fname").style.borderTopColor = 'red';
document.getElementById("fname").style.borderBottomColor = 'red';
Everett answered 31/12, 2013 at 9:38 Comment(1)
What does your code do? How does it solve the problem in the question? Add an explanation, some details.Beefwood

© 2022 - 2024 — McMap. All rights reserved.