So I'm trying to fill popups of a Leaflet JS Map with Content from a csv table. The popup is filled with html. It perfectly fits my needs. The only problem I have is that not every popup has a image available, but every popup depends on the same html code shown below:
popUp = "<h2>" feature.properties.Name "</h2>"
"<img src='" feature.properties.picturelink "'width='300'</img>" "<br>" "<br>"
"<h4>" feature.properties.description "<br>"
If there's no image available, a place holder is shown: placeholder
Is there a way to only show actual images and to hide the placeholder if there is none?
CodePudding user response:
You can add onerror
to the image to hide it if broken.
onerror="this.style.display='none'"
CodePudding user response:
I'd suggest:
// here we're using a template literal which allows us to interpolate
// JavaScript variables (wrapped in the ${...}) directly into the string
// which avoids having to concatenate strings; this also allows new-lines
// within the string itself:
let popUp = `<h2>${feature.properties.Name}</h2>
<img src="${feature.properties.picturelink}"
width="300"
// here we use a conditional/ternary operator,
// if the feature.properties.picturelink property
// is falsey then the style of the <img> is set
// to display: none; otherwise - if the property
// is truthy - it's set to display: auto:
style="${ feature.properties.picturelink ? 'auto' : 'none' }">
<br><br>
<h4>${feature.properties.description}</h4>`;
References: