Dynamically created anchor doesn't work after setTimeout - javascript

Hi I make a Timer with Javascript, it works fine. And when it finish the 5 seconds count the code enable a target for open a web, but when I click its dont working. I try this code outside the timer and its works perfectly. What is the error?
<?php
$windowsOpen .= "window.open('$value', '_blank');";
?>
<script type="text/javascript">
function countDown(secs,elem){
var element = document.getElementById(elem);
element.innerHTML = "Please wait for "+secs+" seconds";
if(secs < 1){
clearTimeout(timer);
element.innerHTML='<p>Click to open webs</p>';
}
secs--;
var timer = setTimeout('countDown('+secs+',"'+elem+'")',1000);
}
</script>
<div id="status"></div>
<script type="text/javascript">countDown(5,"status");</script>

Inline event handlers are essentially eval inside HTML markup - they're bad practice and result in poorly factored, hard-to-manage code. Seriously consider attaching your events with JavaScript, instead: developer.mozilla.org/en/DOM/element.addEventListener
If you absolutely need the window opener to be handled with Javascript instead of the browser's nice native behavior, then define the URL you want people to navigate to upfront, and then attach a listener to the element when it's created:
<?php
$url = 'https://www.google.com';
?>
<script type="text/javascript">
var url = '<?=$url;?>';
var timer;
function countDown(secs,elem){
var element = document.getElementById(elem);
element.innerHTML = "Please wait for "+secs+" seconds";
if(secs < 1){
element.innerHTML='<p>Click to open link</p>';
element.querySelector('a')
.addEventListener('click', () => {
window.open(url);
});
} else {
secs--;
setTimeout(countDown, 1000, secs, elem);
}
}
</script>
<div id="status"></div>
<script type="text/javascript">countDown(5,"status");</script>
You should also avoid using eval in your setTimeout - always write out functions in normal JS, rather than as strings to be parsed into functions.
But it would be much less user-unfriendly if you would let them click the link themselves, using the browser's normal behavior:
element.innerHTML='<p>Click to open link</p>';
element.querySelector('a')
.href = url;

Related

JavaScript code to conditionally change link URL

