Search code examples
htmlcssbootstrap-4media-queries

duplcate id's when hidding content using media query css3


Using bootstrap 4 and vuejs desktop has a container, with a tab pane and map. On Mobile, I remove the tab pane and just show map.

Below code is a simple representation of the problem. The tab pane and map are highly interacting on desktop. On mobile I only want to show the map with minimal interactivity because the tab pane is hidden

           <div class="d-sm-none">
                small
                <div id="mapid" style="width: 100%; height:300px"></div>
            </div>
            <div class="d-none d-md-block">
                large
                <div id="mapid" style="width: 100%; height:300px"></div>
            </div>

The div that is first, will show. For example, in the above code the map will show on mobile, but not desktop. If I rearrange the code desktop will work and mobile will not.

Below is my vue code to display map. I use leaflet.

           this.map = L.map('mapid', {
                center: this.center,
                zoom: this.zoom
            });

How do I get this to work?


Solution

  • The correct solution is not to have duplicate IDs. If this is outside your control, you can pass the div directly, instead of an ID to the Map constructor

    You'd also need to figure out which one is visible.

    function getFirstVisible(els) {
      for (const el of els) {
        if (el.offsetParent) {
          return el;
        }
      }
    }
    
    const divs = document.querySelectorAll("#mapid");
    
    // Then you could do
    // this.map = L.map(getFirstVisible(divs), {center: this.center, zoom: this.zoom});
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet" />
    
    
    <div class="d-sm-none">
      small
      <div id="mapid" style="width: 100%; height:300px"></div>
    </div>
    <div class="d-none d-md-block">
      large
      <div id="mapid" style="width: 100%; height:300px"></div>
    </div>

    See Check if element is visible in DOM