Urls array - Next button

Asked

Viewed 619 times

2

PHP

$urls = Array('www.1.com.br','www.2.com.br', 'www.3.com.br');

HTML

<iframe src="www.1.com.br" width='100%' height='100%'></iframe>

<button>Proximo</button>

How do I always click the next button update only the iframe (not the entire page) in the sequence of urls that are in the php array?

I am also in doubt if it is better to have an array with all urls in javascript or php

UPDATE

1 - The 3 answers worked for me, but the 3 have a common one: when you arrive at the last url of the array, when you click again back to the first url, you should stop having action by clicking the Next button when you finish the array urls

2 - in the 3 examples the full page is updating when there is a change in the url of the iframe

jQuery('#srcFrame').submit(function(){             
           $.ajax({
            url: 'updateUrl.php',
            type: '???',
            data: ????,
        });     
    })

How do I use ajax for just iframe update and what should be the updateUrl.php file?

  • The answer you marked as correct does not do what you put in "update", does not return to the first link.

  • but it is not to return to the first link :) as this written: ao clicar novamente volta para a primeira url, deveria PARAR DE TER AÇÃO ao clicar no botão Proximo quando finalizar as urls do array

  • And it doesn’t come back, if it’s coming back it’s because you used Ivan’s code (which checks the index and, if it equals the total of links, goes back to the first). :)

  • No, both Van and Lucas made changes to the responses during the update. If you followed, I confused and Lucas' was correct, even before I put the Update in my question

  • But I learned a lot from Ivan, great explanations, but the final result without updating the page I could understand from Lucas. Again thank you all

3 answers

3

Capture the elements through the ID, and create an action on the button, checking which next index should be clicked, at each click, sum a position, if it is equal to the url total, it restarts to the index 0 (top):

<button id="next">Proximo</button>

<iframe id="rotator" src="http://www.1.com.br" width='100%' height='100%'></iframe>

<script>
window.onload = function() {
/* Para capturar o elemento por
   getElementById, independente da posição do script,
   é necessário que o documento window tenha sido lido */ 
    var urls = [
                'http://www.1.com.br',
                'http://www.2.com.br',
                'http://www.3.com.br'
        ];

    var index = 1;
    var click_button = document.getElementById('next');
    var el = document.getElementById('rotator');

    click_button.onclick = function() {
        if ( index === urls.length ) {
            index = 0;
        } 
        el.src = urls[index];
        index += 1;
    }
};
</script>

If you want to implement using PHP directly in javascript, can do so, but I do not recommend, prefer to send the data via POST or GET, but then would be for another question:

<?php $urls = array('http://www.1.com.br',
                    'http://www.2.com.br',
                    'http://www.3.com.br'); ?>
 <script>
    window.onload = function() {
    /* Para capturar o elemento por
       getElementById, independente da posição do script,
       é necessário que o documento window tenha sido lido */ 
        var urls = <?php echo '["'.implode('","', $urls).'"];'; ?>

        var index = 1;
        var click_button = document.getElementById('next');
        var el = document.getElementById('rotator');

        click_button.onclick = function() {
            if ( index === urls.length ) {
                index = 0;
            } 
            el.src = urls[index];
            index += 1;
        }
    };
</script>

Resolution for new cases:

Case 1:

   <script>
    window.onload = function() {
    /* Para capturar o elemento por
       getElementById, independente da posição do script,
       é necessário que o documento window tenha sido lido */ 
        var urls = [
                    'http://www.1.com.br',
                    'http://www.2.com.br',
                    'http://www.3.com.br'
            ];

        var index = 1;
        var click_button = document.getElementById('next');
        var el = document.getElementById('rotator');

        click_button.onclick = function() {
            if ( index === urls.length -1 ) {
               this.disabled = true;
            } 
            el.src = urls[index];
            index += 1;
        }
    };
    </script>

Case 2:

It wasn’t exactly clear what the problem was. Because it loads every iframe on the same page, if it’s updating, it has nothing to do with the code I published, but with the rest of the code that exists in your application, I believe.

  • It worked Ivan, the comments you put in the code helped me very much updated my question by inserting two observations

  • About the case 2 is that when you click the button next the whole browser has a refresh, the refresh should be only in iframe, updating only the iframe not the entire page

  • window.onload is not a Reload. It just executes the code after the page is loaded... you can do the test using only blank pages, and you will see that it works normally.

  • yes, I understand, but you know that icon that we use to update the page in the browser (Chrome for example)? then, when we click on the button next the icon of the browser runs, in the case of updating only the iframe it should not run, pq will update only the iframe not the entire page

  • well, you’re doing a javascript action, javascript is not server-side, if you click the update button, obviously it will lose everything. to maintain the position, you would have to record the position in the bank via server-side, or use sessionStorage to keep a cache.

  • That’s why I’m trying to figure out how to use Ajax

  • You can only use javascript for this: localStorage.setItem('posicao', index) and catch with: localStorage.getItem('posicao')

  • The main purpose of ajax is to perform actions in an asynchronous manner.

Show 3 more comments

2


With Javascript, you can change the src using the function attr or prop every event click the button, this way:

HTML:

<iframe id="frames" src="'www.google.com" width='100%' height='100%'></iframe>
<button>Proximo</button>

Javascript:

var urls = ['www.google.com','https://platform.twitter.com/widgets/tweet_button.html', 'www.globo.com.br'];
var frame = $("#frames");
var index = 0;

$("button").click(function(event){
    event.preventDefault();
    if (index < urls.length)
        index++;
    $("#frames").attr("src", urls[index]);
});

Jsfiddle: https://jsfiddle.net/lbclucascosta/rmoqa2c7/

Event.preventDefault() is a function that serves to prevent a default behavior of a particular component, so if you user in Submit, the default behavior of refreshing the page will not happen.

  • Thanks for the indications of the pages in the manual, your code worked there are 2 things I still doubt, updated my question

  • to stop having action on the button when it is: &#xA; if ( index === urls.length) {&#xA; click_button.disabled = true;&#xA; }

  • Actually Lucas, yours when it reaches the end of the array does not happen anything else by clicking the button

  • event.preventDefault() would be at the beginning of Function? here did not change the behavior

  • now the button does not work on goes to the next url

  • how do I change when I have an iframe scrame using preventDefault? Something like onchange iframe src preventDefault

  • Your code worked, I was not noticing because it only had the iframe and the button on the page, I put other dynamic contents and I could notice that it works. Chrome gives the impression to be updating the page because of the update icon, I tested in IE and at first I could see that only iframe was updating. Thank you again for your answers :)

Show 2 more comments

1

You can do it like this:

HTML:

<iframe id="displayURL" src="www.1.com.br" width='100%' height='100%'></iframe>

<button id="changeURL">Próximo</button>

Javascript:

var urls = "<?php echo implode('|', $urls) ?>".split('|');

$('#changeURL').click(function() {
    var i = urls.indexOf($('#displayURL').prop('src'));
    i = (i < 0) ? 0 : i+1;
    if(i <= urls.length-1) {
        $('#displayURL').prop('src', urls[i]);
    }
});

It transforms the PHP array into a string separating the elements by pipe, then javascript transforms this string into an array again, with this array I make the swap logic in the code below, according to the value of src of iframe I can find the index in the array and make it go to the next item, unless it is the last or does not exist, in which case I select the first item of the array.

OBS.: I’m separating the URL by pipe, but you can change to any character you don’t have in your links.

  • Thank you Junior, I liked the idea of imploding the php array within javascript. I still have two questions, I updated my question

  • I updated the code to the first question, the second one you’re sure is the whole page you’re updating or just the iframe?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.