Open a new window after 3 seconds in same tab - javascript

Hii this is my second question i will try to explain. This is a code which close the window after 3 seconds i want new window english.html should appear. thanks
<html>
<head>
<script>
function loaded()
{
window.setTimeout(CloseMe, 3000);
}
function CloseMe()
{
window.close();
}
</script>
</head>
<body onLoad="loaded()">
Hello!
</body>

You can't open a new window in response to anything other than a user interaction. "Three seconds after the page has loaded" is not a user interaction so will be blocked by the standard popup blocking rules that all modern browsers are required to implement by the HTML specification.
Try redirecting the user instead, or better yet, don't: Skip the three second page entirely. If something is worth showing to the user, then it is worth showing to the user until they click a link. That way you know they weren't giving their attention to another tab while your content waltzed by unnoticed.

Below is a simple example of how to achieve what you want:
//<![CDATA[
// external.js
var doc, bod, htm, C, E, T; // for use on other loads
addEventListener('load', function(){ // load start
// I threw in a few goodies to study - it will help you later
doc = document; bod = doc.body; htm = doc.documentElement;
C = function(tag){
return doc.createElement(tag);
}
E = function(id){
return doc.getElementById(id);
}
T = function(tag){ // returns an Array of Elements by tag name
return doc.getElementsByTagName(tag);
}
// notice that `window` is implicit, so you don't actually need to use it to access its properties
setTimeout(function(){ // unexecuted functions and Anonymous functions behave the same
location = 'https://www.w3.org'; // it's really this easy to set the `window.location.href`
}, 3000);
});// load end
/* external.css */
html,body{
padding:0; margin:0;
}
.main{
width:980px; margin:0 auto;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<link type='text/css' rel='stylesheet' href='external.css' />
<script type='text/javascript' src='external.js'></script>
</head>
<body>
<div class='main'>
<div>Just a very simple example</div>
</div>
</body>
</html>
Note: You should practice using external sources so they can be cached. Just make sure you change the filename and path to any source you later change.

Related

Pass global window scoped variable to child iframe in the same domain

Why iframe alert undefined if use setTimeout for changing iframe.src attribute?
Change iframe.src attribute outside of setimeout work.
How to modify|intercept iframe's eval, Function, Element.prototype.appendChild objects if they are different from parent's window (Element !== parent.Element) ?
main.html
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<title>IFrame var pass test</title>
</head>
<body>
<script type='text/javascript'>
ifel = document.createElement('iframe') ;
ifel.frameBorder = ifel.style.width = ifel.style.height = 0 ;
ifel.style.position = 'absolute' ;
ifel.id = 'id-iframe-x' ;
document.body.appendChild(ifel) ;
ifel.contentWindow.Z = 'Y' ; // window changed after load ???
ifel.addEventListener('load', function () {
ifel.contentWindow['Z'] = 'Z' ; // change after load
}) ;
// ifel.src = 'iframe.html' ; // <-- WORK !
setTimeout(function() { // <-- NOT WORK !
ifel.src = 'iframe.html' ;
}, 3000) ;
</script>
</body>
</html>
iframe.html
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<title>IFrame var pass test</title>
</head>
<body>
<script type='text/javascript'>
alert(typeof window.Z) ;
</script>
</body>
You're changing the value of iframewindow.Z from the parent after the iframe is loaded -- this is correct. Your iframe, however, runs its alert before the iframe is finished loading. You need to define a function on the iframe window and call it from the parent window after the iframe is loaded. You could also try to defer the iframe script, but that'll create a race condition -- it might work now, but maybe not always, especially if you have asynchronous data added from the parent.

Scripts execution order - Javascript

I have a HTML file with several JS scripts :
<!DOCTYPE html> <html>
<head>
<title>Application</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
<script src="https://d3js.org/d3.v4.js"></script>
<script src="initMap.js"></script>
<script src="CSVParsing.js"></script>
<script src="nbCinemas.js"></script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=MYKEY&libraries=geometry&callback=initMap"></script>
</head>
<body>
<div id="map" style="width:1000px; height:800px; margin-left:auto; margin-right:auto;"></div>
</body>
My problem is that in my nbCinemas.js file, I am using a global variable that is supposed to have been initialised in CSVParsing.js... but it is not. The thing is, I think that my CSVParsing.js file is loading last. Here is the file:
var arrayData;
d3.csv("cinemas-a-paris.csv", function(data) {
data.forEach(function(d) {
d.lat = +d.lat;
d.lng = +d.lng;
});
arrayData = data;
print();
});
function print() {
console.log("done");
}
In the console, "done" is the last thing written, even though there are other console.logs in my nbCinemas.js file.
Can you help me? Why is my CSVParsing.js file loading last? How can I force it into loading before nbCinemas.js?
Thank you!
Tom.
First, probably
d3.csv("cinemas-a-paris.csv", function(data) {
data.forEach(function(d) {
d.lat = +d.lat;
d.lng = +d.lng;
});
arrayData = data;
print();
});
Is something that is happening in async, so it is send to the event loop, and the "done"message is just show up without that the past function had been finished.
After that, the next file is loaded and initialized and occurs the problem that you have.
One way to deal with this is, verifying that your global variable exists and, if it does, loading dynamicly your next js file like this:
// checking out the variable...
if (typeof variable !== 'undefined') {
// ...the variable is defined, so
var script = document.createElement('script');
script.src = 'http(s)://yourWebSiteURl.com/..js/nbCinemas.js';
}
This way you might ensure that this one last file is loading just after your global variable already exists

clearInterval() not working on clock timer with JavaScript

I am very new to JavaScript and programming in general. I am currently in a little pickle with some code that I am playing around with, and I am wondering if anyone can give me some advice.
Background:
The code I am working with is rather simple; There is a clock with the current time running on setInterval to update by the second.
Below the clock there is a button that reads “Stop,” and when pressed, it will clear the Interval and the button will then read “Start.” If the button, which reads “Start” is pressed again, it will continue the clock timer in its current time. So basically this one button toggles the interval of the clock, and depending on which state it is, the button will read “Start” or “Stop.”
W3Schools: JS Timing is where I am originally referencing when creating the code I am working with. This is where I am learning about how setInterval and clearInterval works. I also took some of the code in the examples and adjusted it so I can try to make the clock timer toggle off and on.
Code:
var clock09 = window.setInterval(myTimer09, 1000);
function myTimer09() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("req09").innerHTML =
"<h1>" + t + "</h1>";
}
function toggle10() {
var button = document.getElementById("button10").innerHTML;
if (button == "Stop") {
window.clearInterval(clock09);
document.getElementById("button10").innerHTML = "Start";
} else {
clock09 = window.setInterval(myTimer09, 1000);
document.getElementById("button10").innerHTML = "Stop";
}
}
<span class="center" id="req09"></span>
<button type="button" id="button10" onclick="toggle10()" class="button">Stop</button>
https://jsfiddle.net/dtc84d78/
Problem:
So my problem with the code is that the button toggles from a “Stop” button to a “Start” button, but the clearInterval is not applying to the Variable with the setInterval.
I have googled similar problems in SO, such as this one, and I followed their advice, and still nothing. After hours of trying to figure out, I decided to just copy and paste some example from W3Schools straight to jsFiddle, and that didn’t even work (included in jsfiddle link)?
I am really just going crazy on why anything with clearInterval() is not working with me? Could it be my computer, browser or anything else? I am coming to SO as my last resource, so if anyone can give me some guidance to this problem, I will name my first child after you.
Thank you in advance.
Extra Info:
I am currently working on a Mac desktop, using Komodo to write the code, and I am using Google Chrome to preview the code.
UPDATE:
I mentioned this in the comments, but coming in the code was in an external .js file. The .js file was then linked in between the head tags, and right before the end body tag.
<head>
<meta charset="utf-8" />
<title>Program</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/program-05.css">
<script type="text/javascript" src="scripts/program-05.js">
/* <![CDATA[ */
/* ]]> */
</script>
</head>
<body onload="checkCookies(); setTimeout(function() { func11() }, 5000);">
. . . code for stuff
. . . code for clock timer
. . . code for other stuff
<script type="text/javascript" src="scripts/program-05.js">
/* <![CDATA[ */
/* ]]> */
</script>
</body>
After #Matz mentioned to stick the clock timer js code in the head section, the code worked great! This is what it looks like so far in the head section.
<head>
<meta charset="utf-8" />
<title>Program</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/program-05.css">
<script type="text/javascript" src="scripts/program-05.js">
/* <![CDATA[ */
/* ]]> */
</script>
<script>
///*
var clock09 = window.setInterval(myTimer09, 1000);
function myTimer09() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("req09").innerHTML =
"<h1>" + t + "</h1>";
}
function toggle10() {
var button = document.getElementById("button10").innerHTML;
if (button == "Stop") {
window.clearInterval(clock09);
document.getElementById("button10").innerHTML = "Start";
} else {
clock09 = window.setInterval(myTimer09, 1000);
document.getElementById("button10").innerHTML = "Stop";
}
}
//*/
</script>
</head>
Though this works great, I now want to figure out as to why the clock timer js code works when it is directly in the head section as compared to keeping it in the external .js file (with the external file being linked in the doc)? What can I do to make it work within the external file?
Problem:
This is because the default Load Type is set to onLoad which is wrapping your javascript code in window.onload = function() {} hence the scope of your function was getting limited to the onload function and it wasn't available outside:
Solution:
Click on the Javascript setting in the Javascript section of the Fiddle, change it to No wrap - in body and it will work since this will now place your Javascript code in the body tag.
Additional Note:
Your code is also working via StackOverflow snippet:
/*My Problem*/
var clock09 = window.setInterval(myTimer09, 1000);
function myTimer09() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("req09").innerHTML =
"<h1>" + t + "</h1>";
}
function toggle10() {
var button = document.getElementById("button10").innerHTML;
if (button == "Stop") {
window.clearInterval(clock09);
document.getElementById("button10").innerHTML = "Start";
} else {
clock09 = window.setInterval(myTimer09, 1000);
document.getElementById("button10").innerHTML = "Stop";
}
}
/*W3S Problem*/
var myVar = setInterval(myTimer, 1000);
function myTimer() {
var d = new Date();
document.getElementById("demo").innerHTML =
d.toLocaleTimeString();
}
<!-- My Problem -->
<span class="center" id="req09"></span>
<button type="button" id="button10" onclick="toggle10()" class="button">Stop</button>
<hr>
<hr>
<!-- W3S Problem -->
<p id="demo"></p>
<button onclick="clearInterval(myVar)">Stop time</button>
Recommendation
Separation of concerns
I'll recommend you moving your javascript code in the external file and later include them in your HTML using script tag. So for example, you moved your code in app.js then include that in your HTML as:
<!-- make sure the path here is relative to the current HTML -->
<script src="./app.js"></script>
One way to fix the timer starting and stopping is to move the javascript in between the HEAD tags so the functions are declared by the time the html loads. I made this work:
<html>
<head>
<title>Stuff</title>
<script >
var clock09 = window.setInterval(myTimer09, 1000);
.... your code
</script>
</head>
<body>
<span class="center" id="req09"></span>
<button type="button" id="button10" onclick="toggle10()" class="button">Stop</button>
</body>
</html>
You are declaring a new date variable in the myTimer09 function, so every time it is called, it shows the current time. You should declare the time outside the function, then pass it to the function. When you stop the timer, you should save the time value so that you can restart with that value.
This seems to be an issue with JSFiddle.
The onclick handler is looking for window.toggle10 which isn't actually defined (check for the error in the console).
It seems that this is something others have seen with JSFiddle
I've C&Ped your code in to a JSbin and it works as described!