I know this has been covered extensively as separate issues; I've tried copying verified answers, but I'm having trouble homologating Javascript conditional statements and a link URL change.
Essentially, what I need to do is detect mobile users and change a conference call URL to a tel link. I've been using if (screen.width <=699) { as the condition and it works on redirects. Here's what I've tried:
<script type="text/javascript">
<!--
var call=document.getElementByID('phone');
if (screen.width <= 699) {
call.write('<a href="tel:!PHONENUMBER!">');
else
call.write('<a href="!URL!" target="blank">);
}
//--!>
</script>
</head><body>
...
...
I've also tried these with corresponding else statements to no avail:
no var and document.getElementByID('phone').write
onclick = function() { window.location.href ='tel:!PHONENUMBER!};.
call.src.replace('tel:!PHONENUMBER!');
call.setAttribute("href",'tel:!PHONENUMBER!');
I apologize if this is a super basic issue - I'm still learning Javascript. Thank you in advance.
Will
You need to either wait for the page to finish loading before you execute your JavaScript or move your script block to the bottom of the HTML.
If you want to wait for the page to finish loading, then wrap your code in the following:
window.onload = function () {
// your code goes here
}
Figured it out with help from #sepbot.
<body onload="mobileURL()">
<div id="phone"></div>
<script type="text/javascript">
function mobileURL() {
var a = document.createElement("a");
a.innerHTML="!LINKTEXT!";
var myPhone = document.getElementById('phone');
if (screen.width <= 699) {
a.setAttribute('href', '!TELEPHONE!');
myPhone.appendChild(a);
} else {
a.setAttribute('href', '!URL!');
myPhone.appendChild(a);
}
}
</script>

How to run code from javascript widget after 10 secs of page load?

I have created a javascript widget that displays popups and anyone can embed it on their websites by pasting a few lines of code before closing </body> tag.
While configuring it a user can specify that he wants a popup to be displayed after 10 secs of page load. But since my script depends on jQuery and before executing its main code it must load it first - sometimes script executes its main() function much later than in 10 secs...
So currently the steps are:
Web page is loaded (I do not know how much time it will take)
My script is loaded (I do not know how much time it will take)
My script loads jQuery if necessary (I do not know how much time it will take)
Only when jQuery is loaded it starts counting 10 secs and then runs displayPopup function
As you can see it's unsafe to run displayPopup function in 10 secs after $(document).ready event because it may not load jQuery or itself yet. And it's okay - it's a technical restriction I can not do anything about (right?).
I just need a way to know how much time has passed since $(document).ready event. And then I will check this number of seconds inside my main() function and decide if I need to display popup immediately (if page was loaded > 10 secs ago) or wait a few seconds.
Script install code:
<script>
(function() {
var scriptTag = document.createElement("script");
scriptTag.type = "text/javascript";
scriptTag.async = true;
scriptTag.src = "https://www.server.com/script.js";
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(scriptTag, s);
})();
</script>
Loading jQuery part of script.js
if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.12.4') {
var script_tag = document.createElement('script');
script_tag.setAttribute("type","text/javascript");
script_tag.setAttribute("src",
"//ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"
);
if (script_tag.readyState) {
script_tag.onreadystatechange = function () {
if (this.readyState == 'complete' || this.readyState == 'loaded') {
scriptLoadHandler();
}
};
}
else {
script_tag.onload = scriptLoadHandler;
}
(document.getElementsByTagName("head")[0] ||
document.documentElement).appendChild(script_tag);
}
else {
jQuery = window.jQuery;
main();
}
function scriptLoadHandler() {
jQuery = window.jQuery.noConflict(true);
main();
}
Main function:
function main() {
setTimeout(function() {
displayPopup();
}, settings['numberOfSeconds'] * 1000);
}
In your install code, set a global variable that captures the current time. Since this is right before the <body> ends it should start right when the DOM has loaded. Then in your main() function, check how much time has passed in the variable. If it's more than 10 seconds, you can show your popup immediately. If it's less, you can calculate the time that has passed and set a timeout to fire once 10 seconds has really passed:
<script>
(function() {
window.myPopupWidgetStartDate = Date.now();
var scriptTag = document.createElement("script");
scriptTag.type = "text/javascript";
scriptTag.async = true;
scriptTag.src = "https://www.server.com/script.js";
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(scriptTag, s);
})();
</script>
function main() {
var secondsSinceInstall = Math.round((window.myPopupWidgetStartDate - Date.now());
if (secondsSinceInstall > settings['numberOfSeconds']) {
displayPopup();
} else {
setTimeout(function() {
displayPopup();
}, settings['numberOfSeconds' - secondsSinceInstall] * 1000);
}
}
You don't have to mess with timetous or intervals. Its pretty simple actually from my point of view, considering I got everything right.
Once you got document.ready grab the current timestamp. Let it be documentReadyAt.
Once jquery was loaded grab the current timestamp again. Let it be jqReadyAt.
Compare the jqReadyAt against documentReadyAt and find the difference. If jQuery already exists the difference will be insignificant. A matter of couple milliseconds. If jquery had to be loaded will be more than 100ms to few seconds.
Start counting whatever you like.
var documentReadyAt, jqReadyAt;
document.onreadystatechange = function () {
if (document.readyState === "complete" && documentReadyAt === undefined) {
documentReadyAt = new Date();
loadJQ(); // Loading jQuery part of script.js.
}
}
//function loadJQ(){ ...whatever you wrote to load jquery }
//For the sake of handling same logic in one place will assign a variable to jqReadyAt here. Could also be done at `main()` without noticeable cost.
function scriptLoadHandler() {
jqReadyAt = new Date();
jQuery = window.jQuery.noConflict(true);
main();
}
//Main will change to that one.
function main() {
var millisPassedSinceDocLoaded = jqReadyAt.getTime() - documentReadyAt.getTime();
setTimeout(function() {
displayPopup();
}, (settings['numberOfSeconds'] * 1000) - millisPassedSinceDocLoaded );
}
you would need to use performance.timing API. there are many useful data there to use, like domContentLoadedEventEnd, domContentLoadedEventStart, loadEventStart, loadEventEnd etc. for your case to measure how much time passed since the dom ready event is triggered, in your main function use below code to get the passed time. once get the elapsed you can now decide how to proceed.
var timePassedSinceDomReady = new Date() - new Date(performance.timing.domContentLoadedEventEnd);
console.log('total time passed: ' + timePassedSinceDomReady + 'ms');
most modern browsers support it. for more details on timing API a see https://developer.mozilla.org/en-US/docs/Web/API/PerformanceTiming, http://www.html5rocks.com/en/tutorials/webperformance/basics/
You could try setting a flag for when jQuery is loaded, then start the setTimeout straight from the document.ready, and check if jQuery is loaded before displaying the popup.
Otherwise you might want to take a look at this question.

Javascript: Using while loop to wait for document load not working

I'm trying to create an html document for my coworkers to complete an online test (I have the right answers). When the document loads, it requests your user and password and tries to log in, then fill the answers and submit.
However I can't pass the user and password values to the elements in the page, this is the error:
Cannot set property 'value' of null
The page is not loading completely when my script tries to get its elements, how could I make this work?
<html>
<head>
<title>BCG test</title>
<script type="text/javascript">
function bcg(){
var user = prompt("Enter username: ");
var pass = prompt("Enter password: ");
var site = "http://app.huawei.com/bcg";
location = site;
while(true){
if (document.readyState == "complete"){
break;
}
}
var user_box = document.getElementById("uid");
var pass_box = document.getElementById("password");
var submit_button = document.getElementsByName("Submit")[0];
user_box.value = user;
pass_box.value = pass;
submit_button.click();
}
</script>
</head>
<body onload = "bcg()">
<h1>BCG TEST</h1>
</body>
</html>
You shouldn't use a while(true) loop because that loops infinitely fast, forever. That will cause the browser to freeze. If you need to keep checking something, set a timer with setInterval.
However, for this purpose, it appears you want to wait until the page loads. Put your code to be executed in this block instead:
document.addEventListener("DOMContentLoaded", function() {
var user_box = document.getElementById("uid");
var pass_box = document.getElementById("password");
var submit_button = document.getElementsByName("Submit")[0];
user_box.value = user;
pass_box.value = pass;
submit_button.click();
});
You can't do that in javascript:
while(true){if(document.readyState == "complete"){ break; }}
It will never exit this event frame.
use window.onload = function(){} or $(document).ready(function(){})
Any of these functions will be called when document loads.

Showing warning with timeout when opening external links

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
}

One time page refresh after first page load

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>

Categories

Resources