I have such code:
$(document).ready(function () {
var el = $('#solving');
setInterval(function(){
if (el.text() == 'gotta!...'){
location.reload();
}
},3000);
});
and i want to do, that after my page is loaded, every 3 seconds i check my html page, on presenting of text 'gotta!...', and if present, i must refresh this page, but for some reasons it didn't work. What i do wrong?
How to check page on presenting of some text (with timer), and reload it?
Check the following example or the jsbin(http://jsbin.com/ibOmaSu/3/edit):
$(document).ready(function () {
var el = $('#solving');
setInterval(function(){
console.log("Checking if el has text");
if (el.text() == 'gotta!...'){
console.log("Reloading");
location.reload();
}
},3000);
// This will simulate whatever adds text to el
setTimeout(function() {
el.text('gotta!...');
},10000);
});
Small note: I can only imagine that the location.reload will not work in www.jsbin.com because it's caught and interrupted, so test locally. I've added a console.log to prove that it hits the correct code line.
Related
i was searching for the solution, but i cannot find any proper suggestions.
My goal is to loop different external urls on the same page (inside the div), rather than looping the pages with header option. Here is my current code for showing one external page in the div:
<script>
$(document).ready(function(){
function loadlink(){
$('#tableHolder').load('read_data_from_page_one?v=1',function () {
$(this).unwrap();
});
}
loadlink(); // This will run on page load
setInterval(function(){
loadlink() // this will run after every 5 seconds
}, 30000);
});
</script>
So after 30 seconds my div "tableholder" is refreshed, which is ok. Now i would like to add another external page after 5 minutes in the same div, and then after 5 minutes again another external page. They need to be refreshed every 30 seconds as my first external page. After that it needs to load again the first external page.
so basicly loop inside external content in a div. Is that possible?
The other solution is to loop the pages via header options:
<?php header("Refresh: 300; URL=read_data_from_page_two.php"); ?>
But i don't want that. Any suggestions?
Best regards, Misko
If pages are numbered, simple counter will be fine:
$(document).ready(function(){
var counter = 1, // current page
max = 3; // last page
function loadlink(){
$('#tableHolder').load('read_data_from_page_one?v='+counter,function () {
$(this).unwrap();
});
}
loadlink(); // This will run on page load
setInterval(loadlink, 30000); // this will run after every 30 seconds
setInterval(function(){
if(++counter > max){ // next page
counter = 1; // back to start
}
}, 5000000); // 5 min interval
});
$(document).ready(function(){
function loadlink(x = 1){
$('#tableHolder').load('read_data_from_page_one?v='+x,function () {
$(this).unwrap();
});
}
loadlink(); // This will run on page load
var x=1;
setInterval(function(){
x++
loadlink(x); // this will run after every 5 seconds
}, 30000);
});
Is this more or less what you are meaning? An array of links that can be cycled through every n seconds and repeated when all have been displayed?
<script>
$(document).ready(function(){
var links=[
'read_data_from_page_one?v=1',
'read_data_from_page_two.php',
'read_data_from_page_three.php',
/*
..... etc
*/
'read_data_from_page_ninetynine.php'
];
var i=0;
function loadlink(i){
var url=links[i];
$('#tableHolder').load( url, function() {
$(this).unwrap();
});
}
loadlink(i);
setInterval(function(){
loadlink(i);
i++;
if( i>=links.length ) i=0;
}, 30000 );
});
</script>
I have a slider with 10 slider elements. However, only 7 out of 10 elements are rendered, given my data structure contains 20 sets. The site is hosted here
The code in question
function populateCarousell(cdata) {
var x = 0; //debug
jQuery(".wslide-slides .wslide-slide").each(function() {
var single = cdata.shift();
var jcurrSlide = jQuery(this);
jcurrSlide.find(".wslide-caption-text").text(single.title);
jcurrSlide.find("a").attr('href', "https://carousell.com/p/" +single.id);
jcurrSlide.css({'background-image':Base64.decode('dXJs')+'('+single.primary_photo_full_url+')'});
jcurrSlide.css({'background-image':'contain'});
jcurrSlide.css({'background-position':'50% 50%'});
jcurrSlide.css({'background-repeat': 'no-repeat'});
x++; //debug
jcurrSlide.find(".wslide-slide-inner2").removeAttr('style').find("img").css({'display':'none'});
});
alert(x); //Outputs 7
}
which is activated by (to ensure page fully loaded)
function caroDataCallback(data) {
if(document.readyState != "complete" ) {
setTimeout(function() { caroDataCallback(data); }, 2000);
}
else{
populateCarousell(data);
}
}
Upon examination in Chrome, the results is
That's because your page is not fully loaded when you call populateCarousell(cdata) function in your javascript file. Try instead of using $(document).ready(), use the $(document).load() to make sure all the images are loaded before you initiate your carousel.
Update: Use $(window).on('load', function() { .. }); instead.
Hope this helps.
Does anyone know how to refresh the page only one time after 5 sec in JavaScript?
I have the following script to refresh the page after 5 sec:
setTimeout(function () {
window.location.reload(1);
}, 5000); // After 5 secs
But somehow this is refresh every 5 sec instead of just once time after the 1st 5 sec. Does anyone know how to fix this issue?
I think better solution is check document.referer and compare with document.location
if (document.referrer !== document.location.href) {
setTimeout(function() {
document.location.reload()
}, 5000);
}
You can try this in jsfiddle: https://jsfiddle.net/ga0Lrurj/
This is by far the simplest and lightest solution:
setTimeout(function () {
if(window.location.hash != '#r') {
window.location.hash = 'r';
window.location.reload(1);
}
}, 5000); // After 5 secs
You need a way to identify a reloaded page. The easiest way (imo) would be to controll this server side. Check a get-variable and include the js-code if it does not exist.
Also, I see people suggesting cookies. I don't like using cookies for minor stuff like this.
You could try something like:
// Get all get-variables
var queryDict = {}
location.search.substr(1).split("&").forEach(function(item) {queryDict[item.split("=")[0]] = item.split("=")[1]})
// Check if reloaded is set
if (queryDict['reloaded'] == 'undefined') {
// Check if url contains any get-variables
if (Object.keys(queryDict).length == 0) {
var redirect = document.URL + '?reloaded';
}
else {
var redirect = document.URL + '&reloaded';
}
// The timeout
setTimeout(function () {
window.location = redirect;
}, 5000);
}
You need to kept this script after doing something like insertions or updations or any other task then it will reload your page after 5 seconds for once. It works for me while uploading pictures i kept this scripts after uploading my file rather than kept it in window.load or documents.ready function its work for like a charm. here is my script. May this helps you solve your problem
<script type="text/javascript">
$(window).load(function () {
$('#<%=FileUpload1.ClientID%>').uploadify({
'swf': 'fy/uploadify.swf',
'cancelImg': 'fy/uploadify-cancel.png',
'buttonText': 'Browse Files',
'uploader': 'Gallery.ashx',
'folder': 'uploads',
'fileDesc': 'Image Files',
'fileExt': '*.jpg;*.jpeg;*.gif;*.png',
'multi':true,
'auto': false,
'formData':{'paid':<%= Request.QueryString["PhotoAlbumID"] %>},
'onUploadStart': function (file) {
$("#<%=FileUpload1.ClientID%>").uploadify("settings", 'Txt', $('#password').val());
$( document ).ready(function() {
}); setTimeout(function() { window.location=window.location;},3000);
}
});
});
</script>
I want that when a user clicks on any external link (identified by either particular id or class) on my site then he should get a popup with a counter of 10 seconds, after 10 seconds the popup should close and the user should be able to access the external URL. How can this be done? I'm able to show a warning like below but I don't know how to add timeout to it, also this is a confirm box, not a popup where I can add some div and more stuff for user to see until the counter stops.
$(document).ready(function(){
var root = new RegExp(location.host);
$('a').each(function(){
if(root.test($(this).attr('href'))){
$(this).addClass('local');
}
else{
// a link that does not contain the current host
var url = $(this).attr('href');
if(url.length > 1)
{
$(this).addClass('external');
}
}
});
$('a.external').live('click', function(e){
e.preventDefault();
var answer = confirm("You are about to leave the website and view the content of an external website. We cannot be held responsible for the content of external websites.");
if (answer){
window.location = $(this).attr('href');
}
});
});
PS: Is there any free plugin for this?
I've put together a little demo to help you out. First thing to be aware of is your going to need to make use of the setTimeout function in JavaScript. Secondly, the confirmation boxes and alert windows will not give you the flexibility you need. So here's my HTML first I show a simple link and then created a popup div that will be hidden from the users view.
<a href='http://www.google.com'>Google</a>
<div id='popUp' style='display:none; border:1px solid black;'>
<span>You will be redirected in</span>
<span class='counter'>10</span>
<span>Seconds</span>
<button class='cancel'>Cancel</button>
</div>
Next I created an object that controls how the popup is displayed, and related events are handled within your popup. This mostly is done to keep my popup code in one place and all events centrally located within the object.
$('a').live('click', function(e){
e.preventDefault();
popUp.start(this);
});
$('.cancel').click(function()
{
popUp.cancel();
});
var popUp = (function()
{
var count = 10; //number of seconds to pause
var cancelled = false;
var start = function(caller)
{
$('#popUp').show();
timer(caller);
};
var timer = function(caller)
{
if(cancelled != true)
{
if(count == 0)
{
finished(caller);
}
else
{
count--;
$('.counter').html(count);
setTimeout(function()
{
timer(caller);
}, 1000);
}
}
};
var cancel = function()
{
cancelled = true;
$('#popUp').hide();
}
var finished = function(caller)
{
alert('Open window to ' + caller.href);
};
return {
start : start,
cancel: cancel
};
}());
If you run, you will see the popup is displayed and the countdown is properly counting down. There's still some tweaks of course that it needs, but you should be able to see the overall idea of whats being accomplished. Hope it helps!
JS Fiddle Sample: http://jsfiddle.net/u39cV/
You cannot using a confirm native dialog box as this kind of dialog, as alert(), is blocking all script execution. You have to use a cutomized dialog box non-blocking.
You can use for example: jquery UI dialog
Even this has modal option, this is not UI blocking.
Consdier using the javascript setTimeout function to execute an action after a given delay
if (answer){
setTimeOut(function(){
//action executed after the delay
window.location = $(this).attr('href');
}, 10000); //delay in ms
}
I would like to implement a JavaScript code which states this:
if the page is loaded completely, refresh the page immediately, but only once.
I'm stuck at the "only once":
window.onload = function () {window.location.reload()}
this gives a loop without the "only once". jQuery is loaded if this helps.
I'd say use hash, like this:
window.onload = function() {
if(!window.location.hash) {
window.location = window.location + '#loaded';
window.location.reload();
}
}
When I meet this problem, I search to here but most of answers are trying to modify existing url. Here is another answer which works for me using localStorage.
<script type='text/javascript'>
(function()
{
if( window.localStorage )
{
if( !localStorage.getItem('firstLoad') )
{
localStorage['firstLoad'] = true;
window.location.reload();
}
else
localStorage.removeItem('firstLoad');
}
})();
</script>
<script type="text/javascript">
$(document).ready(function(){
//Check if the current URL contains '#'
if(document.URL.indexOf("#")==-1){
// Set the URL to whatever it was plus "#".
url = document.URL+"#";
location = "#";
//Reload the page
location.reload(true);
}
});
</script>
Due to the if condition the page will reload only once.I faced this problem too and when I search ,I found this nice solution.
This works for me fine.
Check this Link it contains a java-script code that you can use to refresh your page only once
http://www.hotscripts.com/forums/javascript/4460-how-do-i-have-page-automatically-refesh-only-once.html
There are more than one way to refresh your page:
solution1:
To refresh a page once each time it opens use:
<head>
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Expires" CONTENT="-1">
</head>
sollution2:
<script language=" JavaScript" >
<!--
function LoadOnce()
{
window.location.reload();
}
//-->
</script>
Then change your to say
<Body onLoad=" LoadOnce()" >
solution3:
response.setIntHeader("Refresh", 1);
But this solution will refresh the page more than one time depend on the time you specifying
I hope that will help you
<script>
function reloadIt() {
if (window.location.href.substr(-2) !== "?r") {
window.location = window.location.href + "?r";
}
}
setTimeout('reloadIt()', 1000)();
</script>
this works perfectly
Finally, I got a solution for reloading page once after two months research.
It works fine on my clientside JS project.
I wrote a function that below reloading page only once.
1) First getting browser domloading time
2) Get current timestamp
3) Browser domloading time + 10 seconds
4) If Browser domloading time + 10 seconds bigger than current now timestamp then page is able to be refreshed via "reloadPage();"
But if it's not bigger than 10 seconds that means page is just reloaded thus It will not be reloaded repeatedly.
5) Therefore if you call "reloadPage();" function in somewhere in your js file page will only be reloaded once.
Hope that helps somebody
// Reload Page Function //
function reloadPage() {
var currentDocumentTimestamp = new Date(performance.timing.domLoading).getTime();
// Current Time //
var now = Date.now();
// Total Process Lenght as Minutes //
var tenSec = 10 * 1000;
// End Time of Process //
var plusTenSec = currentDocumentTimestamp + tenSec;
if (now > plusTenSec) {
location.reload();
}
}
// You can call it in somewhere //
reloadPage();
i put this inside my head tags of the page i want a single reload on:
<?php if(!isset($_GET['mc'])) {
echo '<meta http-equiv="refresh" content= "0;URL=?mc=mobile" />';
} ?>
the value "mc" can be set to whatever you want, but both must match in the 2 lines. and the "=mobile" can be "=anythingyouwant" it just needs a value to stop the refresh.
Use window.localStorage... like this:
var refresh = window.localStorage.getItem('refresh');
console.log(refresh);
if (refresh===null){
window.location.reload();
window.localStorage.setItem('refresh', "1");
}
It works for me.
After </body> tag:
<script type="text/javascript">
if (location.href.indexOf('reload')==-1)
{
location.href=location.href+'?reload';
}
</script>
You can make one verable once = false then reload your page with if else like if once == false reload page an make once true.
You'd need to use either GET or POST information. GET would be simplest. Your JS would check the URL, if a certain param wasn't found, it wouldn't just refresh the page, but rather send the user to a "different" url, which would be the same URL but with the GET parameter in it.
For example:
http://example.com -->will refresh
http://example.com?refresh=no -->won't refresh
If you don't want the messy URL, then I'd include some PHP right at the beginning of the body that echos a hidden value that essentitally says whether the necessary POST param for not refreshing the page was included in the initial page request. Right after that, you'd include some JS to check that value and refresh the page WITH that POST information if necessary.
Try with this
var element = document.getElementById('position');
element.scrollIntoView(true);`
Please try with the code below
var windowWidth = $(window).width();
$(window).resize(function() {
if(windowWidth != $(window).width()){
location.reload();
return;
}
});
Here is another solution with setTimeout, not perfect, but it works:
It requires a parameter in the current url, so just image the current url looks like this:
www.google.com?time=1
The following code make the page reload just once:
// Reload Page Function //
// get the time parameter //
let parameter = new URLSearchParams(window.location.search);
let time = parameter.get("time");
console.log(time)//1
let timeId;
if (time == 1) {
// reload the page after 0 ms //
timeId = setTimeout(() => {
window.location.reload();//
}, 0);
// change the time parameter to 0 //
let currentUrl = new URL(window.location.href);
let param = new URLSearchParams(currentUrl.search);
param.set("time", 0);
// replace the time parameter in url to 0; now it is 0 not 1 //
window.history.replaceState({}, "", `${currentUrl.pathname}?${param}`);
// cancel the setTimeout function after 0 ms //
let currentTime = Date.now();
if (Date.now() - currentTime > 0) {
clearTimeout(timeId);
}
}
The accepted answer uses the least amount of code and is easy to understand. I just provided another solution to this.
Hope this helps others.
React Hook worked for me.
import { useEffect, useState } from 'react';
const [load, setLoad] = useState(false);
window.onload = function pageLoad() {
if (load) {
window.location.reload(true);
setLoad(false);
}
};
nothing work for me perfectly except this, -added to my JavaScript file-:
function LoadOnce() {
if (localStorage.getItem('executed') == 'false') {
window.location.reload()
localStorage.setItem('executed', true)
}
}
setTimeout(function () {
LoadOnce()
}, 100)
and in the previous page I wrote:
localStorage.setItem('executed', false)
I got the Answer from here and modified it.This is the perfect solution for me.
var refresh = window.localStorage.getItem('refresh');
console.log(refresh);
setTimeout(function() {
if (refresh===null){
window.location.reload();
window.localStorage.setItem('refresh', "1");
}
}, 1500); // 1500 milliseconds = 1.5 seconds
setTimeout(function() {
localStorage.removeItem('refresh')
}, 1700); // 1700 milliseconds = 1.7 seconds
var foo = true;
if (foo){
window.location.reload(true);
foo = false;
}
use this
<body onload = "if (location.search.length < 1){window.location.reload()}">
Use rel="external"
like below is the example
<li>Home</li>