Skip to content

Undo .removeAtribute function

I’m looking for a solution to restore a removed attribute. I’m not an experienced programmer, so I’m not sure where to start when sharing my code, so I’ll try to give some context below.

I have an image of a map that has several hidden overlays. These overlays are activated by a series of adjacent buttons.

Each of these buttons has a mouseover and mouseout event, which temporarily reveals the overlay. They also have an onclick event that permanently displays the overlay. I’ve used a .removeAtribute function to remove the mouseout event so that my overlay is permanent.

All other layers are still visible with the mouseover and mouseout events (so that you can make comparisons).

When I onclick another overlay button, it clears the previous one, however, now the mouseout event for the previously selected button is still inactive, so hovering over it causes the overlay to appear permanently.

How can I restore the mouseout event after I’ve removed it?

I have tried to use .setAttribute("onmouseout"), but I’ve had no luck in making that work.

Hopefully, this all makes some sense; I’ll post some of my code below, which might help give further context.

function btn01On() {
   document.getElementById("btn01").removeAttribute("onmouseout");
}

function btnClear() {
   document.getElementById("btn01").setAttribute("onmouseout");
}
<button id="btn01" class="map-button map-button1"
onclick="MM_showHideLayers('InfoCurrentExc','','show','OverlayCurrentExc','','show');btn01On();" onmouseover="MM_showHideLayers('OverlayCurrentExc','','show')" onmouseout="MM_showHideLayers('OverlayCurrentExc','','show')">
Current Excavation
</button>

Answer

I was lucky enough to find someone who had a fix for this problem. I’ll share the code below for anyone who might land here with a similar request.

I don’t fully understand how this code works so if someone has a good explanation feel free to share it.

// Remove mouse outs
function btn01On() {
  document.getElementById("btn01").removeAttribute("onmouseout");
}

// keep mouse outs
const buttonIds = ["btn01"];
const mouseOuts = {};
buttonIds.forEach((id) => {
  const el = document.getElementById(id);
  if (el) {
    mouseOuts[id] = el.getAttribute('onmouseout');
  }
});

const restoreMouseOutEvent = () => {
  buttonIds.forEach((id) => {
    const el = document.getElementById(id);
    if (el && mouseOuts[id]) {
      el.setAttribute('onmouseout', mouseOuts[id]);
    }
  });
}