0

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?

Matt
  • 2,341
  • 4
  • 20
  • 20
  • Use different IDs? IDs must be unique, don't go against the grain, it will be an uphill battle. – Ruan Mendes Jun 30 '20 at 17:42
  • I understand the id's have to be unique. I don't understand when the id is duplicated on a responsive media query? I thought the code would be hidden resulting in the removal of the id. If I use different id's, how do I select the id in the javascript code on the media query? – Matt Jun 30 '20 at 17:53
  • The element is not removed from the DOM, it is just hidden, I've posted an answer that should address your concerns. – Ruan Mendes Jun 30 '20 at 17:54
  • Thanks, let me try your solution... – Matt Jun 30 '20 at 17:55

1 Answers1

1

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

Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217