I want to load the image after the image is completely loaded or downloaded in the browser.
I dont want to display the image while it is being downloaded. Rather I would like to display a lower quality version of that image until the high quality images is loaded in the background, and when the image is completly loaded in the background, I want to replace the lower quality image with that image.
I have two images, say
$LQimage = "LQabc.jpg";
$HQimg = "HQabc.jpg";
How can I make it work?
EDIT
With the answer posted by #codebox, this code worked.. thanks :)
<html>
<head>
<script type="text/javascript">
function load(){
var img = new Image();
var imgUrl = 'HQabc.jpg';
img.onload = function(){
// this gets run once the image has finished downloading
document.getElementById('pp').src = imgUrl;
}
img.src = imgUrl; // this causes the image to get downloaded in the background
}
</script>
</head>
<body onload="load()">
<img id="pp" src="LQabc.jpg" width=600/>
</body>
</html>
This should do it:
function preLoadImage(){
var img = new Image();
var imgUrl = 'HQabc.jpg';
img.onload = function(){
// this gets run once the image has finished downloading
document.getElementById('idOfImgElement').src = imgUrl;
}
img.src = imgUrl; // this causes the image to get downloaded in the background
}
If you run this function once the page has loaded it should work:
<body onload="preLoadImage()">
Related
i am displaying a gif image on my wordpress site - when i refresh the page the gif is being cached at the final frame. I would like to make it so everytime the page is refreshed the gif restarts from the beginning. is their any code (php) i could add to the functions.php file in order for this to take place.
Thanks.
Tried a few different options on stack overflow such as:
<img id="gif" src=""/>
<script>document.getElementById('gif').src="path_to_picture.gif?a="+Math.random()</script>
and
var src = 'http://i.imgur.com/JfkmXjG.gif';
$(document).ready(function(){
var $img = $('img');
$('#target').toggle(
function(){
var timeout = 0; // no delay
$img.show();
setTimeout(function() {
$img.attr('src', src);
}, timeout);
},
function(){
$img.hide();
}
);
});
I'm trying to load a pdf from external server and now I'm getting this error in console.
XMLHttpRequest cannot load
https://mobile.switchitapp.com/uploads/pdf/userGuide.pdf. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://appsdata2.cloudapp.net' is therefore not
allowed access.
How to get rid of this error? I have tried a lot but nothing has worked for me till now please help me out
thanks :)
here is my code
<!DOCTYPE html>
<html>
<head>
<title>PDF.js Learning</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/1.8.472/pdf.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/1.8.472/pdf.worker.js"></script>
<script>
// URL of PDF document
var url = "https://mobile.switchitapp.com/uploads/pdf/userGuide.pdf";
// Asynchronous download PDF
PDFJS.getDocument(url)
.then(function(pdf) {
return pdf.getPage(1);
})
.then(function(page) {
// Set scale (zoom) level
var scale = 1.5;
// Get viewport (dimensions)
var viewport = page.getViewport(scale);
// Get canvas#the-canvas
var canvas = document.getElementById('the-canvas');
// Fetch canvas' 2d context
var context = canvas.getContext('2d');
// Set dimensions to Canvas
canvas.height = viewport.height;
canvas.width = viewport.width;
// Prepare object needed by render method
var renderContext = {
canvasContext: context,
viewport: viewport
};
// Render PDF page
page.render(renderContext);
});
</script>
</head>
<body>
<canvas id="the-canvas"></canvas>
</body>
</html>
Try var url = "https://cors-anywhere.herokuapp.com/https://mobile.switchitapp.com/uploads/pdf/userGuide.pdf"
doesn't work either also
The suggested solution is the comment shall work. Please see:
// URL of PDF document
var url = "https://cors-anywhere.herokuapp.com/" +
"https://mobile.switchitapp.com/uploads/pdf/userGuide.pdf";
// Asynchronous download PDF
PDFJS.getDocument(url)
.then(function(pdf) {
return pdf.getPage(1);
})
.then(function(page) {
// Set scale (zoom) level
var scale = 1.5;
// Get viewport (dimensions)
var viewport = page.getViewport(scale);
// Get canvas#the-canvas
var canvas = document.getElementById('the-canvas');
// Fetch canvas' 2d context
var context = canvas.getContext('2d');
// Set dimensions to Canvas
canvas.height = viewport.height;
canvas.width = viewport.width;
// Prepare object needed by render method
var renderContext = {
canvasContext: context,
viewport: viewport
};
// Render PDF page
page.render(renderContext);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/1.8.472/pdf.js"></script>
<canvas id="the-canvas"></canvas>
Enabling CORS on localhost is no different from enabling on any remote server. See https://enable-cors.org/server.html
Your problem that you cannot do that for remote server, and you really need to enable CORS there instead of localhost. You question is somewhat invalid.
I am looking to create sound buttons.
Have used the answer here:
Buttons click Sounds
and implemented it so that the buttons are divs and created dynamically from a MySQL DB.
Does anyone know how to preload that list of sounds on page load?
Also, I want to apply a CSS class to the div when clicked and then when the audio finishes, want it to switch back to the original CSS class.
This is what I have tried. The sounds play correctly but the onended fuction does not fire.
<script type='text/javascript'>
$(window).load(function(){
var baseUrl = "http://[URL HERE]";
var audio = [<?php echo $audiostring; ?>];
$('div.ci').click(function() {
var i = $(this).attr('id').substring(1);
mySound = new Audio(baseUrl + audio[i-1]).play();
mySound.onended = function() {
alert("The audio has ended");};
});
});
</script>
If you are using HTML5 audio you can do something like the following:
mySound.addEventListener("ended", function()
{
alert("The audio has ended");
});
Edit:
Try changing the way you create the audio tag, as referenced here.
$('div.ci').click(function() {
var i = $(this).attr('id').substring(1);
mySound = $(document.createElement('audio'));
mySound.src = baseUrl + audio[i-1];
mySound.play();
mySound.addEventListener("ended", function()
{
alert("The audio has ended");
});
});
<audio> and new Audio() should be the same but it doesn't look
like that is the case in practice. Whenever I need to create an audio
object in JavaScript I actually just create an element like
this:
The ended event is created based on .currentTime attribute. event-media-ended
the canplaythrough event was used to knowing when the browser has finished downloading the audio file and we can play
code complete use closest
<style type="text/css">
body{background: #aaa;color:#fff;}
div
{
width: 100px;
height: 100px;
background: #dda;
}
</style>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div >
</div>
<div >
</div>
<div >
</div>
<script type="text/javascript">
$(window).load(function(){
var audioFiles = [
"http://www.soundjay.com/button/beep-01a.mp3",
"http://www.soundjay.com/button/beep-02.mp3",
"http://www.soundjay.com/button/beep-03.mp3",
"http://www.soundjay.com/button/beep-05.mp3"
];
function Preload(url) {
var audio = new Audio();
// once this file loads, it will call loadedAudio()
// the file will be kept by the browser as cache
audio.addEventListener('canplaythrough', loadedAudio, false);
audio.src = url;
}
var loaded = 0;
function loadedAudio() {
// this will be called every time an audio file is loaded
// we keep track of the loaded files vs the requested files
loaded++;
if (loaded == audioFiles.length){
// all have loaded
init();
}
}
var player = document.createElement('audio');
function playAudio(index) {
player.src = audioFiles[index];
player.play();
}
function init() {
$('div').click(function(event) {
$(this).css('background', 'blue');
playAudio(Math.floor(Math.random()*audioFiles.length));
player.addEventListener("ended", function(){
player.currentTime = 0;
$(event.target).closest('div').css('background', '#dda');
});
});
}
// We begin to upload files array
for (var i in audioFiles) {
Preload(audioFiles[i]);
}
});
</script>
I'm having trouble getting the dimensions of a series of images that are loading via PHP.
<?
$Ldir="imgs/liveGallery/"; // Directory where files are stored
if ($Lhandle = opendir($Ldir)) {
while (false !== ($Lfile = readdir($Lhandle))) {
if ($Lfile != "." && $Lfile != "..") $Lthefiles[] = $Lfile;
}
closedir($Lhandle);
}
sort($Lthefiles);
for ($Li=0;$Li<count($Lthefiles);$Li++) { ?>
<a href="<?php echo $Ldir.$Lthefiles[$Li]; ?>" class="ilightbox">
<div class="adj">
<img src="<?php echo $Ldir.$Lthefiles[$Li]; ?>" class="percent">
</div>
</a>
<?php }
?>
In the above code PHP is doing its job loading all the images from a nearby directory. The .adj class is formatting the <div> into a square and floating them all to the left so they tile the screen. It's also hiding the overflow so that no matter the dimensions all you see is a square.
My issue comes when trying to read the widths and heights of the images that are being loaded into that <div>. I want to have the image fit at a width or height of 100% depending on which is proportional to fill the square. Here's the jquery code I thought should work.
$(window).load(function() {
$(".adj").each(function() {
var $this = $(this);
var imageWidth = $this.children("img").attr("width");
var imageHeight = $this.children("img").attr("height");
if (imageWidth < imageHeight){
$this.addClass("aW");
} else if (imageWidth > imageHeight) {
$this.addClass("aH");
}
});
});
I don't seem to be capturing an image width or height at all, with what I wrote above.
I'm using fullpage.js and ilightbox.js which may be messing with my code, but I doubt it. I've also tried putting a modified version of this code inside the PHP for loop (without the jquery each function) and that doesn't work either. HELP!
Here's a link for you.
You can try somethig like
$(window).load(function() {
$(".adj").each(function () {
var $this = $(this);
var img = new Image();
//Set Image source
img.src = $this.children("img").attr("src");
//Wait for image to be loaded.
//Event will fire when image is loaded
img.onload = function () {
//Get Height and width
var imageWidth = img.width;
var imageHeight = img.height;
if (imageWidth < imageHeight) {
$this.addClass("aW");
} else if (imageWidth > imageHeight) {
$this.addClass("aH");
}
};
});
});
Note: I am not sure, this is a best practice
You have set the width and height in the css styling and not inline as attributes,
So attributes width and height are empty
$this.children("img").attr("width"); // .attr would not work
Should be
$this.children("img").css("width"); // .css is the method
And
$(window).load(function() {
$(".adj").each(function() {
var $this = $(this);
// when your referring same img multiple times, grab it in a variable
var image = $this.children("img");
var imgWidth = image.width(); // or image.css("width")
var imageHeight = image.height(); // or image.css("height")
if (imageWidth < imageHeight){
$this.addClass("aW");
} else if (imageWidth > imageHeight) {
$this.addClass("aH");
}
});
});
note .css() gives in the px'.
Example 100px even though you set the values in pt or em etc. After seeing your code since your comparing the values I would suggest .width() and .height() as they return integer values and easy to compare
jQuery documentation
Note that .width() will always return the content width, regardless of the value of the CSS box-sizing property. As of jQuery 1.8, this may require retrieving the CSS width plus box-sizing property and then subtracting any potential border and padding on each element when the element has box-sizing: border-box. To avoid this penalty, use .css( "width" ) rather than .width()
Gif will only resize after the gif is fully loaded. How do I make the gif resized whilst even loading?
I use multiple gifs so they come in different sizes so I can not just do the usual 100% height and width, I want to keep the aspects correct.
The script I use to resize the gif
<script>
function resizeToMax(id){
myImage = new Image()
var img = document.getElementById(id);
myImage.src = img.src;
if(myImage.width / document.body.clientWidth > myImage.height / document.body.clientHeight){
img.style.width = "100%";
} else {
img.style.height = "100%";
}
}
</script>
The php to display the image
<?php
echo '<img id="image" onload="resizeToMax(this.id)" src="gifs/' . $myTokens[1] . '/' . $myTokens[2] . '.gif">';
?>
One thing you may be able to do is have the image hidden until it is loaded (add a CSS class for example), and then in your resizeToMax function, remove the CSS class that is hiding the image.
The onload events fire only when image has finished loading.
In the meanwhile, you could play with the css width and / or height properties, or even max-width and max-height.
The risk is that you don't know the image proportions yet, so the image may looks distorted ehile loading.
IMHO the best solution is to replace the image with a placeholder, load the image without displaying it (eg. outside of the screen window), then resizing and displaying it in the correct position removing the placeholder.
Use window.onload event to make sure your resizing will be effective at beginning of window loading.
<script>
window.onload = function() {
resizeToMax("image");
};
function resizeToMax(id){
myImage = new Image()
var img = document.getElementById(id);
myImage.src = img.src;
if(myImage.width / document.body.clientWidth > myImage.height / document.body.clientHeight){
img.style.width = "100%";
} else {
img.style.height = "100%";
}
document.getElementById(id).style.display = "block";
}
</script>
<?php
echo '<img id="image" style="display:none;" src="gifs/' . $myTokens[1] . '/' . $myTokens[2] . '.gif">';
?>
Or hide your image in css and show it in your function after your resizing.