Sign up ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.

i tried to change the css style of a division using javascript. here is Css

<style>
#box
{
height:200px;
width:200px;
background:#c0c0c0;
}
</style>

Here is javascript code

<script>
function fun()
{
setInterval(function(){fun1()},3000);
}

function fun1()
{
var x = document.getElementById("box");
x.style.backgroundColor="red";
} 
</script>

and within HTML body

<div id="box"></div>
<br>
<button type="button" onClick="fun();">Click here </button>

why isn't the color of the div being changed even after clicking the button?

share|improve this question

closed as off-topic by mc10, Josh Crozier, Zword, Sirko, antyrat Jan 17 '14 at 17:31

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "This question was caused by a problem that can no longer be reproduced or a simple typographical error. While similar questions may be on-topic here, this one was resolved in a manner unlikely to help future readers. This can often be avoided by identifying and closely inspecting the shortest program necessary to reproduce the problem before posting." – mc10, Josh Crozier, Zword, Sirko, antyrat
If this question can be reworded to fit the rules in the help center, please edit the question.

2  
Possible duplicate: stackoverflow.com/questions/197748/… – Alex Shilman Jan 16 '14 at 18:41
    
Does write the fun1() instead of function fun1() works? – Beterraba Jan 16 '14 at 18:42
    
Do you declare fun1 before button in document? – skmasq Jan 16 '14 at 18:44
    
Here is a working example.. jsfiddle.net/dnDEN – Josh Crozier Jan 16 '14 at 18:44
    
Did you actually look at the console and see the errors? – epascarello Jan 16 '14 at 18:44

1 Answer 1

up vote 3 down vote accepted

If you look in your console you would have seen you got some errors.

You should define a function as:

function fun(){ 
    // ...
}

instead of just

fun() {
    // .. 
}

So it should be :

function fun() {
    setInterval(fun1,3000);
}

function fun1() {
    var x = document.getElementById("box");
    x.style.backgroundColor="red";
} 

Fiddle (Thanks skmasq)

share|improve this answer
    
This is answer. – skmasq Jan 16 '14 at 18:45
    
jsfiddle.net/dnDEN – skmasq Jan 16 '14 at 18:47
    
@putvande thank you! but still it is not working. i looked it in the console and the error shown is :- Uncaught TypeError: Property 'backgroundColor' of object #<CSSStyleDeclaration> is not a function – user2375166 Jan 16 '14 at 18:51
    
Is your HTML exactly the same as in your question? If you see the Fiddle it put in my answer you see it works just fine. – putvande Jan 16 '14 at 19:04

Not the answer you're looking for? Browse other questions tagged or ask your own question.