Javascript: How to get a list of all open windows - javascript

Suppose you open a handful of windows with:
window.open(url1,'win1');
window.open(url2,'win2');
window.open(url3,'win3');
(each window has a unique name)
And then you refresh the page.
The 3 popup windows are still open. Is there a way to list the names of all of the open windows and close them?
This is not a duplicate question.
In this question the browser is being refreshed, so you cannot simply use a global array to keep track of child windows.
This is not a duplicate question.

So the questions is closed, I'll post an answer based on the comments and research.
Firstly, to all who commented, thank you for helping.
Answer:
There is not a built-in object which tracks opened windows and persists from page load to page load.
As Felix Kling pointed out, using localStorage is a possible work-around.

Try postMessage to communicate between existing windows within the same domain. That's how i'm going to try and solve the same problem. See: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
index.htm
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>pop</title>
</head>
<body>
<script>
var pops = [];
window.onmessage = function(e)
{
// todo: check domain
// if( e.origin )
var data;
try
{
data = JSON.parse(e.data);
}
catch(e)
{
// fail silent...?
return;
}
switch(data.event)
{
case "RestoreOpenWindow":
onClosePopup(e.source.name);
case "QueryOpenWindows":
pops.push(e.source);
updateLabel();
break;
}
};
window.onload = function()
{
window.onClosePopup = onClosePopup;
updateLabel();
};
window.onbeforeunload = function()
{
for(var i = 0; i < pops.length; i++) pops[i].queryOpenPopups();
};
function onClosePopup(name)
{
for(var i = pops.length - 1; i >= 0; i--)
if(pops[i].name === name)
{ pops.splice(i, 1); break; }
updateLabel();
};
function openPopup()
{
pops.push(window.open("pop/popup.htm", "pop" + pops.length, ' '));
updateLabel();
setTimeout(function(){
alert('Click ok to refresh...');
location.href = location.href;
}, 5000);
}
function updateLabel()
{
document.getElementById("total").innerHTML = pops.length;
var html = [];
for(var i = 0; i < pops.length; i++)
html.push(pops[i].name);
document.getElementById("names").innerHTML = html.join("<br"+"/"+">");
}
</script>
<button onclick="openPopup()">open popup and refresh after 5 seconds (...allow em popups...)</button></br>
<span>total: </span><span id="total"></span></br>
<span id="names"></span></br>
</body>
</html>
popup.htm
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>pop</title>
</head>
<body>
<script>
window.queryOpenPopups = function()
{
var count = 0;
var hInterval = setInterval(function () {
try
{
if(window.opener)
{
window.opener.postMessage(JSON.stringify({"event": "QueryOpenWindows", "name": window.name}), "*");
clearInterval(hInterval);
} else count++;
}
catch(e)
{
count++;
}
if(count > 50)window.close();
}, 100);
};
window.onbeforeunload = function(){
window.opener.onClosePopup(window.name);
};
// restore link with opener on refresh
window.opener.postMessage(JSON.stringify({"event": "RestoreOpenWindow", "name": window.name}), "*");
window.onload=function(){ document.getElementById("name").innerHTML = window.name; };
</script>
<span id="name"></span>
</body>
</html>

Related

How to save a list of "divs" to sessionStorage and display them when the user reloads the page?

