Search code examples
javascriptborderonmouseoveronmouseout

Javascript onmouseover border color changing function deleting the border


I've made a function to change a border's color onmouseover but for some reason it deletes the border without changing the color, so I can't change the color back onmouseout. Here it is:

function borderChange(id, color) 
        {
            document.getElementById(id).style.border = color;
        }
<div class="menu" id="menu1" onmouseover="borderChange(this.id, 'White');" onmouseout="borderChange(this.id, 'Black');"> Text </div> 


Solution

  • When you use the border shorthand property, if you don't specify the width and style then they default to 0 and none … at which point it doesn't matter what the colour is.

    Set the border-color property instead.

    function borderChange(id, color) {
      document.getElementById(id).style.borderColor = color;
    }
    div { border: solid red 1px; }
    body { background: blue; }
    <div class="menu" id="menu1" onmouseover="borderChange(this.id, 'White');" onmouseout="borderChange(this.id, 'Black');"> Text </div>


    Aside…

    Passing the id of the element and then immediately getting the element by its ID is pointless. Just pass the element itself.

    function borderChange(element, color) {
      element.style.borderColor = color;
    }
    div { border: solid red 1px; }
    body { background: blue; }
    <div class="menu" id="menu1" onmouseover="borderChange(this, 'White');" onmouseout="borderChange(this, 'Black');"> Text </div>

    Likewise, using JavaScript for this is overcomplicated. You can just use CSS.

    div { border: solid red 1px; }
    div:hover { border-color: white; }
    body { background: blue; }
    <div class="menu" id="menu1"> Text </div>