How can I re-use a script for multiple variables on the same page?

Hi - I’ve created this script:

<script>
function getURL() {
    var url = prompt("Get this URL. Click OK to load this URL in the browser", "https://www.myurl.com");
        if (url != "" && url != null)
      window.open(url);
}
</script>

which is then called by this button:

<span onclick="getURL" type="button">Click here to get URL</span>

I’d like to re-use the script several times (in different buttons) on the same page for different urls - how can I call the script with a different url variable each time from a button?

Thanks for any tips!

Pass the url in as a parameter to the function, so change your function to something like

function getURL(strURL) {
    var url = prompt("Get this URL. Click OK to load this URL in the browser", strURL);
        if (url != "" && url != null)
      window.open(url);
}

and then call it as

<span onclick="getURL('https://www.myurl.com')" type="button">Click here to get URL</span>

The problem with this (and maybe with your original code) is that if you’re doing this to hide your URLs, then they will be available in plain view to anyone who views the source of the web page in their browser. If you’re more concerned about BOTs reading them, there are ways to obscure the plain-text url - pass it in backwards, or encoded, and have your function decode it for example.

Great thanks for answering such a simple question. no worries re security, we just like the standard js alert because it allows users to either load the url or copy and paste it :slight_smile:

Hi,

which is then called by this button:

<span onclick="getURL" type="button">Click here to get URL</span>

This is not a button. It’s a <span> with an invalid type attribute and some Javascript attached. If you want to have a button, use a <button> element. Also I would use Javascript’s element.addEventListener to attach the functionality to the button and use a data-attribute to store unique URLs. Something like this, maybe:

<!-- HTML -->
<button type="button" data-url="http://www.example.com">Click hre to get URL</button>

<!-- Javascript -->
<script>
    // create an array with all Buttons that have the data-url attribute
    var btns = [].slice.call(document.querySelectorAll("[data-url]"));

    // the function we’ll call when a user clicks on the button
    var getURL = function () {
        var url = this.getAttribute("data-url"); // get the unique URL
        var msg = "Get this URL. Click OK to load this URL in the browser.";
        var p = prompt(msg, url);
        if (p !== "" && p !== null) {
            window.open(url);
        }
    };
    
    // Add an eventListener to each Button we’ve found earlier
    btns.forEach(function (btn) {
        btn.addEventListener("click", getURL, false);
    });
</script>
2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.