I have an HTML page as follows:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css" type="text/css">
<title>Test</title>
</head>
<body>
<div>
<p>Hello World!</p>
</div>
</body>
</html>
Then I have a JS file that listens for clicks of the enter key, and if the user clicks enter if adds another div.
//the event handler function
function captureEnterPress(event) {
if (event.key === "Enter" || event.keyCode === 13) {
event.preventDefault();
createNewDiv();
}
}
//creates the div
function createNewDiv() {
var body = document.body;
var div = document.createElement("div");
var p = document.createElement("p");
var labelText = document.createTextNode("Hello World!");
p.appendChild(labelText);
div.appendChile(p);
body.appendChild(div);
}
onload = () => {
document.documentElement.addEventListener("keyup", captureEnterPress);
}
I am trying to have the number of divs saved, so when the user reloads the page it shows the same amount of divs like he had before.
What I tried
I tried saving an array of all the divs to sessionStorage as follows:
var myStorage = window.sessionStorage;
var elementsArray = [];
//the event handler function
function captureEnterPress(event) {
if (event.key === "Enter" || event.keyCode === 13) {
event.preventDefault();
createNewDiv();
}
}
//creates the div
function createNewDiv() {
var body = document.body;
var div = document.createElement("div");
var p = document.createElement("p");
var labelText = document.createTextNode("Hello World!");
p.appendChild(labelText);
div.appendChile(p);
body.appendChild(div);
elementsArray[elementsArray.length] = div;
myStorage.setItem("storedPage", JSON.stringify(elementsArray));
}
onload = () => {
var storedPage = JSON.parse(myStorage.getItem("storedPage"));
if(storedPage){
event.preventDefault();
for(var i = 0; i < storedPage.length; i++){
document.body.appendChild(storedPage[i]);
console.log(storedPage)
}
}
document.documentElement.addEventListener("keyup", captureEnterPress);
}
I just logged it to the console to see what the values are, but they are empty. So I tried storing the div.innerHTML instead, but then if I try to append it to the document I get and error that it's a String and not a node.
I am out of ideas, and I am pretty new to the whole state storing concept in front-end development I would appreciate if somebody could tell me what is the right way to do it.
Thanks!
Not tested, but enough to illustrate
function createNewDiv() {
// create html content
const div = `<div><p>Hello World!</p></div>`;
// concat with body
document.body.innerHTML += div;
// save in array
elementsArray[elementsArray.length] = div;
// save in storage
myStorage.setItem("storedPage", JSON.stringify(elementsArray));
}
onload = () => {
var storedPage = JSON.parse(myStorage.getItem("storedPage"));
if(storedPage){
event.preventDefault();
// get stored content array and join by empty '' and add into body
document.body.innerHTML = storedPage.join('');
}
document.documentElement.addEventListener("keyup", captureEnterPress);
}
The problem I see in this code is that JSON.stringify is not able to convert DOM elements. Article on how to do this.
However, the better way is to save the innerHTML of some container, and then restore it.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css" type="text/css">
<title>Test</title>
</head>
<body>
<div id="div-container">
<div>
<p>Hello World!</p>
</div>
</div>
</body>
</html>
JS:
var myStorage = window.sessionStorage;
var elementsArray = [];
//the event handler function
function captureEnterPress(event) {
if (event.key === "Enter" || event.keyCode === 13) {
event.preventDefault();
createNewDiv();
}
}
//creates the div
function createNewDiv() {
var divContainer = document.getElementById("div-container");
const div = "<div><p>Hello World!</p></div>";
divContainer.innerHTML += div;
console.log(divContainer.innerHTML);
myStorage.setItem("storedPage", divContainer.innerHTML);
}
onload = () => {
var storedPage = myStorage.getItem("storedPage");
if(storedPage){
event.preventDefault();
var divContainer = document.getElementById("div-container");
divContainer.innerHTML = storedPage;
}
document.documentElement.addEventListener("keyup", captureEnterPress);
}
JSFiddle: https://jsfiddle.net/wLgh1ef8/1/
Edit:
You always can see the content of sessionStorage using DevTools
F12 -> Application tab -> Session Storage

Detect URL if it is already opened and throw pop-up : HTML+JS [duplicate]

I want to check with JavaScript if the user has already opened my website in another tab in their browser.
It seems I cannot do that with pagevisibility...
The only way I see is to use WebSocket based on a session cookie, and check if the client has more than one socket. But by this way, from current tab, I have to ask my server if this user has a tab opened right next to their current browser tab. It is a little far-fetched!
Maybe with localstorage?
The shorter version with localStorage and Storage listener
<script type="text/javascript">
// Broadcast that you're opening a page.
localStorage.openpages = Date.now();
var onLocalStorageEvent = function(e){
if(e.key == "openpages"){
// Listen if anybody else is opening the same page!
localStorage.page_available = Date.now();
}
if(e.key == "page_available"){
alert("One more page already open");
}
};
window.addEventListener('storage', onLocalStorageEvent, false);
</script>
Update:
Works on page crash as well.
Stimulate page crash in chrome: chrome://inducebrowsercrashforrealz
Live demo
Using local storage I created a simple demo that should accomplish what your looking to do. Basically, it simply maintains a count of currently opened windows. When the window is closed the unload events fire and remove it from the total window count.
When you first look at it, you may think there's more going on than there really is. Most of it was a shotty attempt to add logic into who was the "main" window, and who should take over as the "main" window as you closed children. (Hence the setTimeout calls to recheck if it should be promoted to a main window) After some head scratching, I decided it would take too much time to implement and was outside the scope of this question. However, if you have two windows open (Main, and Child) and you close the Main, the child will be promoted to a main.
For the most part you should be able to get the general idea of whats going on and use it for your own implementation.
See it all in action here:
http://jsbin.com/mipanuro/1/edit
Oh yeah, to actually see it in action... Open the link in multiple windows. :)
Update:
I've made the necessary changes to have the the local storage maintain the "main" window. As you close tabs child windows can then become promoted to a main window. There are two ways to control the "main" window state through a parameter passed to the constructor of WindowStateManager. This implementation is much nicer than my previous attempt.
JavaScript:
// noprotect
var statusWindow = document.getElementById('status');
(function (win)
{
//Private variables
var _LOCALSTORAGE_KEY = 'WINDOW_VALIDATION';
var RECHECK_WINDOW_DELAY_MS = 100;
var _initialized = false;
var _isMainWindow = false;
var _unloaded = false;
var _windowArray;
var _windowId;
var _isNewWindowPromotedToMain = false;
var _onWindowUpdated;
function WindowStateManager(isNewWindowPromotedToMain, onWindowUpdated)
{
//this.resetWindows();
_onWindowUpdated = onWindowUpdated;
_isNewWindowPromotedToMain = isNewWindowPromotedToMain;
_windowId = Date.now().toString();
bindUnload();
determineWindowState.call(this);
_initialized = true;
_onWindowUpdated.call(this);
}
//Determine the state of the window
//If its a main or child window
function determineWindowState()
{
var self = this;
var _previousState = _isMainWindow;
_windowArray = localStorage.getItem(_LOCALSTORAGE_KEY);
if (_windowArray === null || _windowArray === "NaN")
{
_windowArray = [];
}
else
{
_windowArray = JSON.parse(_windowArray);
}
if (_initialized)
{
//Determine if this window should be promoted
if (_windowArray.length <= 1 ||
(_isNewWindowPromotedToMain ? _windowArray[_windowArray.length - 1] : _windowArray[0]) === _windowId)
{
_isMainWindow = true;
}
else
{
_isMainWindow = false;
}
}
else
{
if (_windowArray.length === 0)
{
_isMainWindow = true;
_windowArray[0] = _windowId;
localStorage.setItem(_LOCALSTORAGE_KEY, JSON.stringify(_windowArray));
}
else
{
_isMainWindow = false;
_windowArray.push(_windowId);
localStorage.setItem(_LOCALSTORAGE_KEY, JSON.stringify(_windowArray));
}
}
//If the window state has been updated invoke callback
if (_previousState !== _isMainWindow)
{
_onWindowUpdated.call(this);
}
//Perform a recheck of the window on a delay
setTimeout(function()
{
determineWindowState.call(self);
}, RECHECK_WINDOW_DELAY_MS);
}
//Remove the window from the global count
function removeWindow()
{
var __windowArray = JSON.parse(localStorage.getItem(_LOCALSTORAGE_KEY));
for (var i = 0, length = __windowArray.length; i < length; i++)
{
if (__windowArray[i] === _windowId)
{
__windowArray.splice(i, 1);
break;
}
}
//Update the local storage with the new array
localStorage.setItem(_LOCALSTORAGE_KEY, JSON.stringify(__windowArray));
}
//Bind unloading events
function bindUnload()
{
win.addEventListener('beforeunload', function ()
{
if (!_unloaded)
{
removeWindow();
}
});
win.addEventListener('unload', function ()
{
if (!_unloaded)
{
removeWindow();
}
});
}
WindowStateManager.prototype.isMainWindow = function ()
{
return _isMainWindow;
};
WindowStateManager.prototype.resetWindows = function ()
{
localStorage.removeItem(_LOCALSTORAGE_KEY);
};
win.WindowStateManager = WindowStateManager;
})(window);
var WindowStateManager = new WindowStateManager(false, windowUpdated);
function windowUpdated()
{
//"this" is a reference to the WindowStateManager
statusWindow.className = (this.isMainWindow() ? 'main' : 'child');
}
//Resets the count in case something goes wrong in code
//WindowStateManager.resetWindows()
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div id='status'>
<span class='mainWindow'>Main Window</span>
<span class='childWindow'>Child Window</span>
</div>
</body>
</html>
CSS:
#status
{
display:table;
width:100%;
height:500px;
border:1px solid black;
}
span
{
vertical-align:middle;
text-align:center;
margin:0 auto;
font-size:50px;
font-family:arial;
color:#ba3fa3;
display:none;
}
#status.main .mainWindow,
#status.child .childWindow
{
display:table-cell;
}
.mainWindow
{
background-color:#22d86e;
}
.childWindow
{
background-color:#70aeff;
}
(2021) You can use BroadcastChannel to communicate between tabs of the same origin.
For example, put the following at the top level of your js code, then test by opening 2 tabs:
const bc = new BroadcastChannel("my-awesome-site");
bc.onmessage = (event) => {
if (event.data === `Am I the first?`) {
bc.postMessage(`No you're not.`);
alert(`Another tab of this site just got opened`);
}
if (event.data === `No you're not.`) {
alert(`An instance of this site is already running`);
}
};
bc.postMessage(`Am I the first?`);
I know it is late, but maybe help someone
This snippet of code, will detect how many tabs are open and how many are active (visible) and if none of tabs is active, it will choose last opened tab, as active one.
This code will handle windows/tab crash too and it will refresh the count at crash.
Because localStorage is not supported on Stack Overflow currently, please test here.
<html>
<body>
Open in several tabs or windows
<div id="holder_element"></div>
<script type="text/javascript">
//localStorage.clear();
manage_crash();
//Create a windows ID for each windows that is oppened
var current_window_id = Date.now() + "";//convert to string
var time_period = 3000;//ms
//Check to see if PageVisibility API is supported or not
var PV_API = page_visibility_API_check();
/************************
** PAGE VISIBILITY API **
*************************/
function page_visibility_API_check ()
{
var page_visibility_API = false;
var visibility_change_handler = false;
if ('hidden' in document)
{
page_visibility_API = 'hidden';
visibility_change_handler = 'visibilitychange';
}
else
{
var prefixes = ['webkit','moz','ms','o'];
//loop over all the known prefixes
for (var i = 0; i < prefixes.length; i++){
if ((prefixes[i] + 'Hidden') in document)
{
page_visibility_API = prefixes[i] + 'Hidden';
visibility_change_handler = prefixes[i] + 'visibilitychange';
}
}
}
if (!page_visibility_API)
{
//PageVisibility API is not supported in this device
return page_visibility_API;
}
return {"hidden": page_visibility_API, "handler": visibility_change_handler};
}
if (PV_API)
{
document.addEventListener(PV_API.handler, function(){
//console.log("current_window_id", current_window_id, "document[PV_API.hidden]", document[PV_API.hidden]);
if (document[PV_API.hidden])
{
//windows is hidden now
remove_from_active_windows(current_window_id);
//skip_once = true;
}
else
{
//windows is visible now
//add_to_active_windows(current_window_id);
//skip_once = false;
check_current_window_status ();
}
}, false);
}
/********************************************
** ADD CURRENT WINDOW TO main_windows LIST **
*********************************************/
add_to_main_windows_list(current_window_id);
//update active_window to current window
localStorage.active_window = current_window_id;
/**************************************************************************
** REMOVE CURRENT WINDOWS FROM THE main_windows LIST ON CLOSE OR REFRESH **
***************************************************************************/
window.addEventListener('beforeunload', function ()
{
remove_from_main_windows_list(current_window_id);
});
/*****************************
** ADD TO main_windows LIST **
******************************/
function add_to_main_windows_list(window_id)
{
var temp_main_windows_list = get_main_windows_list();
var index = temp_main_windows_list.indexOf(window_id);
if (index < 0)
{
//this windows is not in the list currently
temp_main_windows_list.push(window_id);
}
localStorage.main_windows = temp_main_windows_list.join(",");
return temp_main_windows_list;
}
/**************************
** GET main_windows LIST **
***************************/
function get_main_windows_list()
{
var temp_main_windows_list = [];
if (localStorage.main_windows)
{
temp_main_windows_list = (localStorage.main_windows).split(",");
}
return temp_main_windows_list;
}
/**********************************************
** REMOVE WINDOWS FROM THE main_windows LIST **
***********************************************/
function remove_from_main_windows_list(window_id)
{
var temp_main_windows_list = [];
if (localStorage.main_windows)
{
temp_main_windows_list = (localStorage.main_windows).split(",");
}
var index = temp_main_windows_list.indexOf(window_id);
if (index > -1) {
temp_main_windows_list.splice(index, 1);
}
localStorage.main_windows = temp_main_windows_list.join(",");
//remove from active windows too
remove_from_active_windows(window_id);
return temp_main_windows_list;
}
/**************************
** GET active_windows LIST **
***************************/
function get_active_windows_list()
{
var temp_active_windows_list = [];
if (localStorage.actived_windows)
{
temp_active_windows_list = (localStorage.actived_windows).split(",");
}
return temp_active_windows_list;
}
/*************************************
** REMOVE FROM actived_windows LIST **
**************************************/
function remove_from_active_windows(window_id)
{
var temp_active_windows_list = get_active_windows_list();
var index = temp_active_windows_list.indexOf(window_id);
if (index > -1) {
temp_active_windows_list.splice(index, 1);
}
localStorage.actived_windows = temp_active_windows_list.join(",");
return temp_active_windows_list;
}
/********************************
** ADD TO actived_windows LIST **
*********************************/
function add_to_active_windows(window_id)
{
var temp_active_windows_list = get_active_windows_list();
var index = temp_active_windows_list.indexOf(window_id);
if (index < 0)
{
//this windows is not in active list currently
temp_active_windows_list.push(window_id);
}
localStorage.actived_windows = temp_active_windows_list.join(",");
return temp_active_windows_list;
}
/*****************
** MANAGE CRASH **
******************/
//If the last update didn't happened recently (more than time_period*2)
//we will clear saved localStorage's data and reload the page
function manage_crash()
{
if (localStorage.last_update)
{
if (parseInt(localStorage.last_update) + (time_period * 2) < Date.now())
{
//seems a crash came! who knows!?
//localStorage.clear();
localStorage.removeItem('main_windows');
localStorage.removeItem('actived_windows');
localStorage.removeItem('active_window');
localStorage.removeItem('last_update');
location.reload();
}
}
}
/********************************
** CHECK CURRENT WINDOW STATUS **
*********************************/
function check_current_window_status(test)
{
manage_crash();
if (PV_API)
{
var active_status = "Inactive";
var windows_list = get_main_windows_list();
var active_windows_list = get_active_windows_list();
if (windows_list.indexOf(localStorage.active_window) < 0)
{
//last actived windows is not alive anymore!
//remove_from_main_windows_list(localStorage.active_window);
//set the last added window, as active_window
localStorage.active_window = windows_list[windows_list.length - 1];
}
if (! document[PV_API.hidden])
{
//Window's page is visible
localStorage.active_window = current_window_id;
}
if (localStorage.active_window == current_window_id)
{
active_status = "Active";
}
if (active_status == "Active")
{
active_windows_list = add_to_active_windows(current_window_id);
}
else
{
active_windows_list = remove_from_active_windows(current_window_id);
}
console.log(test, active_windows_list);
var element_holder = document.getElementById("holder_element");
element_holder.insertAdjacentHTML("afterbegin", "<div>"+element_holder.childElementCount+") Current Windows is "+ active_status +" "+active_windows_list.length+" window(s) is visible and active of "+ windows_list.length +" windows</div>");
}
else
{
console.log("PageVisibility API is not supported :(");
//our INACTIVE pages, will remain INACTIVE forever, you need to make some action in this case!
}
localStorage.last_update = Date.now();
}
//check storage continuously
setInterval(function(){
check_current_window_status ();
}, time_period);
//initial check
check_current_window_status ();
</script>
</body>
</html>

