Skip to content Skip to sidebar Skip to footer

One Link Opens Two Iframe Targets On Same Page

I currently have a working webpage that has a list of links that open in a targeted iFrame. I would like to add a subsequent iFrame target and be able to open supplementary pages i

Solution 1:

You can have an array/object storing the links, and then run an onclick event that will change the corresponding iframe sources to the values from said array (iframes have a src attribute which you can change through JS).

For example:

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript">
        var frm = ['gallery', 'info'];
        var hrf = ['http://example.com/', 'http://example.net/'];

        function setSource() {
            for(i=0, l=frm.length; i<l; i++) {
                document.querySelector('iframe[name="'+frm[i]+'"]').src = hrf[i];
            }
        }
    </script>
</head>
<body>
    <iframe src="" name="gallery"></iframe>
    <iframe src="" name="info"></iframe>
    <span onclick="javascript: setSource();">Click me</span>
</body>
</html>

If you'd like to have multiple span elements, each changing the iframes' sources to a different set of links, you can always use a multidimensional array (an array of arrays) for src and add a parameter to the function:

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript">
        var frm = ['gallery', 'info'];
        var hrf = [['http://example0.com/', 'http://example0.net/'], ['http://example1.com/', 'http://example1.net/']];

        function setSource(num) {
            for(i=0, l=frm.length; i<l; i++) {
                document.querySelector('iframe[name="'+frm[i]+'"]').src = hrf[num][i];
            }
        }
    </script>
</head>
<body>
    <iframe src="" name="gallery"></iframe>
    <iframe src="" name="info"></iframe>
    <span onclick="javascript: setSource(0);">Click me #0</span>
    <span onclick="javascript: setSource(1);">Click me #1</span>
</body>
</html>

Here hrf is an array that contains another array (['http://example0.com/', 'http://example0.net/']) at index 0 and yet another one (['http://example1.com/', 'http://example1.net/']) - at index 1. By passing a parameter to setSource we can choose what subarray we want to pick to get the sources from.


Please don't forget to close your tags.

Using the a tag for your purpose is not a good idea, I recommend using a span. The a tag's purpose is to link the user to another document, not run javascript code (not using a also means you don't have to use preventDefault).

The javascript: prefix is used for the onclick attribute to provide backwards compatibility for some older mobile browsers.


Post a Comment for "One Link Opens Two Iframe Targets On Same Page"