2

How can I get the "select" element to open and show its option elements when I click inside "div" element? In other words, I want to trigger the "select" element when I click to green zone.

HTML

<div>
  <h3>Cities</h3>
  <select>
    <option>Berlin</option>
    <option>Paris</option>
    <option>London</option>
  </select>
</div>

SCSS

body{
  background-color: lightgray;
  margin: 100px;
  
    div{
    display: inline-block;
    padding: 50px;
    background-color: green;

    select{
      width:300px;

      &:focus{
        outline: none;
      }
    }
  }
}

https://codepen.io/mehmetguduk/pen/vYWVGPK

  • you could use javascript to focus it upon clicking the div – Sandil Ranasinghe Mar 01 '22 at 12:07
  • @SandilRanasinghe Yes, but how ? – Mehmet Güdük Mar 01 '22 at 12:08
  • Does this answer your question? [How can you programmatically tell an HTML SELECT to drop down (for example, due to mouseover)?](https://stackoverflow.com/questions/249192/how-can-you-programmatically-tell-an-html-select-to-drop-down-for-example-due) – pilchard Mar 01 '22 at 12:15
  • @pilchard This question is about 4 months ago. I don't know what changed but their solutions are not working right now. They even shared solutions they found with the link. Here : http://jsfiddle.net/fz2sY/39/ as you can see it is not working. – Mehmet Güdük Mar 01 '22 at 12:44
  • 1
    my apologies I misunderstood your question earlier. it seems that it is not possible to do it directly with javascript. You might want to make your own custom element instead of using select. As for the solutions in the link mentioned above, they no longer seem to be supported by browsers. – Sandil Ranasinghe Mar 01 '22 at 12:58

1 Answers1

0

I would not recommend doing such thing but here you go:

$select-width: 400px;
$top-spacing: 100px;
$bottom-spacing: 50px;
$left-spacing: 30px;

body {
    background-color: lightgray;
    margin: 100px;

    div {
        display: inline-block;
        background-color: green;
        position: relative;
        padding: $top-spacing 0 $bottom-spacing;

        h3 {
            left: $left-spacing;
            position: absolute;
            top: 40px;
        }

        select {
            border-top: $top-spacing solid green;
            border-bottom: $top-spacing solid green;
            border-left: $left-spacing solid green;
            border-right: $left-spacing solid green;
            margin: -$top-spacing 0 (-$bottom-spacing);
            cursor: pointer;
            width: $select-width;

            &:focus {
                outline: none;
                border-top: $top-spacing solid green;
                // border has to stay 0 in order to keep options still
                border-width: 0px;
                width: $select-width - (2 * $left-spacing);
                margin: -$top-spacing $left-spacing $bottom-spacing;
            }
        }
    }
}

https://codepen.io/Gotzi/pen/LYejZJq

Gotzi
  • 39
  • 4