LearnFast.Ninja

JavaScript onmouseover change css class example with div by id

Write css for over and out background colors. Write JavaScript function that change the class attribute using getElementById and setAttribute. Write html div element and call the function twice using onmouseover and onmouseout. Try the Working Example.

Step 1: Write CSS for over and out background colors. 

<style type="text/css">

    .Over_Bg {

        background-color: Green;

    }

 

    .Out_Bg {

        background-color: Silver;

    }

 

    div {

        width: 200px;

        height: 200px;

    }

</style>


Step 2: Write JavaScript function that change the class attribute using getElementById and setAttribute.

<script type="text/javascript">

    function Change_Class(My_Element, My_Class) {

        document.getElementById(My_Element).setAttribute("class", My_Class);

    }

</script>


Step 3: Write html div element and call the function twice using onmouseover and onmouseout. 

<div class="Out_Bg" id="Div_1" onmouseover="Change_Class('Div_1','Over_Bg')" onmouseout="Change_Class('Div_1','Out_Bg')">

    Over me to change my background

</div>


Working Example: 

<html>

<head>

    <title>Change css</title>

    <style type="text/css">

        .Over_Bg { background-color: Green; }

        .Out_Bg { background-color: Silver; }

        div { width: 200px; height: 200px; }

    </style>

    <script type="text/javascript">

        function changeClass(My_Element, My_Class) {

            document.getElementById(My_Element).setAttribute("class", My_Class);

        }

    </script>

</head>

<body>

    <div class="Out_Bg" id="Div_1" onmouseover="changeClass('Div_1','Over_Bg')"

        onmouseout="Change_Class('Div_1','Out_Bg')">

        Over me to change my background

    </div>

</body>

</html>


Result:


Trick:

<html>

<head>

    <title>Change css</title>

    <style type="text/css">

        .Over_Bg {

            background-color: Green;

        }

 

        .Out_Bg {

            background-color: Silver;

        }

 

        div {

            width: 200px;

            height: 200px;

        }

    </style>

 

    <script type="text/javascript">

        function Change_Class(myElement, My_Class) {

            myElement.setAttribute("class", My_Class);

        }

    </script>

</head>

<body>

    <div class="Out_Bg" id="Div_1" onmouseover="Change_Class(this,'Over_Bg')"

        onmouseout="Change_Class(this,'Out_Bg')">

        Over me to change my background

    </div>

</body>

</html>


Tags

javascript

onmouseover