How to make a piece of Javascript work only when the user is on a different tab?

I have the following javascript to make the webpage title change again and again after every five seconds.
<script>
var titleArray = ["TITLE-1","TITLE-2","TITLE-3","TITLE-4"];
var N = titleArray.length;
var i = 0;
setInterval(func,5000);
function func(){
if (i == 4) {
i = 0;
}
document.title = titleArray[i];
i++;
}
</script>
I want it to work only when the user has opened a different tab in order to "attract" him/her back to my site.While he/she is on my site I want this javascript to stop working so the title of the webpage is what I simply write in the title tags.
here is a summary of what I want.
<script>
if (the user is not on this tab but has opened and is using a different tab)
{the javascript I have mentioned above};
elce {nothing so the title tags work};
</script>
P.S: Is this a good idea? Got any other suggestions? I just really like thinking out of the box.
Please try with below script.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
var isActive;
window.onfocus = function () {
isActive = true;
};
window.onblur = function () {
isActive = false;
};
// test
var titleArray = ["TITLE-1","TITLE-2","TITLE-3","TITLE-4"];
var N = titleArray.length;
var i = 0;
function changeTitle(){
if (i == 4) {
i = 0;
}
document.title = titleArray[i];
i++;
}
setInterval(function () {
if(window.isActive !== true){
changeTitle();
}
}, 1000);
</script>

