Lewis Day Lewis Day - 5 months ago 19
jQuery Question

Onclick load page in Div and change text

I have this button and what it currently does is onclick it changes the text from

text1
to
text2
Below is the button and the script which achieves this.

Button

<button type="button" id="buttonsend" style="margin-top:-7px;" class="btn btn-default">
<span>text 1</span>
<span style="display:none">text 2</span>
</button>

<div id="load"></div>


Javascript

$('#buttonsend').click(function() {
$('span',this).toggle();
});


What I want it to also do is load a page in the
#load
div only once its clicked and also refresh the page loaded in the div every 10 seconds.

Example

Once the button is clicked the text is changed to
text2
and the
#load
div loads the demo.html page and refreshes this page every 10 seconds. once the button is clicked again the
#load
div stops refreshing the page and the text returns to
text1
. I'm really sorry for making this almost a request but I'm having some difficulties achieving this.

I have coded this script below which refreshes a page loaded in a div every 10 seconds however it loads before the button is clicked so I'm not sure how to get it work once the button is clicked and when the button is clicked again to stop refreshing. Thankyou.

Refresh Script

$(document).ready(function(){
setInterval(function(){
$("#load").load('/demo.html')
}, 10000);
});

Answer

You could use a boolean variable for this, which you toggle when the button is clicked, and in your interval callback you just check whether it is set before reloading:

var reload = false;
$('#buttonsend').click(function() {
    reload = !reload;
    // other actions...
});

$(document).ready(function(){
    setInterval(function(){
        if (reload) $("#load").load('/demo.html')
    }, 1000); // or 10000 if you want 10 sec.
});