skip to Main Content

So, trying to get some help om if/how this would be done.
I have a list of canvas elements on a page horizontally. I would like to have the behaviour that if I click on one of them, the OTHERS should get a width of 100px.
I’m in control of the click event on each canvas only, so I’m able to add a "selected" class on the canvas to be in focus. If no canvas have the selected class they should use their "default" value, but when selected is added, it does nothing to the canvas itself but finds all other canvases that doesn’t have the selected class and change their width.

2

Answers


  1. So my solution is to use the CSS pseudo-class :focus.
    And to enable it to do so, you need to set tabindex for the canvas elements first.

    Here my example:

    * {
      box-sizing: border-box;
    }
    
    .canvas-container {
      display: flex;
      flex-direction: row;
    }
    
    .canvas-div {
      border: 1px solid black;
      height: 100px;
      min-width: 100px;
    }
    
    .canvas-div:focus {
      width: 100%;
    }
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>Static Template</title>
        <link rel="stylesheet" href="style.css" />
      </head>
      <body>
        <div class="canvas-container">
          <canvas
            class="canvas-div"
            height="100"
            tabindex="0"
            style="background: pink;"
          >
          </canvas>
          <canvas
            class="canvas-div"
            height="100"
            tabindex="0"
            style="background: yellowgreen;"
          >
          </canvas>
          <canvas
            class="canvas-div"
            height="100"
            tabindex="0"
            style="background: orangered;"
          >
          </canvas>
        </div>
        <script src="script.js"></script>
      </body>
    </html>
    Login or Signup to reply.
  2. If the canvases have a common parent you can do this using the CSS :has (currently supported by major browsers except Firefox where the user has to set a flag to enable it) and CSS :not.

    canvas {
      border: 1px solid black;
    }
    
    .container:has(>.selected) canvas:not(.selected) {
      width: 100px;
    }
    <div class="container">
      <canvas width="200" height="300"></canvas><canvas width="200" height="300" class="selected"></canvas><canvas width="200" height="300"></canvas><canvas width="200" height="300"></canvas>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search