Checking internet connection and change the content jquery/Javascript - javascript

This all happen on page load without click event call:-
Here is updated code, In this I am trying to check internet connection is on or not. If connection is off then 'link' on the will be automatically disable(non clickable) and it bgcolor changes to red.
And if connection is off 'link' will be automatically get enable(clickable) and it bgcolor changes to green. However I am missing some thing:
code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.1/jquery.mobile-1.4.1.min.css">
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.1/jquery.mobile-1.4.1.min.js"></script>
</head>
<style>
.connected{ background-color:green;}
.diconnected{background-color:red;}
#link1{
width: 100px;
height: 200px;
border: #0FF 1px solid;
}
</style>
<body>
<img src="images/network.png"> My status
</body>
<script>
window.onload=function() {
var tId = setInterval(function() {
document.getElementById("link1").disabled=!navigator.onLine;
},500);
if (navigator.onLine) {
$("link1").bind('click', true).addClass('connected').removeclass('diconnected');
} else {
$('.link1').unbind('click', false);
$(".link1").bind('click', true).addClass('diconnected').removeclass('diconnected');
}
}
</script>
</html>
Thanks for help.

you can write following just before closing body tag =>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.10.2.min.js"><\/script>')</script>
You can check reachability in following way
function hostReachable() {
// Handle IE and more capable browsers
var xhr = new ( window.ActiveXObject || XMLHttpRequest )( "Microsoft.XMLHTTP" );
var status;
// Open new request as a HEAD to the root hostname with a random param to bust the cache
xhr.open( "HEAD", "//" + window.location.hostname + "/?rand=" + Math.floor((1 + Math.random()) * 0x10000), false );
// Issue request and handle response
try {
xhr.send();
return ( xhr.status >= 200 && xhr.status < 300 || xhr.status === 304 );
} catch (error) {
return false;
}
}

First of all, if the user doesn't have an internet connection, how can you load in the jQuery library from an outside source? No internet = no web page.
Im going to guess that this is located on an intranet/network of some sort which is accessible without an internet connection, and if so, you will need to download the jQuery libraries yourself and upload them to the local server where they can be accessed by the network.
Second of all, you've referenced your ID's and Class's wrong.
$("link1") // Wrong
$("#link1") // Right
These will need to be amended so that jQuery knows its pointing at the right thing.

Related

window.matchMedia not works in iframe

I'm detecting device orientation using window.matchMedia. The following code works as intended - every orientation change is logged to console with correct value:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Test App</title>
</head>
<body>
<script type="application/javascript">
let isIframe= () => {
try {
return window.self !== window.top;
} catch (e) {
return true;
}
}
let onOrientationChange = () => {
const isLandscape = window.matchMedia("(orientation: landscape)").matches;
console.log("Event: " + (isIframe() ? "Iframe " : "") + "landscape:" + isLandscape);
}
let mediaQueryList = window.matchMedia("(orientation: landscape)");
console.log("Onload: " + (isIframe() ? "Iframe " : "") + "landscape:" + mediaQueryList.matches);
mediaQueryList.addListener(onOrientationChange);
</script>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root">Hello World in Iframe</div>
</body>
</html>
But when I run that page in iframe, callback registered using addListener is not fired. In iframe, I only get singular log line - Onload: Iframe landscape:true, regardless of the device orientation.
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root">Hello World</div>
<iframe id="game" src="iframeContent.html" frameborder="0" style="width: 960px; height: 600px;"></iframe>
</body>
I'm using addListener instead of addEventListener, because the second one function is not working on all Safari versions.
Tested on Safari 14 and on Dev Tools of Chrome and Firefox.
My question is - why addListener callback is not invoked in iframe.
Thank you.
If the iframe does not get it's size to change because it has fixed width and height, thus resize related events cannot be triggered inside it including MediaQueryList events regarding orientation.
You can do two things to get this working; you can make your iFrame width and height to be 100%, or you can let the media query detection code inside the main window and pass the orientation state using postMessage when it triggers a change event.
1) Changing iFrame size to 100% so it resizes when landscape/portrait orientation event triggers
In the main page, make the body full height and the iframe full width/height (using CSS).
body {
height: 100vh;
margin: 0;
}
iframe {
width: 100%;
height: 100%;
}
Live example that you can test: https://zikro.gr/dbg/so/65704468/
2) Media query detection on the main page and use postMessage to send a message to iFrame when orientation event triggers
index.html:
<iframe src="iframe.html"></iframe>
<script>
let iframe = document.querySelector('iframe');
let onOrientationChange = () => {
iframe.contentWindow.postMessage({
isLandscape: window.matchMedia("(orientation: landscape)").matches
}, '*');
}
iframe.addEventListener('load', onOrientationChange);
const mediaQueryList = window.matchMedia("(orientation: landscape)");
mediaQueryList.addListener(onOrientationChange);
</script>
iframe.html:
<script>
window.addEventListener("message", (event) => {
if (event.data.isLandscape) {
console.log('iFrame Landscape');
} else {
console.log('iFrame Portrait');
}
});
</script>
Live example that you can test: https://zikro.gr/dbg/so/65704468/pm/

Refresh a generated image

I am fairly unfamiliar with web technology.
A software that embeds a web server output a dynamic image
on the local host:
<img src="http://localhost:8000/" alt="http://localhost:8000/" class="transparent shrinkToFit" width="419" height="428">
This image is updated regularly by the software. I am trying to display this update in the web browser. There are several related posts and I have tried two solutions but so far with no luck.
Below are two attempts inspired by existing code and both fail. The problem seems to be related to some caching effect but I am not sure how to work around this.
Thanks in advance,
Trad
<html>
<head>
<title></title>
<meta content="">
<style></style>
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="rsc/stylesheet.css" type="text/css" charset="utf-8" />
<!-- <script>
setInterval(function() {
var url = "http://localhost:8000";//document.getElementById("url").value;
var xhr = new XMLHttpRequest();
xhr.open("GET",url);
xhr.responseType = "blob";
xhr.onreadystatechange = function() {
if (xhr.readyState == xhr.DONE && xhr.status == 200 ) { // xhr.readyState == xhr.DONE &&
// Render the downloaded image
var myblob = xhr.response;
var image = document.getElementById("ImageMusic");
image.addEventListener("load", function (evt) {
URL.revokeObjectURL(evt.target.src);
});
image.src = URL.createObjectURL(myblob);
}
}
xhr.send(null);
}, 100);
</script>
-->
<script>
setInterval(function() {
var myImageElement = document.getElementById('ImageMusic');
myImageElement.src = 'http://localhost:8000?rand=' + Math.random();
}, 100);
</script>
<script src="https://aframe.io/releases/0.3.0/aframe.min.js"></script>
</head>
<body>
<a-scene>
<a-assets>
<img id="ImageMusic" src="http://localhost:8000" />
</a-assets>
<a-image position="1 1 -4" width="4" height="4" src="#ImageMusic"></a-image>
</a-scene>
</body>
</html>
It is not possible to use a web page as an image or texture.
In the context of A-Frame, you cannot use I-Frames as an image or texture either, it is not possible in the browser.
Try using iframe
<iframe src="http://localhost:8000/">Your browser does not support the iframe HTML tag</iframe>
This should update automatically.
Alternatively, you can use the <embed src="http://localhost:8000/"></embed> tag. As long as you have a set pixel size for the images, (eg: 1080x720), you shouldn't have any problems with scrolling or stretched images.
CSS:
embed {
width:1080px;
height: 720px;
}

Video.js not working in Safari (CODE:4 MEDIA_ERR_SRC_NOT_SUPPORTED)

I am trying to use video.js to prevent fast-forward, but allow rewind, for mp4 videos on a Moodle site. It is working properly in Chrome and Opera, but when I try in Safari, I get the following error message:
VIDEOJS: (4)
"ERROR:"
"(CODE:4 MEDIA_ERR_SRC_NOT_SUPPORTED)"
"The media could not be loaded, either because the server or network failed or because the format is not supported."
I have seen a suggestion to change the Content-Type header to mp4, but for some reason, my iframe doesn't generate a head tag at all (only in Safari; in all other browsers, the iframe contains an html tag with both head and body). Also, it turns out, I am blocked from prepending a head tag to the iframe html. I tried throwing it into a meta tag instead, but this had no impact on the error message
The following is the script I'm using to prevent fast-forward:
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<link href="https://vjs.zencdn.net/5.0/video-js.min.css" rel="stylesheet">
<script src="https://vjs.zencdn.net/5.0/video.min.js"></script>
<script>
window.onload = function() {
if ($('iframe').length > 0) {
$('iframe').ready(function() {
if ($('iframe').contents().find('head').length === 0) {
console.log("*********************");
console.log("In the if!");
$('iframe').contents().find('html').prepend("<head><meta name='viewport' content='width=device-width' content-type='video/mp4'></head>");
$('iframe').contents().find('html').attr("content-type", "video/mp4");
console.log($('iframe').contents().find('head'));
console.log($('iframe').contents().find('html'));
}
var videoPlayer = $('iframe').contents().find('video')[0];
var cssLink = document.createElement("link")
cssLink.href = "https://vjs.zencdn.net/5.0/video-js.min.css";
cssLink.rel = "stylesheet";
cssLink.type = "text/css";
$('iframe').contents().find('head').append(cssLink);
videojs(videoPlayer, {}, function() {
var vjsPlayer = this;
$('iframe').contents().find('video').prop('controls', 'true');
$('iframe').contents().find('div .vjs-big-play-button').html('');
$('iframe').contents().find('div .vjs-control-bar').html('');
$('iframe').contents().find('div .vjs-caption-settings').html('');
var currentTime = 0;
vjsPlayer.on("seeking", function(event) {
if (currentTime < vjsPlayer.currentTime()) {
vjsPlayer.currentTime(currentTime);
}
});
vjsPlayer.on("seeked", function(event) {
if (currentTime < vjsPlayer.currentTime()) {
vjsPlayer.currentTime(currentTime);
}
});
setInterval(function() {
if (!vjsPlayer.paused()) {
currentTime = vjsPlayer.currentTime();
}
}, 1000);
});
});
}
}
</script>
My web server is Apache2.
Any advice on how to enable the Content-Type video/mp4 (or another way to resolve this error) would be greatly appreciated.
I'm also having trouble with the play/pause functions for the video in Firefox and Microsoft Edge. Please check out those questions if you have any ideas.
The same error i faced in my application. after few days of research i found that
safari can run only the H264 codec format for the videos . and MP3, AAC for the audio.
check the video format and the server response.
for reference: https://docs.videojs.com/tutorial-troubleshooting.html#problems-when-hosting-media

jquery not firing the error event on 403 when loading new src for img

I'm trying to make a page which includes a static Google map. When the page is resized I dynamically change the map. I have the following code in a function which is fired on page resize and periodically after a check that the sizes of elements on the page match :
if (imageDownloadEnabled) {
url = 'http://maps.googleapis.com/maps/api/staticmap?center=' + userLat + ',' + userLng + '&zoom=14&size=' + ((theWidth/2)|0) + 'x'+ ((theHeight/2)|0) + '&sensor=false&scale=2';
newImage = $('<img />');
console.log('Retrieving map from ' + url);
newImage.error( function() {
console.log("error loading image");
imageDownloadEnabled = false;
}).load(function(eventObject) {
console.log("done loading image");
console.dir(eventObject);
$('#maps-image').replaceWith(newImage);
newImage.attr('id', 'maps-image');
}).attr('src', url);
/**/
} else {
console.log('disabled');
}
When the google maps api overloads (happening at the moment because a bug of mine caused an infinite loop) I get a 403 error and a substitute image. The error event handler is not called though.
Is there any way around this? I'd like to make sure that in the event of a 403, the page stops requesting new images from Google.
Try using the complete callback function of .load and check the textStatus value
.load($url,function(responseText, textStatus, XMLHttpRequest) {
if(textStatus=="error") {
//do something
}
});
I don't think you need the load bit if you just want to know if an image failed to load, the below example works for me:
.error() is a shortcut for .bind('error', handler).
The preset src loads fine, once its loaded (documentready) jquery attempts to replace it with an invalid file and falls back to the google logo if it can't
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#foo-image").error(function(){
alert("error loading image, substituting...");
$(this).attr("src","http://www.google.co.uk/images/srpr/logo3w.png");
}).attr("src", "missing.png");
});
</script>
</head>
<body style="font-family:arial; font-weight:bold;">
<img id="foo-image" src="http://www.iskin.co.uk/wallpapers/imagecache/ipad/union_flag_wallpaper.jpg" />
</body>
</html>
This is what I came up with in the end, after looking around.
The problem is that Google is returning an image along with the 403 status, so the onload event is fired. So my code would load the 10px by 10px error image, regardless of the size of the div it sat in.
The trick was to use an in-memory Image(), load the url and check the size of the image in the onload event. If the image is too small, load the standin.
The code :
if (imageDownloadEnabled) {
url = 'http://maps.googleapis.com/maps/api/staticmap?center=' + userLat + ',' + userLng + '&zoom=14&size=' + ((rightWidth/2)|0) + 'x'+ ((rightHeight/2)|0) + '&sensor=false&scale=2';
oldMap = $('#maps-image');
var img = new Image();
img.onload = function() {
if(this.width < 100 || this.height <100) {
console.log('Google 403, loading standin');
/* disable image download */
imageDownloadEnabled = false;
oldMap.attr('src', standinUrl);
} else {
oldMap.attr('src', url);
}
}
img.onerror = function() {
console.log('Error, loading standin');
oldMap.attr('src', standinUrl);
}
img.src = url;
} else {
oldMap.attr('src', standinUrl);
}
In case it is not clear, below a certain browser size I get rid of the map, which is why I simply check for image size in the onload function.

Not able to load google map

I am trying to show the user's location obtained using geolocation API on google map.but the map is not loading.What am i doing wrong ?
$(document).ready(function(){
trackLocation()
})
//Track the user's location with high accuracy
function trackLocation(){
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(
successFunction,
errorFunction,
{enableHighAccuracy : true,
timeout:1000 * 10 * 100,
maximumAge:0
}
)
}
}
function successFunction(position){
plotMap(position)
}
function errorFunction(error){
alert(error)
}
function plotMap(position){
var location = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude)
alert('created locaction')
var plotOptions = {
center: location,
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
alert('created options')
var map = new google.maps.Map(document.getElementById('map_canvas'),plotOptions)
alert('created map')
}
and the html is
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="{{STATIC_URL}}jquery.min.js"></script>
<script type="text/javascript" src="{{STATIC_URL}}javascript_posted_above.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
</head>
<body>
Hi
<div id="map_canvas" style="width:100%; height:100%;"></div>
</body>
</html>
Take a look at this jsFiddle. The only differences between this and yours are the removal of the static js references and added the CSS. Without that CSS the map doesn't appear to display. I have never experienced this problem when using the Maps Api, perhaps I just added this CSS without thinking.
The CSS was taken from the HelloWorld tutorial on the docs.
here is my fiddle, I changed a few things:
First off all, I changed Alert to Console.log, which is important
since it is a non-obstructive way of logging, alert stops script
excecution and is not reliable.
I removed the google map script tag, and dynamically added it to the page in the document.ready handler, I also added a callback function "&callback=trackLocation", the JSON-P loaded script from Google will run the function with that name, when its executed.
I attached the function trackLocation(), directly to the window object, so it would be found by the script loaded from Google.
I changed the height of your map_canvas to 500px, instead of 100%, there seems to be an issue stretching a map. My first google search gave me: http://forum.jquery.com/topic/google-map-not-stretching-properly-when-width-set-to-100 you could do more research with that.
Good luck with your map!
Have you tried calling googlemap.js before your .js in the html?
I was loading the Google Maps API like this:
function mapsjsready()
{
// mapsjs ready!
}
$(document).ready( function() {
var mapsjs = document.createElement( 'script' );
mapsjs.type = "text/javascript";
mapsjs.async = true;
mapsjs.src = "https://maps.googleapis.com/maps/api/js?sensor=false";
mapsjs.id = "mapsjs";
mapsjs.onload = mapsjsready;
// Only for IE 6 and 7
mapsjs.onreadystatechange = function()
{
if( this.readyState == 'complete' )
{
mapsjsready();
}
}
document.body.appendChild( mapsjs );
});
But it suddenly stopped working.
I found that adding the callback parameter somehow solved the problem :
function mapsjsready()
{
// mapsjs ready!
}
function mapsjsloaded()
{
// mapsjs loaded!
}
$(document).ready( function() {
var mapsjs = document.createElement( 'script' );
mapsjs.type = "text/javascript";
mapsjs.async = true;
mapsjs.src = "https://maps.googleapis.com/maps/api/js?sensor=false&callback=mapsjsloaded";
mapsjs.id = "mapsjs";
mapsjs.onload = mapsjsready;
// Only for IE 6 and 7
mapsjs.onreadystatechange = function()
{
if( this.readyState == 'complete' )
{
mapsjsready();
}
}
document.body.appendChild( mapsjs );
});
I don't understand why, but adding the callback parameter solved my problem.

Categories

Resources