How to delay a link for 5 seconds with HTML? [duplicate] - html

I've been looking through the Stackoverflow questions, trying to get help with a simple link delay; I want to put it around a div, and I can't make heads or tails of the examples I've found.
So far, I understand that I need to halt the native function of href, but I don't know how to do that. The code is still very alien to me. Help?

Set your href attribute as href="javascript:delay('URL')" and JavaScript:
function delay (URL) {
setTimeout( function() { window.location = URL }, 500 );
}

If you want to delay every link on your page, you can do it with jQuery like this
$(function(){
$("a").click(function(evt){
var link = $(this).attr("href");
setTimeout(function() {
window.location.href = link;
}, 500);
});
});

I use this to keep the function waiting before continuing:
var wait_until = new Date().getTime() + 500;
while (new Date().getTime() < wait_until) {
//Do nothing, wait
}

To delay a link with inline javascript, just
set your href attribute as href="javascript:setTimeout(()=>{window.location = 'URL' },500);".
When you replace the URL with your link, just make sure it is inside the ' '.
<li class="nav-item">
<a href="javascript:setTimeout(()=>{window.location = '#About' },500);">
About Me
</a>
</li>

If you want to open on a new tab (target="_blank"),
This would be #gurvinder372's code changed to account for the new tab:
If you want to use any other target setting, just change the "_blank" to your preferred setting.
function delay(URL) {
setTimeout(function () {
window.open(URL, "_blank"); // this is what I've changed.
}, 500);
}

Related

Define a keyword to replace a long url

To create download button I normally use:
<button></button>
Is there any way to define myfile = url-to-the-file so that I can use just:
<button></button>
Per my comment, I'm not sure why you would want to do this, but for example you could replace the short text with the real links fairly easily. Just as a very basic example (http://jsfiddle.net/7vbv9oxc/):
HTML:
<button>
Click
</button>
JS:
var links = {
googs: "http://google.com"
}
// jQuery but vanilla JS shouldn't be hard
$('a').each(function(){
var $this = $(this);
var shortLink = $this.attr('href');
if(typeof(links[shortLink]) !== "undefined") {
$this.attr('href', links[shortLink]);
}
});
Alternatively, you could do the substitution at click time, saving iterating over all the anchor tags.
$('a').on('click', function(e) {
var $this = $(this);
var shortLink = $this.attr('href');
if(typeof(links[shortLink]) !== "undefined") {
$this.attr('href', links[shortLink]);
}
});
We don't prevent default (or return false) because we WANT it to act like a normal anchor, but after the swap has been made. If you want to do something different before loading or redirecting the target URL, you would add an e.preventDefault() to that code block.
Note (for my own peace of mind!) that none of this code is meant to represent optimizations or best practices; it's just meant to illustrate the idea. For example, you would probably want to put the click listener on an ancestor!

HTML <a> tag download file error handling

In my app I have tag with link to api for file download (pdf). The problem is that it is not 100% stable and I have to handle then service is not available or file is not available and server responds with error.
<a href="link/to/api" target="_blank" download="filename">
By the way I am using AngularJS in this app. If there is any solution using it it would help a lot
In case somebody else will face similar problem. Here is the solution I have implemented after some research.
Remove the link from an <a> tag and add a click event:
<a href="#" ng-click="downloadFile()">
now you need to download blob (here you can control if you can access it file) and let make DOM object add all needed attributes end trigger it.
$scope.downloadFile = function () {
$http.get('api/link', { responseType: 'arraybuffer' })
.then(function (data) {
var file = new Blob([data], { type: "application/pdf" });
var url = $window.URL || $window.webkitURL;
var fileURL = url.createObjectURL(file);
var a = document.createElement("a");
a.href = fileURL;
a.download = "nameOfFile";
a.target = "_self";
a.click();
url.revokeObjectURL(fileURL);
}).error(function (data) {
console.error(data);
})
};
UPDATE:
This was working only for Chrome. Other browsers had different approach of downloading blob. So I have users FileSaver.js for this task. Even then I had problems opening it on iOS. It is blocking file saving if it was triggered out side of user event. Here is my workaround for this.
var file = new Blob([data], { type: "application/pdf" });
var isIos = (navigator.userAgent.match(/(iPad|iPhone|iPod)/g) ? true : false);
if(isIos){
var element = document.getElementById("downloadButton");
element.onclick - function(){
saveAs(file, "name.pdf");
}
element.onclick();
} else {
saveAs(file, "name.pdf");
}
Hope this will save time for someone.
Use extensionnames after the link like link/to/api.pdf and download="filename.pdf".
Also, try target="_self"

How to preload images on refresh?

