user7133318 user7133318 - 12 days ago 7
Javascript Question

Javascript Uncaught TypeError: Cannot read property 'style' of undefined(…)

Hello I have the following code:

I want to be able to change the background color of the inputs when they are clicked. As well as do other things.





var bp = false;
var np = false;
var b = false;
var i = false;
var u = false;

function iFrameOn(){
richTextField.document.designMode = 'On';
}
function iBold(){
richTextField.document.execCommand('Bold',false,null);
if(b == false){
b = true;
document.getElementById['btn1'].style.backgroundColor = 'red';
}else if(b == true){
b = false;
document.getElementById['btn1'].style.backgroundColor = 'red';
}
}

<center>
<div>
<input class="buttonOnBar" id="btn1" type="button" value="" onClick="javascript:iBold();" style="background-image: url('img/icons/bold.png');" title="Bold text">
<input class="buttonOnBar" id="btn2" type="button" value="" onClick="javascript:iUnderline();" style="background-image: url('img/icons/underline.png');"title="Underlined text">
<input class="buttonOnBar" id="btn3" type="button" value="" onClick="javascript:iItalic();" style="background-image: url('img/icons/italic.png');"title="Italic text">
<input class="buttonOnBar" id="btn4" type="button" value="" onClick="javascript:iUnorderedList();" style="background-image: url('img/icons/numberPoint.png');"title="Numbered list">
<input class="buttonOnBar" id="btn5" type="button" value="" onClick="javascript:iOrderedList();" style="background-image: url('img/icons/bulletPoint.png');"title="Bullet point list">
<input class="buttonOnBar" id="btn6" type="button" value="" onClick="javascript:iLink();" style="background-image: url('img/icons/link.png');"title="Insert link">
<input class="buttonOnBar" id="btn7" type="button" value="" onClick="javascript:iImage();" style="background-image: url('img/icons/picture.png');"title="Insert image">
</div>
</center>

<textarea style="display:none;"id="postTextStyle" name="Text" cols="100" rows="14"></textarea>
<center><iframe name="richTextField" id="richTextField" style="border:#000000 1px solid; width:700px;height:300px;"></iframe></center>

<textarea id="postTagStyle" name="desc" rows="2" maxlength = "1000" placeholder="Description"></textarea>

<center><input type="button" value="Post" style="margin-top:40px;"class = "Post2" onClick="javascript:submit_form();"></center>

</form>

<br>
<script type="text/javascript"src="WYSIWYG.js"></script>





For whatever reason i keep getting the error that is in the title when i click the input button. Why do I get this error and why doesn't the color change?

Answer

Did you mean

document.getElementById('btn1').style.backgroundColor = 'red';