views:

105

answers:

3

I am trying to make a script that when you type in a hex value and press submit itchanges the text color to the color inputted.

It seems the problem is the way i am calling the variable "userInput" inside the variable new html

Any Ideas?

<script type="text/javascript">

function changeText3(){
    var userInput = document.getElementById('userInput').value;
    var oldHTML = document.getElementById('para').innerHTML;
    var newHTML = "<span style='color:userInput'>" + oldHTML + "</span>";
    document.getElementById('para').innerHTML = newHTML;
}

</script>

<p id='para'>Welcome to the site <b>dude</b> </p> 
<input type='text' id='userInput' value='#' />
<input type='button' onclick='changeText3()' value='Change Text'/>
+1  A: 

It's just the one line that's causing the problem:

var newHTML = "<span style='color:" + userInput + "'>" + oldHTML + "</span>";
thenduks
A: 

Hi, you need to "inject" the userInput variable into your newHTML variable. See below;

<script type="text/javascript">

function changeText3(){
    var userInput = document.getElementById('userInput').value;
    var oldHTML = document.getElementById('para').innerHTML;
    var newHTML = "<span style='color:" + userInput + "'>" + oldHTML + "</span>";
    document.getElementById('para').innerHTML = newHTML;
}

</script>

<p id='para'>Welcome to the site <b>dude</b> </p> 
<input type='text' id='userInput' value='#' />
<input type='button' onclick='changeText3()' value='Change Text'/>
Pace
this works, but now the problem is that i didn't think this through properly because it can only change once, so i gotta start over
Dasa
see my answer - it will work more than once ;)
Ghommey
+6  A: 

I would suggest to use the style reference instead of adding more and more spans:

document.getElementById('para').style.color = userInput;
Ghommey
works like a charm, thanks
Dasa