LearnFast.Ninja

JavaScript change background color of div onmouseover and onmouseout

Write JavaScript function to change the background of div its parameters are element id and string with color code. Write div with id then call your function with the onmouseover and onmouseout events. Copy the working example and test it at your browser.

Step 1: Write JavaScript function to change the background of div its parameters are element id and string 
with color code. 

function changeBackground(id, color) {

    document.getElementById(id).style.background = color;

}


Step 2: Write div with id then call your function with the onmouseover and onmouseout events. 

<div id="Div_1" onmouseover="changeBackground(this.id, '#c0c0c0');"

    onmouseout="changeBackground(this.id, '#ffffdd');">

    I am Div_1

</div>


Working Example: 

<html>

<head>

    <title>Change background of div</title>

    <script type="text/javascript">

        function changeBackground(id, color) {

            document.getElementById(id).style.background = color;

        }

    </script>

</head>

<body>

    <div id="Div_1" onmouseover="changeBackground(this.id, '#c0c0c0');"

        onmouseout="changeBackground(this.id, '#ffffdd');">

        I am Div_1

    </div>

</body>

</html>

Result: 



Tags

javascript

onmouseover onmouseout