Switching between documents using Javascript? - javascript

I'm working on a karaoke video assignment and was hoping to find a way to flip between two different index.html documents (one for chorus, one for verses) using JS. I have limited knowledge of Javascript and am in the process of learning it. So far I think I need to use the following:
$(document).ready(function () {
window.setTimeout(function () {
window.location.href = "index2.html";
}, 5000);
});
Right now I have my index1.html and index2.html for the chorus and verses. I'm thinking I'd make an external JS file with the above function which displays index1.html for x amount of seconds and then index2.html for another duration. Sorry if this question is too simple or not well clarified. Still a beginner so any help is appreciated! Thanks!

What you are looking for is:
window.location.replace('path/to/index2.html')
I'm not sure what your directory structure looks like but you can pass it a relative or absolute path.

you don't even need javascript for this purpose, just put this in your head section:
<meta http-equiv="refresh" content="5; url=index2.html">
it will redirect to index2.html after 5 seconds.
http-equiv means "http header equivalent". As you can guess it can also be a http header sent by the server so you can serve even pure txt documents and switch them using headers sent by server.
If you want to use the power of javascript, you don't need to switch between pages, you can simply hide one content or another which is pretty simple:
<pre id="verse1">
verse 1 here
</pre>
<pre id="chorus" style="display: none">
chorus here
</pre>
<script>
$(function () {
window.setTimeout(function () {
$('#verse1').hide();
$('#chorus').show();
}, 5000);
});
</script>

Related

Lazy-load a javascript script?

Is there a way I can wrap an external JS script embed with lazy-load behavior to only execute when the embed is in the viewport?
Context: I have an external javascript embed that when run, generates an iframe with a scheduling widget. Works pretty well, except that when the script executes, it steals focus and scrolls you down to the widget when it’s done executing. The vendor has been looking at a fix for a couple weeks, but it’s messing up my pages. I otherwise like the vendor.
Javascript embed call:
<a href=https://10to8.com/book/zgdmlguizqqyrsxvzo/ id="TTE-871dab0c-4011-4293-bee3-7aabab857cfd" target="_blank">See
Online Booking Page</a>
<script src=https://d3saea0ftg7bjt.cloudfront.net/embed/js/embed.min.js> </script> <script>
window.TTE.init({
targetDivId: "TTE-871dab0c-4011-4293-bee3-7aabab857cfd",
uuid: "871dab0c-4011-4293-bee3-7aabab857cfd",
service: 1158717
});
</script>
While I'm waiting for the vendor to fix their js, I wondered if lazy-loading the JS embed may practically eliminate the poor user experience. Warning: I'm a JS/webdev noob, so probably can't do anything complicated. A timer-based workaround is not ideal because users may still be looking at other parts of the page when the timer runs out. Here are the things I’ve tried and what happens:
I tried:
What happened:
Add async to one or both of the script declarations above
Either only shows the link or keeps stealing focus.
Adding type=”module” to one or both script declarations above
Only rendered the link.
Wrapping the above code in an iframe with the appropriate lazy-loading tags
When I tried, it rendered a blank space.
Also, I realize it's basically the same question as this, but it didn't get any workable answers.
I actually also speak french but I'll reply in english for everybody.
Your question was quite interesting because I also wanted to try out some lazy loading so I had a play on Codepen with your example (using your booking id).
I used the appear.js library because I didn't really want to spend time trying some other APIs (perhaps lighter so to take in consideration).
The main JS part I wrote is like this:
// The code to init the appear.js lib and add our logic for the booking links.
(function(){
// Perhaps these constants could be put in the generated HTML. I don't really know
// where they come from but they seem to be related to an account.
const VENDOR_LIB_SRC = "https://d3saea0ftg7bjt.cloudfront.net/embed/js/embed.min.js";
const UUID = "871dab0c-4011-4293-bee3-7aabab857cfd";
const SERVICE = 1158717;
let vendorLibLoaded = false; // Just to avoid loading several times the vendor's lib.
appear({
elements: function() {
return document.querySelectorAll('a.booking-link');
},
appear: function(bookingLink) {
console.log('booking link is visible', bookingLink);
/**
* A function which we'll be able to execute once the vendor's
* script has been loaded or later when we see other booking links
* in the page.
*/
function initBookingLink(bookingLink) {
window.TTE.init({
targetDivId: bookingLink.getAttribute('id'),
uuid: UUID,
service: SERVICE
});
}
if (!vendorLibLoaded) {
// Load the vendor's JS and once it's loaded then init the link.
let script = document.createElement('script');
script.onload = function() {
vendorLibLoaded = true;
initBookingLink(bookingLink);
};
script.src = VENDOR_LIB_SRC;
document.head.appendChild(script);
} else {
initBookingLink(bookingLink);
}
},
reappear: false
});
})();
I let you try my codepen here: https://codepen.io/patacra/pen/gOmaKev?editors=1111
Tell me when to delete it if it contains sensitive data!
Kind regards,
Patrick
This method will Lazy Load HTML Elements only when it is visible to User, If the Element is not scrolled into viewport it will not be loaded, it works like Lazy Loading an Image.
Add LazyHTML script to Head.
<script async src="https://cdn.jsdelivr.net/npm/lazyhtml#1.0.0/dist/lazyhtml.min.js" crossorigin="anonymous" debug></script>
Wrap Element in LazyHTML Wrapper.
<div class="lazyhtml" data-lazyhtml onvisible>
<script type="text/lazyhtml">
<!--
<a href=https://10to8.com/book/zgdmlguizqqyrsxvzo/ id="TTE-871dab0c-4011-4293-bee3-7aabab857cfd" target="_blank">See
Online Booking Page</a>
<script src=https://d3saea0ftg7bjt.cloudfront.net/embed/js/embed.min.js>
</script>
<script>
window.TTE.init({
targetDivId: "TTE-871dab0c-4011-4293-bee3-7aabab857cfd",
uuid: "871dab0c-4011-4293-bee3-7aabab857cfd",
service: 1158717
});
</script>
-->
</script>
</div>

