Henry Henry -4 years ago 78
CSS Question

Change CSS style in JavaScript when button is clicked but change back to original when another button is pressed

I have a web page where you click a button with an image of the cursor and the whole HTML body has that cursor:

<table>
<tr>
<td><button id="alias" onclick="cur('alias')"><img src="alais.png"/>
</button></td>
<td><button id="cell" onclick="cur('cell')"><img src="cell.png"/>
</button></td>
<td><button id="col-resize" onclick="cur('col-resize')"><img src="col-
resize.png"/>
</button></td>
</tr>
...
</table>


All the buttons already have a
1px solid black
border

This is the JavaScript function:

function cur(curval){
document.getElementById(curval).style.borderWidth ="3px"
document.body.style.cursor = curval;
}


This is to show which button is selected, but when you press another button the previous button keeps the 3px border. How could I make it so only one button (the most recently pressed one) has the 3px border?

EDIT

I have tried I want to change the style of all sibling elements but this uses classes with the same name except one, but I am using IDs and they are all named differently, and I can't work out how you would change this to work.

Answer Source

You can keep a reference to previous value and current value and do like this:

var prevElement, currentElement;

function cur(curval) {
  if (!prevElement) {
    prevElement = document.getElementById(curval);
    currentElement = prevElement;
  } else {
    prevElement = currentElement;
    prevElement.style.borderWidth = "1px"
    currentElement = document.getElementById(curval);

  }
  currentElement.style.borderWidth = "3px"
  document.body.style.cursor = curval;
}
<table>
  <tr>
    <td>
      <button id="alias" onclick="cur('alias')">
                    <img src="alais.png" />
                </button>
    </td>
    <td>
      <button id="cell" onclick="cur('cell')">
                    <img src="cell.png" />
                </button>
    </td>
    <td>
      <button id="col-resize" onclick="cur('col-resize')">
                    <img src="col-
        resize.png" />
                </button>
    </td>
  </tr>

</table>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download