Katie Ziebarth
Katie Ziebarth

Reputation: 43

Style popups differently depending on the clicked layer using Mapbox GL JS

I am currently trying to give my popups different background based on the layer they are found in (i.e. I have a layer called Indigenous Sites where I would like the background of the popup to be different from the other layers).

I have tried giving the popup a className but I am not sure how to call it properly in the CSS.

Below is a sample of the popup script in my html document (script for 2 different layers popups):

// popup for the Other European Sites layer 
map.on('click', 'Other European Sites', function (e) {
new mapboxgl.Popup()
    .setLngLat(e.lngLat)
    .setHTML('<h2>' + 'European Site' + '</h2>' + 
        '<p>' + e.features[0].properties.placeName + '</p>' + 
        '<h2>' + 'Story' + '</h2>' + 
        '<p>' + e.features[0].properties.Story + '</p>' + 
        '<h2>' + 'Latitude' + '</h2>' + 
        '<p>' + e.features[0].properties.latitude + '</p>'  + 
        '<h2>' + 'Longitude' + '</h2>' + 
        '<p>' + e.features[0].properties.longitude + '</p>')
    .addTo(map);
});

// popup for the Other Indigenous Sites layer
map.on('click', 'Other Indigenous Sites', function (e) {
new mapboxgl.Popup({className: 'popupCustom'})
    .setLngLat(e.lngLat)
    .setHTML('<h2>' + 'Indigenous Site' + '</h2>' + 
        '<p>' + e.features[0].properties.placeName + '</p>' + 
        '<h2>' + 'Story' + '</h2>' + 
        '<p>' + e.features[0].properties.Story + '</p>' + 
        '<h2>' + 'Latitude' + '</h2>' + 
        '<p>' + e.features[0].properties.latitude + '</p>'  + 
        '<h2>' + 'Longitude' + '</h2>' + 
        '<p>' + e.features[0].properties.longitude + '</p>')
    .addTo(map);
});

Here is my current CSS that gives all of my popups the same background:

.mapboxgl-popup-content {
overflow-y: scroll;
background-color: #000000;
}

How would I go about assigning the popups different classNames and calling them in the CSS so that I can have different backgrounds for each layer?

Thanks so much for any input!

Upvotes: 4

Views: 1133

Answers (1)

Steve Bennett
Steve Bennett

Reputation: 126527

The className is a CSS class name that will be applied to the popup container (which contains the "mapboxgl-popup-content" element). So if you want your "Other Indigenous Sites" layer to have, say, yellow popups, you could do this:

.mapboxgl-popup-content {
    overflow-y: scroll;
    background-color: #000000;
}

.popupCustom .mapboxgl-popup-content {
    background-color: yellow;
}

Note however that this functionality was only very recently added and I don't think it has been released yet. (It's not in the published docs).

Upvotes: 1

Related Questions