Search code examples
javascripthtmlmousehover

How to specify a source and a target on the function using JavaScript?


I need this function to change the border color of a form when the mouse hovers over a button. I got the expected result, but the function affects all page forms. I would like to determine which button affects each form.

How can I specify the source ID and target ID in the function?

View demo

<head>
    <script>
        function chbg(color) {
            document.getElementById('b').style.backgroundColor = color;
            document.getElementById('d').style.backgroundColor = color;
        }
    </script>
</head>

<body>
    <div id="a" onmouseover="chbg('red')" onmouseout="chbg('white')">A - This should effect B only</div>
    <div id="b">B - This is neutral</div>
    <div id="c" onmouseover="chbg('blue')" onmouseout="chbg('white')"> C - This should effect D only</div>
    <div id="d">D - This is neutral</div>
</body>

Update:

Solved! Thank you guys for the help.

View solution


Solution

  • Straightforward, by adding extra parameters to the function:

    function chbg(color, source, target) {
        document.getElementById(source).style.backgroundColor = color;
        document.getElementById(target).style.backgroundColor = color;
    }
    

    Example usage:

    <div id="a" onmouseover="chbg('red', 'a', 'b')" onmouseout="chbg('white', 'a', 'b')">A - This should effect B only</div>
    <div id="b">B - This is neutral</div>
    <div id="c" onmouseover="chbg('blue', 'c', 'd')" onmouseout="chbg('white', 'c', 'd')"> C - This should effect D only</div>
    <div id="d">D - This is neutral</div>