I'm using leaflet.js to make a map and I need help with the javascript required to make a map-marker generate a random phrase with each click.

I've used this code to generate random text:

function randomText() {
var items = new Array(
            "Stop poking me",
            "Leave me alone",
            "Don't you have anything better to do?",
            "You're hurting me",
            "Go away"

var i = Math.floor(Math.random() * items.length);

return items[i];}

But when I try to put it in popup content it's blank.

I tried


My current gist has .bindPopup(randomText()); because it is, at least, not blank and generates a random phrase with each page load.

Here is my gist https://gist.github.com/joshuahouston/800cd59aab26c264f3bc

And the working map with where I'm currently stuck http://bl.ocks.org/joshuahouston/800cd59aab26c264f3bc


this works for me:

function bindNewPopup(){
var marker = L.marker([47.16, -115.32])
        .on('click', bindNewPopup)

The code in your gist only gets a randomText() when the marker is created. To change the text on every click, you need some way to call the function again; therefore create the function bindNewPopup.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.