I have a code, which gets refreshed from mysql database on a button click.
From the mysql I get links of images on refresh, but I never know, hat links and how many.
I have a "loading" circle which spins until the page is loaded, but it is shown only, until the code is loaded, which is not very long. After that I see small empty squares on my page as placeholders, until the real images show up.
Does anybody have an idea, how to show the spinning circle untill all images are loaded?
I tried some javascript examples found on the net with building arrays of links, but I was not able to integrate them into my code, because the construction of the codes are very different and I obviously am not a pro.
So here is my code (I simplified it for now):
$(document).ready(function() {
function refresh(free){
$("#loadingfree").show();
if (free) datum = datum + free;
var url = "listfree.php?date=" + datum;
$.getJSON(url,function(data) {
var div_data = '';
$.each(data, function(i,data) {
div_data += "<div class='iconsfree'><a href='"+data.title+"-"+data.appID+"' title='"+data.title+"'><img src='"+data.icon+"'></img></a></div>";
});
$("#loadingfree").hide();
$("#app-wrapper-free").html(div_data);
});
}
$(document).on('click', '#prevbuttonfree', function(e){
e.preventDefault();
$("#app-wrapper-free").empty();
refresh(-1);
});
$(document).on('click', '#nextbuttonfree', function(e){
e.preventDefault();
$("#app-wrapper-free").empty();
refresh(+1);
});
// call the method when page is opened:
refresh(0);
});
If you want the spinner to continue showing until the images are loaded, you should use the load eventListener to make that happen.
So let's say you have your code that has the spinner while it makes the request to the server.
//just an example
$('button').click(function(){
//call server
$.ajax();
//show spinner
$('.spinner').show();
});
Now we will tell the spinner to stay showing until the images are done loading.
$('img').on('load',function(){
//Not sure what your spinner is called
$('.spinner').hide();
});
I ended up with this.
It just shows the content a bit later. It's a fake preloader.
<script type="text/javascript">
var datum = 0;
$(document).ready(function() {
function refresh(free){
if (free) datum = datum + free;
var url = "listfree.php?date=" + datum;
$.getJSON(url,function(data) {
var div_data = '';
$.each(data, function(i,data) {
if ($("#date_free").html() == '');
div_data += "<div class='iconsfree'><a href='"+data.title+"-"+data.appID+"' title='"+data.title+"'><img src='"+data.icon+"'></img></a></div>";
});
$("#loadingfree").show();
$(div_data).hide()
.appendTo("#app-wrapper-free")
setTimeout( function() {
$("#app-wrapper-free").children().show()
$("#loadingfree").hide()
}, 3000 );
});
}
$(document).on('click', '#prevbuttonfree', function(e){
e.preventDefault();
$("#app-wrapper-free").empty();
refresh(-1);
});
$(document).on('click', '#nextbuttonfree', function(e){
e.preventDefault();
$("#app-wrapper-free").empty();
refresh(+1);
});
// call the method when page is opened:
refresh(0);
});
</script>

change the body background every 10 seconds

I'm looking for a really simple and lightweight code that change the body background of the website (it can go with the css also) every 10 seconds, it's supposed to be something easy with jquery and css, right?
how can i do that?
You can use JavaScript's setTimeout() function. Here is an example of how to use it.
For setTimeout(), you need 2 parameters, one being your function, and the other an integer, which is how long your timeout will last.
So for your instance, you can do:
$(function() {
var newBg = ['img1.png', 'img2.jpg', 'img3.png'];
var path="img/";
var i = 0;
var changeBg = setTimeout(function() {
$('body').css({backgroundImage : 'url(' path + newBg[i] + ')'});
if(i == newBg.length)
i=0;
else
i++;
}, 10000);
});
This creates an array of your images, specified with a path. Thus I create a variable which checks the length of your arrayList, and whether or not you need to reset the variable i.
So i hope that helps :)
custom-background.js is a lightweight jQuery plugin to allow users change the website’s default background and saves the background selected to local storage. This plugin can easily be added to any website or web app without any compromise on website's performance.
https://github.com/CybrSys/custom-background.js
You can easily do this with jQuery.
A simple javascript function to toggle between two colors every X seconds
function toggle_color(color1,color2,cycle_time,wait_time) {
setInterval(function first_color() {
$("body").animate({
backgroundColor: color1
}, 1000, function () {
setTimeout(change_color, wait_time);
});
}, cycle_time);
function change_color() {
$("body").animate({
backgroundColor: color2
}, 1000, function () {
setTimeout(function () {}, wait_time);
});
}
}
You can check Changing background color every X seconds in Javascript for working demo and explanation.

dojo 1.8 integrating html5 postmessage

Im trying to get some html5 post messaging going with dojo 1.8, i've created a jsfiddle to try to explain it better. One thing to note is that the button is being loaded within the iframe. So basically if a click happens within the iframe then the parent node should receive and act upon the message. Any pointers would be appreciated.
http://jsfiddle.net/AvPFv/
Basically, you should listen for message on iframe window, i.e. iframe.contentWindow. Also, please note there is no dojo in your iframe.
I created a jsFiddle to show how it works: http://jsfiddle.net/phusick/H7Zh8/ but I'm afraid it is very messy to have everything in a single file, i.e. in the context of the parent window, because it does not explain properly where window reference points to and it does not simulate real world usage. I suggest you try it at localhost having two sets of scripts, one for parent window and one for iframe.
require([
"dojo/dom",
"dojo/on",
"dojo/date/locale",
"dojo/domReady!"
], function(
dom,
on,
locale
) {
var buttonNode = dom.byId("postMessageButton");
var iframeNode = dom.byId("iframe");
var iframe = iframeNode.contentWindow;
var iframeButtonNode = iframe.document.getElementById("postMessageButton");
on(buttonNode, "click", function() {
iframe.postMessage("hello from parent", "*");
});
on(iframe, "message", function(event) {
var msgNode = iframe.document.getElementById("msg");
msgNode.innerHTML += formatMessage(event);
event.source.postMessage("echo from iframe", "*");
});
on(iframeButtonNode, "click", function() {
iframe.parent.postMessage("hello from iframe", "*");
})
on(window, "message", function(event) {
dom.byId("msg").innerHTML += formatMessage(event);
});
function formatMessage(event) {
var time = locale.format(new Date(event.timeStamp),{
selector: "time",
formatLength: "medium"
});
return time + ": " + event.data + "<br>";
}
});