Skip to content
Advertisement

How to add a button to run code inside LeafletJS marker?

I am trying to add a button inside a pointer which print a log to the console. This is just meant to be a test, so I can actually make the marker run a method, but I can’t even get it to print text.

const marker = L.marker([latitude, longitude]).addTo(map);

const button = '<br/><button type="button">Click button</button>'
const clickbutton = document.querySelector("#click");
button1.addEventListener("click", function(event) {
    console.log('This button works!');
});
marker.bindPopup(button);

When I load the page, I immediately get this error:

Uncaught (in promise) TypeError: Cannot read properties of null (reading ‘addEventListener’)

The console says this error is caused by

button1.addEventListener("click", function(event) {

but I’m not sure why it’s null. Can anyone help me out?

Advertisement

Answer

You are creating the button incorrectly.

It will be right this way:

const button = document.createElement('button');

button.id = 'delete';
button.textContent = 'Delete marker';

In order to add a button to the page, you need to find the desired parent element and add the button as a child element:

// replace this id with what you need
const buttonParrentId = 'button-parrent-id';

const buttonParrent = document.getElementById(buttonParrentId);
buttonParrent.appendChild(button);

Next, you can work with the button as you need:

const marker = L.marker([latitude, longitude]).addTo(map);

button.addEventListener("click", function(event) {
    console.log('This button works!');
});

marker.bindPopup(button);

Result code example:

const button = document.createElement('button');

button.id = 'delete';
button.textContent = 'Delete marker';

// replace this id with what you need
const buttonParrentId = 'button-parrent-id';

const buttonParrent = document.getElementById(buttonParrentId);
buttonParrent.appendChild(button);

const marker = L.marker([latitude, longitude]).addTo(map);

button.addEventListener("click", function(event) {
    console.log('This button works!');
});

marker.bindPopup(button);

More about createElement

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement