Preload all images in a directory using jQuery - javascript

I want to preload all images in a directory called img,and that directory also contains sub directory called ui_images.
I know how to preload specific images by putting their names in an array and doing the preloading work, but i want to know how to tell the script to search dynamically for all images in that directory img and img/ui_images?
Here's my code :
var preloadImg = function(imgArr){
$.each(imgArr, function(index,value){
$("<img/>")[0].src = value;
});
}
var arrimg = ['img/check.png','img/add_sub.png'];
preloadImg(arrimg);

There is no generally available facility for doing a directory listing in http. The options I can think of are:
Name your images in a predictable fashion like (img001, img002, etc...) and then you can load images until you get an error.
Name your images in a predictable fashion like (img001, img002, etc...) and then code in one numeric limit value into your web page for how many there are.
Create an ajax call (on both client and server) that will give you a list of image names to preload.
Have your server embed an array of image names into the page so you know what to preload.

I was looking at improving the performance on one of my sites and looked into this. My solution seems to work and I haven't seen it anywhere else yet.
Its a two step approach using jquery and php
// Preload images via jquery .load and delete once their cached via the callback
<div id="preload"></div>
$('#preload').load('preload.php', function() {
$('#preload').remove();
});
// preload.php below - loop through the image folder and insert the images into a hidden div
<div style="display:none">
<?php
$dirf = 'images';
$dir = scandir($dirf);
foreach ($dir as $file) {
if (($file != '..') && ($file != '.')) {
echo "<img src='images/$file' />";
}
}
?>
</div>
This worked in Firefox but feel free to critique or improve

Related

How can I list the files on an FTP from a (stand-alone) .html file?

I am developing a self-contained (stand-alone) HTML form.
In one part of the form, I would like to make it possible to select the name of a file that is on an FTP.
In my .html file, I am therefore trying to find a way to list the names of all the files on an FTP.
Based on what I have read so far, it seems there is no conventional way to do this as accessing an FTP should be done using server-side languages such as PHP for example, as explained here or here.
So I am trying to see if I can do this in a different way.
An idea I had is to copy the content displayed on an FTP page into a JavaScript variable, as shown here.
I am using as an example the FTP from the German Climate Data Center because it is an open access FTP that doesn’t require any login information.
In the code below, I am trying to place the content displayed on a page of that FTP into a <div> inside my .html file, and then display the <div> using console.log.
However, as shown below, I haven’t been successful so far:
function start_FTP() {
var server = "ftp-cdc.dwd.de/test/weather/radar/sites/sweep_vol_z/mem/hdf5/filter_polarimetric/";
var ftpsite = "ftp://" + server;
window.open(ftpsite);
document.getElementById("FTP_content").innerHTML = '<object type="text/html" data=ftpsite ></object>';
console.log(FTP_content);
}
<h2> List FTP content using JavaScript </h2>
<button type="button" id="FTP_button" name="FTP_button" onclick="start_FTP()">Select File Name</button>
<div id="FTP_content"> </div>
The <div> does not contain any useful information.
This is just a step towards my final goal, which is in fact to create a new window that lists the contents on the FTP page with a checkbox next to each line, such that the user can select the name of the file he needs.
Is this possible using JavaScript?
If not, are there any other “tricks” that can be used to reach this goal using JavaScript only?
EDIT
The issue I have is that I can not do anything on the server-side (unfortunately).
I need to develop a stand-alone HTML form that needs to be sent to lots of different end users, who need to be able to use this form “as is”.
These end users (clients) need to be able to select the name of a file from a list of files that can be seen on an open access FTP.
So I am trying to copy the names of the files that are visible on an open access FTP page, and add a check box in front of each file name, such that the end user can select the check box that corresponds to the name of the file (that will be used for further data-processing).
Do you Mean something like this?
It requires Jquery.
Javascript,css and then the HTML.
function handleFileSelect (e) {
var files = e.target.files;
if (files.length < 1) {
alert('select a file...');
return;
}
var file = files[0];
var reader = new FileReader();
reader.onload = onFileLoaded;
reader.readAsDataURL(file);
}
function onFileLoaded (e) {
var match = /^data:(.*);base64,(.*)$/.exec(e.target.result);
if (match == null) {
throw 'Could not parse result'; // should not happen
}
var mimeType = match[1];
var content = match[2];
alert(mimeType);
alert(content);
}
$(function () {
$('#import-pfx-button').click(function(e) {
$('#file-input').click();
});
$('#file-input').change(handleFileSelect);
});
#file-input {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="import-pfx-button">Browse...</button>
<input type="file" id="file-input" />
<output id="list"></output>

How to pass a responsive DIV size to PHP?

I've been trying to pass an specific Div's height and width to a PHP code, the problem is, the page is supposed to be responsive, with div height and width changing accordingly.
How can I pass these values dynamically?
<?php
/* Configuration Start */
$thumb_directory = 'img/thumbs';
$orig_directory = 'img/original';
$stage_width=600; // How big is the area the images are scattered on
$stage_height=400;
/* Configuration end */
$allowed_types=array('jpg','jpeg','gif','png');
$file_parts=array();
$ext='';
$title='';
$i=0;
/* Opening the thumbnail directory and looping through all the thumbs: */
$dir_handle = #opendir($thumb_directory) or
die("There is an error with your image directory!");
$i=1;
while ($file = readdir($dir_handle))
{
/* Skipping the system files: */
if($file=='.' || $file == '..') continue;
$file_parts = explode('.',$file);
$ext = strtolower(array_pop($file_parts));
/* Using the file name (withouth the extension) as a image title: */
$title = implode('.',$file_parts);
$title = htmlspecialchars($title);
/* If the file extension is allowed: */
if(in_array($ext,$allowed_types))
{
/* Generating random values for the position and rotation: */
$left=rand(0,$stage_width);
$top=rand(0,400);
$rot = rand(-40,40);
/* Outputting each image: */
echo '
<div id="pic-'.($i++).'" class="pic" style="top:'.$top.'px;left:'.$left.'px;background:url('.$thumb_directory.'/'.$file.') no-repeat 50% 50%; -moz-transform:rotate('.$rot.'deg); -webkit-transform:rotate('.$rot.'deg);">
<a class="fancybox" rel="fncbx" href="'.$orig_directory.'/'.$file.'" target="_blank">'.$title.'</a>
</div>';
}
}
The specific variables are $stage_width and $stage_height, those are supposed to receive the div size, but as you can see, right now, all I can do is to set a static value in them.
Is there anyway to do that? Either with JS, PHP or something else entirely?
Take a moment to learn about AJAX.
AJAX stands for Asynchronous JavaScript And XML. In a nutshell, it is the use of the XMLHttpRequest object to communicate with servers. It can send and receive information in various formats, including JSON, XML, HTML, and text files. AJAX’s most appealing characteristic is its "asynchronous" nature, which means it can communicate with the server, exchange data, and update the page without having to refresh the page.
In this case, you would:
Compute the actual div size on the client using javascript
Send an ajax request to the server with those values
Create the div markdown with the correct values
Replace the div on the client with the markdown received from the asynchronous request.
This, however, is a bit clunky. You could be better off simply doing all that transformation on the client, using JavaScript:
Generate the markdown with PHP (like you are doing) but without the top and left styling
On client side, after the page loads (the 'DOMContentLoaded' event in JavaScript) compute the actual sizes and transform the divs accordingly.
window.addEventListenet('DOMContentLoaded', () => {
// get the div real size with getComputedStyle or something like that
// replace the div's style with correct calculations
})

PHP, JavaScript - Is it right to detect screen-width by redirecting header