Make an achor tag non-clickable for while and make it clickable again

How can I make an anchor tag clickable after few seconds ? I made it non-clickable but now can't make it clickable again.
(Note: there will be no id used for the tag)
Heres my html and javascript:
function neww(id,time){
var sec,min,hr;
var i=(time*1);
var neew=setInterval(function(){
if(i>0){
i--;
if(i>=60){
min=parseInt(i/60);
sec=i%60;
if(min>=60){
hr=parseInt(min/60);
min=min%60;
}else{
hr=0;
}
}else{
min=0;
hr=0;
sec=i;
}
if(sec<10){
sec="0"+sec;
}
if(min<10){
min="0"+min;
}
if(hr<10){
hr="0"+hr;
}
id.onclick=function(){return false}; // its working here
id.style.color="red";
id.style.backgroundColor="#ffffff";
id.innerHTML=hr+':'+min+':'+sec;
}
if(i==0){
id.innerHTML="Ready";
id.style.color="#ffffff";
id.style.backgroundColor="green";
if(id.onclick==false){id.onclick=function(){return true};} // but its not working
clearInterval(neew);
}
},1000);
}
Html:
Ready
-Thanks in advance.
SOLVED:
I just removed the 'onclick' attribute from the anchor, so the timer function gets no barrier until the timer completes. Thank you everybody for your effort which helped me to solve this.
Thiss for the link is alive but that doesn't interfere the timer function:
function neww(id,time){
var link=id.getAttribute("onclick");
id.removeAttribute("onclick");
var sec,min,hr;
var i=(time*1);
var neew=setInterval(function(){
if(i>0){
i--;
if(i>=60){
min=parseInt(i/60);
sec=i%60;
if(min>=60){
hr=parseInt(min/60);
min=min%60;
}else{
hr=0;
}
}else{
min=0;
hr=0;
sec=i;
}
if(sec<10){
sec="0"+sec;
}
if(min<10){
min="0"+min;
}
if(hr<10){
hr="0"+hr;
}
id.style.color="red";
id.style.backgroundColor="#ffffff";
id.innerHTML=hr+':'+min+':'+sec;
}
if(i==0){
id.innerHTML="Ready";
id.style.color="#ffffff";
id.style.backgroundColor="green";
id.setAttribute("onclick",link);
clearInterval(neew);
}
},1000);
}
And thiss for the link is dead while the timer is running:
function neww(id,time){
var link=id.getAttribute("onclick");
var linkk=id.getAttribute("href");
var sec,min,hr;
var i=(time*1);//+60;
var neew=setInterval(function(){
if(i>0){
i--;
if(i>=60){
min=parseInt(i/60);
sec=i%60;
if(min>=60){
hr=parseInt(min/60);
min=min%60;
}else{
hr=0;
}
}else{
min=0;
hr=0;
sec=i;
}
if(sec<10){
sec="0"+sec;
}
if(min<10){
min="0"+min;
}
if(hr<10){
hr="0"+hr;
}
id.removeAttribute("onclick");
id.removeAttribute("href");
id.style.color="red";
id.style.backgroundColor="#ffffff";
id.innerHTML=hr+':'+min+':'+sec;
}
if(i==0){
id.innerHTML="Ready";
id.style.color="#ffffff";
id.style.backgroundColor="green";
id.setAttribute("onclick",link);
id.setAttribute("href",linkk);
clearInterval(neew);
}
},1000);
}
Here I am giving you one idea. please modify, according to your need. Hope it help.
After three minutes, it will create the link.
HTML:
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.9.1.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
Ready
</body>
</html>
jQuery:
$(function(){
var link = $('.mynewclass').attr('href');
$('.mynewclass').removeAttr('href');
setTimeout(function(){
$('.mynewclass').attr('href', link);
}, 3000);
});
Javascript:
I am using the javascript getElementsByClassName method. if you are using older browser then i think it will not work. please check the browser support.
window.onload = function () {
var elem = document.getElementsByClassName('mynewclass'),
urlLink = elem[0].getAttribute('href'),
emptyURL = elem[0].removeAttribute('href');
setTimeout(function () {
urlLink = elem[0].setAttribute('href', urlLink);
}, 3000);
}
Here is the jsbin link - http://jsbin.com/dawit/2/
In Vanilla JavaScript:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Delay Click</title>
</head>
<body>
Ready |
Ready |
Ready |
<script>
var enableLinks = false;
setTimeout(function(){
enableLinks = true;
}, 5000); //add delay of 5 seconds = 5000 miliseconds
function clickHandler(e){
var el = e.target;
if(!enableLinks){
e.preventDefault();
}else{
//add rest of your logic here
console.log("it's working");
}
}
var anchors = document.querySelectorAll(".mynewclass");
for(var i=0; i< anchors.length; i++){
if (anchors[i].addEventListener) {
anchors[i].addEventListener('click', clickHandler, false);
} else if (anchors[i].attachEvent) {
anchors[i].attachEvent('onclick', clickHandler);
}
}
</script>
</body>
</html>

Javascript: Opening windows in a row problem

this is my html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Something</title>
</head>
<body>
Try Me!
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script>
$("a").click(function(event){
for(id=0;id<=10;id++){
setTimeout(function() {
var local_id = id;
window.open("http://www.mysite.com/characterID="+local_id,"", "win"+local_id, "width=100,height=100,resizable");
}, 3000*id);
}
event.preventDefault();
});
</script>
</body>
</html>
This link is opening each window 3 seconds after the next.
This is the row I need: http://www.mysite.com/characterID=1, http://www.mysite.com/characterID=2, http://www.mysite.com/characterID=3...
But it always opens http://www.mysite.com/characterID=11
How can I fix it?
Thank you...
This is a common issue.
You're overwriting local_id in the loop, and always referring to the same variable when the code runs. This is because JavaScript does not have block scope, just function scope.
So to scope the id, you need to invoke a function, and define the variable (or function parameter) there.
function createWindow(local_id) {
setTimeout(function () {
window.open("http://www.mysite.com/characterID=" + local_id, "", "win" + local_id, "width=100,height=100,resizable");
}, 3000 * local_id);
}
for (id = 0; id <= 10; id++) {
createWindow(id);
}
Or a similar patter would be to have the function return a function to the loop.
function createWindow(local_id) {
return function() {
window.open("http://www.mysite.com/characterID=" + local_id, "", "win" + local_id, "width=100,height=100,resizable");
};
}
for (id = 0; id <= 10; id++) {
setTimeout( createWindow(id) , 3000 * id);
}
It is because var local_id = id; is called after the loop exits when id is set to 11.
Try this:
for(id=0;id<=10;id++){
setTimeout('window.open("http://www.mysite.com/characterID='+id+'","win'+id+'","width=100,height=100,resizable")', 3000*id);
}
This is a classic JavaScript closure issue. The anonymous function is using the value id which is set to 11 at the end of the loop. To fix this, you need to make a function that returns a function (that will close around the id value).
Try it like so:
$("a").click(function(event) {
var timeout = function(local_id){
return function(){
window.open("http://www.mysite.com/characterID=" + local_id, "", "win" + local_id, "width=100,height=100,resizable");
};
};
for (id = 0; id <= 10; id++) {
setTimeout(timeout(id), 3000 * id);
}
event.preventDefault();
});
You can pass id as an additional parameter to setTimeout, like so: (This is essentially #mrk's answer with less evil.)
setTimeout(function(local_id) {
window.open("http://www.mysite.com/characterID="+local_id,"", "win"+local_id, "width=100,height=100,resizable");
}, 3000*id, id);
After lots of years I wanted to answer my own question. I couldnt remember what I was trying to do but my solution should using let not var. let is scope bounded while var is not.
for(id=0;id<=10;id++){
let local_id = id;
setTimeout(function() {
console.log(local_id)
}, 3000);
}

Categories

Resources