-1

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?

user2375166
  • 45
  • 1
  • 6

1 Answers1

3

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)

putvande
  • 15,068
  • 3
  • 34
  • 50
  • @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 # 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