0

Please be gentle with me, it is my first time uploading a question to stack overflow, and since I am rather new in programming I might be a bit vague in the terms.

My problem is that I have a function that places some markers on a map, this happens automatically when I load the site, these markers are different and contain different "trophies", that I have placed in a pop-up locked to the marker. However I want the program to be able to collect the trophies, therefore I would like to call a function with the specific trophy as my parameter in my javaScript file when I click a button in my pop up. HTML.

So far it looks like this:

function createMarker(coords, trophy) {
  var id
  // check if array is empty and set id to 0 if it is
  if (markers.length < 1) id = 0
  // else make id based on array length
  else id = markers[markers.length - 1]._id + 1
  // custom popup content with HTML that can be styled
  var popupContent =
    '<div id= "divTrophy">'+
    '<img src=' + trophy +'></img>' +
    '<button onClick="trophyCollection('+trophy+')">Collect trophy</button>'+
    '<button onclick="closePopUp()">Close pop up</button>'+
    '</div>'
'<button onClick="trophyCollection('+trophy+')">Collect trophy</button>'+

The problem is in this line where I am for some reason not allowed to concat this way, which confuses me because it works fine in the line above in the <img>.

I really hope someone can help me, create my little treasure hunt around DK.

xxx
  • 1,153
  • 1
  • 11
  • 23

4 Answers4

1

Try using string interpolation. Something like this.

`your_html_string ${your_dynamic_value} your_html_string`

You can find more info on interpolation here. How to interpolate variables in strings in JavaScript, without concatenation?

Gaurav Mall
  • 500
  • 4
  • 16
  • If you're just going to link to other questions, you should flag it as a duplicate, not post an answer. – Barmar Mar 26 '21 at 20:27
0

Try escaping them it should work, example

'<button onClick="trophyCollection(\''+trophy+'\')">Collect trophy</button>'+
0

You can insert your entire HTML inside of a backtick string and interpolate values like this:

let popupContent =
  `<div id= "divTrophy">
    <img src=${trophy}></img>
    <button onClick="trophyCollection(${trophy})">Collect trophy</button>
    <button onclick="closePopUp()">Close pop up</button>
  </div>`
-1

As suggested you can try template literals:

var popupContent = `<div id="divTrophy">
   <img src="${trophy}"/>
   <button onClick="trophyCollection('${trophy}')">Collect trophy</button>
   <button onclick="closePopUp()">Close pop up</button>
</div>`

Do note that as trophy is a string you still need to wrap it in quotes.

SuperDJ
  • 7,488
  • 11
  • 40
  • 74