0

I am trying to add a border around all items of a class when the mouse is hovering over it. However, no matter which item I hover over, the border is always applied to the last item on the page.

Could anyone explain what is going on and how I may fix it? Thanks.

function setAlertHovers(){
    var alerts = document.getElementsByClassName('alert');
    for(var i=0; i < alerts.length; i++)
    {
        var obj = alerts[i];
        obj.addEventListener('mouseover', function(){addBorder(obj);});
        obj.addEventListener('mouseout', function(){removeBorder(obj);});
    }
}

function addBorder(obj)
{
    obj.style.borderStyle = "solid";
}

function removeBorder(obj)
{
    obj.style.borderStyle = "none";
}

setAlertHovers();
Steven K.
  • 57
  • 1
  • 3
  • 1
    this could be done with css only. why do you use javascript? – jbe May 19 '17 at 21:28
  • For direct children `.parentclass:hover > * {border: 1px solid #000}; ` or for all children `.parentclass:hover * {border: 1px solid #000};` – Todor Simeonov May 19 '17 at 21:30
  • This is just a test for what I actually want to do, which cannot be done in CSS alone. I'm just trying to learn how this works so I can do more complicated things. – Steven K. May 19 '17 at 21:43
  • You may pass this: obj.addEventListener('mouseover', function(){addBorder(this);}); – Jonas Wilms May 20 '17 at 07:58

0 Answers0