I am using the following JavaScript to detect the screen-width and use it as a constant across my template files through conditional statements to display / not-display portions of my site. While it has nothing much to do with my questions, but just in case... Yes I am using WordPress. Also I am already using mobiledetect PHP Library.
function getLayoutWidth() {
if (isset($_GET['width'])) {
define( "SCREEN_WIDTH", $_GET['width']);
} else {
echo "<script language='javascript'>\n";
echo " location.href=\"${_SERVER['SCRIPT_NAME']}?${_SERVER['QUERY_STRING']}"
. "&width=\" + screen.width;\n";
echo "</script>\n";
exit();
}
}
Important :
Other techniques are like...... Let's assume if my site is 2MB in size, it will still load 2MB of content and then hide 1.5MB of it on mobile devices by using CSS properties like display:none; Whereas I don't want that template part to load itself, thus not needing to hide anything.
I am not looking to load an entire JavaScript library like jQuery or so to do this because location.href=\"${_SERVER['SCRIPT_NAME']}?${_SERVER['QUERY_STRING']}". "&width=\" + screen.width; is the only JavaScript in my entire site. Rest everything is pure PHP, HTML and CSS based. I even disabled jQuery of WordPress in the front-end template.
UPDATE :
Since some friends did not get my point although I mentioned clearly that I don't want to load the content into DOM at all, I am giving a bit more clarity here.....
For Example --- #1200px I want only 1 Sidebar to be displayed. #1600px I want 2 Sidebars to be displayed and over 1600px I want 3 Sidebars to be displayed. Please don't suggest Media Queries solutions as I already know it and that is exactly what I don't want to do. I want to avoid loading the content into DOM. Kindly let focus be only and only on questions asked. Also please don't post suggestions as answers. Let others with proper answers do it. Kindly post suggestions in Comment section.
My questions :
Is this a good / correct way to do from SEO stand point? If not why?
My URL is displayed as example.com/my-product-category/my-product-name/?width=1440 How to remove /?width=1343 and display just example.com/my-product-category/my-product-name part?
Simple answer, no, it is not good from a SEO standpoint. Or any other standpoint. Crawlers such as Googles are designed to completely ignore all hidden elements and thus you will lose big time SEO ranking if your content isnt getting fully crawled, and crawlers crawl each site multiple times masquerading as mobile devices to check if the site is mobile friendly as well.
http://www.seonick.net/responsive-design-seo/
Not to mention the trouble of calculating your arbitrary cutoff point of .5mb serves no purpose if the content is merely hidden (since its all getting sent anyway thus saving no bandwidth).
You need to do this in pure CSS using media queries, it is the most compatible way and allows for a fluid design (changes on the go as the window resizes.
<link rel="stylesheet" media="(max-width: 700px)" href="mobile.css">
<link rel="stylesheet" media="(min-width: 700px)" href="full.css">
That will use one css file if the window is smaller than 700px and the other if it is over.
Another of my more favorite methods is to use the http://mobiledetect.net/ class. Its small and fast, more accurate and better flexibility. Load that class then just add classes to your body element depending on the visitors browser
<body class="<?PHP if ($detect->isMobile() && !$detect->isTablet()) echo " .phone";?>">
Then style by targeting classes inside body.phone. This method also ensures you know if the browser is mobile BEFORE the DOM starts to process, meaning you can serve compressed versions of images through some simple logic rather than having CSS swap them out or just resize them or omit entire parts of the markup from being sent to the user at all ensure bandwidth is only used for parts of the DOM relevant to the users device.
<body>
This is normal content and will be visible to all devices
<?PHP if (!$detect->isMobile()) { ?>
This content will only be visible to desktop users, in fact it wont even be transmitted to mobile users thus making it NOT in the DOM
<?PHP } ?>
</body>
To set a cookie in javascript
function Cookies(){};
Cookies.prototype.save=function(name,value,days){
if( days ) {
var date = new Date();
date.setTime( date.getTime()+( days*24*60*60*1000 ) );
var expires = "; expires="+date.toGMTString();
var dom = "; domain="+document.domain;
} else { expires = ""; }
var path = "; path=/";
var tmp=[];
if( typeof( value )=='object' ) {
for( p in value ) tmp.push( p+'='+value[ p ] );
value=tmp.join(';');
}
document.cookie = name+"="+value+expires+path;
};
Cookies.prototype.read=function(name){
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for( var i=0; i < ca.length;i++ ) {
var c = ca[i];
while( c.charAt(0)==' ') c = c.substring(1,c.length);
if( c.indexOf( nameEQ ) == 0 ) return c.substring( nameEQ.length, c.length );
}
return null;
};
Cookies.prototype.erase=function(name){
this.save( name, "", -1 );
};
var cn='jsdim';
var ckie=new Cookies;
ckie.save( cn, JSON.stringify({ width:screen.availWidth, height:screen.availHeight, colour:screen.colorDepth, depth:screen.pixelDepth }), 1 );
In PHP
<?php
if( isset( $_COOKIE['jsdim'] ) ){
$json=json_decode( $_COOKIE['jsdim'] );
if( !defined('SCREEN_WIDTH') ) define( 'SCREEN_WIDTH', $json->width );
if( !defined('SCREEN_HEIGHT') ) define( 'SCREEN_HEIGHT', $json->height );
if( !defined('SCREEN_COLOUR_DEPTH') ) define( 'SCREEN_COLOUR_DEPTH', $json->colour );
if( !defined('SCREEN_PIXEL_DEPTH') ) define( 'SCREEN_PIXEL_DEPTH', $json->depth );
}
?>
I do not think, that screen size/resolution is really what you want to adjust your view templates for mobile devices. Actually you want to know what plattform/device someone is using, think about Nexus 7, which has 1920 × 1200 or Sony Xperia Z5 with 2160 x 3840px.
I would look at user-agent and HTTP headers for the server side code, there are already good libraries for that: e.g. mobiledetect. For the client side the best practice is to use CSS3 Media Queries: Media Queries for Standard Devices
You can retire the $_GET of the URL by the htaccess, I'm using RewriteRule.
Options +FollowSymLinks
RewriteRule ^folder/file.php$ folder/file.php?g=2
#if you want to remove php file extension, don't keep the .php before the $
To remove all php files extension: php.net.
Edit: this is for who doesn't use Wordpress
You can use this plugin:
https://wordpress.org/plugins/mobble/
It adds an is_mobile()-feature.
In your theme you can now use is_mobile() instead of $_GET['width'] > ...
This way you don't need a ?width= in your $_GET

JQuery seems to be blocked by something else

JQuery seems to be blocked
Hello there, I've been confronting this problem for several days, I just can't find a way to get this fixed, or around it.
What I want to do is simple, I want to read out every sub-folder of a big Project folder. Then assign a thumbnail image and a figcapture to this folder. With a simple for loop, php builds this for me. Everything works perfect and quick. The only thing is that the jquery won't respond. Even though I have created various menus with this technique. As you can see in my code, in the "script" tags, I have the jquery code which doesn't seem to work.
I don't know wheter php puts in a space somewhere or I just looked too long at this code for seing the error.
I appreciate any help.
<?php
/*Because of the "ease of use" aspect of this site, I prefered to write it completely in PHP,
advantage of that:
Images are loaded directly out of the folder, so I can just drag and drop something onto the server without having to write aditional code.
As you see, it can save a lot of time.*/
echo "<h1>Referenzen</h1><br>";
$projects = scandir('../src/sub/credentials'); //The credentials directory is being scanned and converted into an array.
$projectsSize = count($projects); //$size is being created. It counts the number of objects in the array which has been created above.
$projectsCaptions = file('../src/sub/captionsOfCredentials.txt'); //Edit the name of the figcaption in the "captionsOfCredentials.txt".
for($i = 2; $i < $projectsSize; $i++){ /*Simple "for" loop, that creates $i with the size of two, because PHP is 0-index based and has the "dot" and the "dotdot" folder. The loop stops at the end of the array($size).*/
echo '<a href="index.php#PRJ'.trim($projectsCaptions[$i]).'" class="ID'.trim($projectsCaptions[$i]).'">
<div class="projectFolder">
<img src="src/sub/credentialsThumb/project_00'.$i.'.jpg" width="100%" />
<figcaption>'
.$projectsCaptions[$i].
'</figcaption>
</div>
</a>';
/*Project folder level starts here.*/
$images = scandir('../src/sub/credentials/project_00'.$i);
$imagesSize = count($images);
for($k = 3; $k < $imagesSize; $k++){
$tempID = ('ID'.trim($projectsCaptions[$i]).'.php'); //$tempID is the entire file name including the .php part.
$handle = fopen($tempID, "a") or die ('Unable to open '.$tempID.' , please contact admin A.S.A.P..');
$imagesCode = 'test';
fwrite($handle, $imagesCode);
}
//end second for-loop
echo "
<script>
$(document).ready(function () {
$('#ID".$projectsCaptions[$i]."').click(function () {
$('#mainContent').load('de-DE/".$tempID."');
});
});
</script>";
}
//end first for-loop
?>
You're selecting an element by id when you need to use class. Change the JS block to this:
$(document).ready(function () {
// Note ".ID" not "#ID"
$('.ID".$projectsCaptions[$i]."').click(function () {
$('#mainContent').load('de-DE/".$tempID."');
});
});
UPDATE
It seems like you've also got an illegal character in $projectsCaptions[$i]. It's most likely a newline character. Try wrapping the above reference above in trim():
$('.ID" . trim($projectsCaptions[$i]) . "').click(function () {

Change image src without refreshing from mysql database

I am a bit of a pickle right now: I have an image displayed on my website, which has an src from a mysql server, it looks like this:
echo '<img src = "'.$sourceVariableFromDatabase.'" class = "profileImage" id = "profilePicture" />';
Also on my site, is a function that changes the database, and hence the value of $sourceVariableFromDatabase. However, the image won't update until the page is refreshed, but I would like it to display the new image src from the databse without refreshing.
I know this can be done through jQuery, but am unsure as to how to get the value from a database, as Javascript is not a server side, like javascript, and as far as I know cannot access databases in mysql.
How can I achieve this in Javascript/jquery.
Thanks, I have tried to be as clear as possible, and apologise for any waffle.
JQuery can be used to call a URL that returns data (e.g. HTML, JSON, text, etc). How that URL returns data can be however you want (PHP+MySQL, etc). Once JQuery receives the response, it can then update the img tag.
Here is a simple example:
Example HTML
<img id="profilePicture" src="(your source from db1)" />
Example JQuery on HTML page
function update_image(db)
{
// get new image src
$.get('some/url/to/get/new/src', {db: db}, function(response){
// update the img src
$('#profilePicture').attr('src', response);
});
}
Example page (/some/url/to/get/new/src):
<?php
// get request data
$db = $_GET['db'];
// get img src
$src = some_function_to_get_src($db);
// output src
echo $src;
$.get('/pathToCode', function(imagePath){
$('#profilePicture').attr('src', imagePath);
});
The file at /pathToCode would need to query the database and echo the path to the image. Just add this code to the end of your function that changes the database.

Categories

Resources