Joseph February 2016

Opening Javascript onbutton Press/Link into an iframe

My code below opens a random link and instead of opening the link in a new page I want it to open in an Iframe is this possible.

<button onclick="randomLink()" target="iframe_a";>Click here to go somewhere else!</button>

var randomLink = function () {


    var links = [
        "bing.com",
        "google.com"
    ];



    var max = (links.length)


    var randomNumber = Math.floor(Math.random()*max);


    var link = links[randomNumber];


    window.location = "http://" + link ;
}
</script>

<iframe src="demo_iframe.htm" name="iframe_a"></iframe>

Answers


kevinkl3 February 2016

Simply change the src attribute of the iframe, replacing the window.location = "http://" + link ; line to the following:

document.getElementById('iframe_a').setAttribute('src', "https://" + link);

Or if you want to use jQuery:

$('iframe').attr('src', "https://" + link);

Just like in the @DinoMyte comment.

The javascript code would look like this:

var randomLink = function () {


    var links = [
        "bing.com",
        "google.com"
    ]; 

    var max = (links.length);

    var randomNumber = Math.floor(Math.random()*max);

    var link = links[randomNumber];

    document.getElementById('iframe_a').setAttribute('src', "https://" + link);

};

The complete example is here: https://jsbin.com/cuzehu/1/edit?html,js,output

Post Status

Asked in February 2016
Viewed 1,638 times
Voted 12
Answered 1 times

Search




Leave an answer