How to use Javascript/jQuery to load the content from another domain?

I need to create a javascript application that can display the content from another domain (admittedly another big website). Further interpretation of the DOM tree is not needed at the moment. It will be used by only ten more people.
I can make it work via php's get_content function. But that is very slow since it runs on the server side. I looked into any origin but cannot get it to work. It is best to not touch any origin since we use it extensively and we don't have much cash to spend around. Can anyone help? By the way, iframe is not an option since the big website blocked it. The code is below. Admittedly I kind of took it from another stackoverflow answer. Thank you in advance!
Btw. another engineer told me if I use the extension .hta instead of html, the same-origin policy issue would be resolved. I tried it and it did not work. But I was wondering if I did it right.
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
function myCallbackFunction(myData) {
$(function() {
$("#test").contents().find('html').html(myData.contents);
});
}
</script>
<script src="http://anyorigin.com/get?url=http://http://www.amazon.com/dp/B001F7SGHQ/&callback=myCallbackFunction"></script>
</head>
<body>
</body>
<iframe id='test' style='width: 100%; height: 100%'>
</html>
Try something like the following.
var invocation = new XMLHttpRequest();
var url = 'http://http://www.amazon.com/dp/B001F7SGHQ/&callback=myCallbackFunction';
function callOtherDomain() {
if(invocation) {
invocation.open('GET', url, true);
invocation.withCredentials = true;
invocation.onreadystatechange = handler;
invocation.send();
}
}
Addition of [withCredentials = true] will enable the HTTP header "Access-Control-Allow-Origin:".
there's another good solution might be what you need via PHP ,
is to use class called PHP
Simple HTML DOM Parser
this class can copy all source of a websites and you can save it in your server with extension you want also you can modified what you need before you save and this class have a full documentation (You need to be good in PHP5 POO )
this a link for class
http://simplehtmldom.sourceforge.net/
and there a good advanced thing you can do it for make your website faster , is use a Cash System so you can download the source from website one time a Day or 1H or 12 Hours ,
and save it in your host .
i hope that will give you what you need .

"Splash Page" NOT index.asp

Client requests a small video to play as a "splash page". But I dont want to make it the index page for SEO purposes. Can I place a re-direct line of code at the top of my index? Cookies to make it only once?
I think there might be a few ways to do this, but i know none of them.
Thanks for your time.
James
Like my comment you can use jquery to achieve this. Check my example: http://jsfiddle.net/LSjbS/
The splash section should come last in the markup, as it has the least importance.
You can use javascript:
<script type="text/javascript">
setTimeout('Redirect()',4000); //time in ms
function Redirect()
{
location.href = 'http://www.website.com/path/splash';
}
​
</script>
It's that easy :) Just put it in the head section. the 4000 is the time in ms (as shown by my comment) change this to 1 for an almost immediate redirect :)

Javascript function to reload a page every X seconds?

A couple of questions:
I've never really used JS listeners other than onclick and onkey events, so I wondered if someone could help me with what I need in order to reload the page every X seconds?
Secondly, the page contains bare minimum, literally just one input box. Do I still need to include the html head and body?
You don't need Javascript for this simple function. Add in the page header:
<meta http-equiv="Refresh" content="300">
300 is the number of seconds in this example.
To reload the page after 5 seconds (5000 milliseconds) using JavaScript, add the following to the bottom of the page:
<script type="text/javascript">
setTimeout(function () { location.reload(true); }, 5000);
</script>
As Greg Hewgill notes, you can also accomplish this with the meta refresh tag:
<meta http-equiv="Refresh" content="5">
Strictly speaking, you do still need <html> and <body> tags. Some browsers may render the page correctly without them, but your are safest to include them.
use a timer: http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/
and usee ajax to reload if it is dynamic
To your second question, ye you definitely do!!
Toy your first question check this out:
http://www.javascriptkit.com/script/script2/autofresh.shtml
Or this to do it without javascript:
http://webdesign.about.com/od/metataglibraries/a/aa080300a.htm
It does what you asked and is very easy to configure!

Tracking outgoing links with Javascript and PHP

I have tried it using jQuery but it is not working.
<script>
$("a").click(function () {
$.post("http://www.example.com/trackol.php", {result: "click"
}, "html");
});
</script>
out
To get the best results you should change two things in your approach
Use onmousedown instead of click - this way you get a few extra milliseconds to complete the tracking request, otherwise the browser might not start the connection to your tracker at all as it is already navigating away from the original page. The downside is that you might get some false-positive counts, since the clicking user might not finish the click (eg. keeps the mousebutton down and moves the cursor away from the link) but overall it's a sacrifice you should be willing to make - considering the better quality of tracking.
Instead of an Ajax call ($.post('...')) use an image pre-fetcher (new Image().src='...'). The fact that the tracker is not an image is not relevant in this case because you don't want to use the resulting "image" anyway, you just want to make a request to the server. Ajax call is a two way connection so it takes a bit more time and might fail if the browser is already navigating away but the image pre-fetcher just sends the request to the server and it doesn't really matter if you get something back or not.
So the solution would be something like this:
<script>
$(document).ready(function() {
$("a").mousedown(function (){
new Image().src= "http://www.example.com/trackol.php?result=click";
});
});
</script>
out
Instead of using JavaScript to call a php tracking script, you could just link to your tracking script directly and have it in turn redirect the response to the ultimate destination, something like this:
out
and in the PHP script, after you do your tracking stuff:
...
header("Location: $dest");
As mentioned, the problem is you’re not running the script after the DOM has loaded. You can fix this by wrapping your jQuery script inside $(function() { }, like so:
This works:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Tracking outgoing links with JavaScript and PHP</title>
</head>
<body>
<p>Test link to Google</p>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script>
$(function() {
$('a').click(function() {
$.post('http://www.example.com/trackol.php', { result: 'click' }, 'html');
});
});
</script>
</body>
</html>
See it in action here: http://jsbin.com/imomo3

Categories