Change a div background image using javascript if/else

I am trying to get the background image of a div to change at an interval. I created an Array with the images, and every few seconds the function should check the value of "x" against the array length. If X is less, x will increase by one and the background image will change to the next image in the array, otherwise it will set x=0 and restart the process.
The div and initial image shows up how I want, but nothing happens.
I know there are probably better ways to do this, but I am very new to Javascript and want to learn why this code doesn't work. Thanks in advance for the help!!
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>ImageChanger</title>
<style type="text/css">
#imagediv {
float:left;
border-style:ridge;
border-width:8px;
border-color:Green;
border-radius:15px;
width:1250px;
height:450px;
background-image:url(images/landscape1.jpg)
}
</style>
<script type="text/javascript">
function displayNextImage() {
var x;
If (x<imageArray.length) {
x=x+1;
document.getElementById("imagediv").style.backgroundImage=images[x];
}
else {
x=0;
document.getElementById("imagediv").style.backgroundImage=images[x];
}
function startTimer() {
setInterval(displayNextImage, 3000);
}
var imageArray=new Array();
images[0] = "images/landscape1.jpg";
images[1] = "images/landscape2.jpg";
images[2] = "images/landscape3.jpg";
images[3] = "images/landscape4.jpg";
</script>
</head>
<body>
<div id="imagediv">
</div>
</body>
</html>
If (x<imageArray.length) {..
should be
if (x<imageArray.length) {
Javascript is case-sensitive.
Also you have some missing braces like you are not closing
function displayNextImage() { ....
Use your browser console to debug. These syntax errors will be shown there.
As far as syntax issues go:
As #Zee stated, If should be lowercase (if)
Also, as #Zee and some others stated, you are not closing function displayNextImage() { with a closing brace }.
You are improperly defining the background-image property in your function, whereas you defined it correctly in the block of CSS. You must wrap the image name with url().
You are never calling your timeout function, startTimer.
You create a new array imageArray but then use an undeclared array images

What is the preferred way of searching for content in source code using JS?

I have a JavaScript statement on the bottom of my page that I want to trigger ONLY if a certain HTML comment is available
<!-- mytriggercomment -->
In the above example, if the mytriggercomment is detected within the current page, only then should the JavaScript statement trigger. What is the preferred way of doing this?
May not work for older browsers, but this way is a logical DOM approach:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script>
window.onload = function () {
var treeWalker = document.createTreeWalker(
document,
NodeFilter.SHOW_COMMENT,
{acceptNode: function(node) {
if (node.nodeValue.trim() === 'mytriggercomment') {
return NodeFilter.FILTER_ACCEPT;
}
}}
);
var nodeList = [];
while(treeWalker.nextNode()) nodeList.push(treeWalker.currentNode);
alert(nodeList)
};
</script></head>
<body>
</body>
</html>
<!-- mytriggercomment -->
If you know it will always be at the bottom, you may be able to target it like:
window.onload = function () {
alert(document.documentElement.nextSibling &&
document.documentElement.nextSibling.nodeValue.trim() === 'mytriggercomment')
};

Categories