Google drawing Red rule using jquery - php

I am working on custom form builder for one of my clients where we have functionality like drag fields , resize, apply css like borders and align fields using jquery. i am done with dragging,resizing and css but one of the major requirement is to apply "google drawing red rule " as we have in google drawing.
i have attached a screencast video as well as screencast images to clarify what red rule is.
http://screencast.com/t/ow6s5zKt9P
http://screencast.com/t/e1SL26gFJT8v
http://screencast.com/t/QAJGB7PzEwB
http://screencast.com/t/OoM6BqAH
Video:
http://screencast.com/t/ORaqAVWX4XGu
As can be seen in the above screen casts when ever we drag/draw a field and overlap with other fields it highlights the vertical and horizontal center of the dragging field or the overlap field in Red color (hence the title red rule). it also highlights the borders of any field overlapping the other field or moving out of the canvas area. it also shows whether field can be inscribed inside in another field while dragging.
I am looking at some one who can guide me in correct direction to acchive this functionality. i need to apply this red rule effect other than drawing or any thing. please sugguest any possibilities.
Any help is greatly appreciated.

i got the solutuon.
you can check her http://jsfiddle.net/elin/A6CpP/
<div id="parent">
<div class="other-objects" style="left:0px;top:300px;background:#a00;"></div>
<div class="other-objects"></div>
<div class="other-objects" style="left:400px;top:20px;"></div>
<div class="objectx"></div>
<div class="objecty"></div>
</div>
$.ui.plugin.add("draggable", "smartguides", {
start: function(event, ui) {
var i = $(this).data("draggable"), o = i.options;
i.elements = [];
$(o.smartguides.constructor != String ? ( o.smartguides.items || ':data(draggable)' ) : o.smartguides).each(function() {
var $t = $(this); var $o = $t.offset();
if(this != i.element[0]) i.elements.push({
item: this,
width: $t.outerWidth(), height: $t.outerHeight(),
top: $o.top, left: $o.left
});
});
},
stop: function(event, ui) {
$(".objectx").css({"display":"none"});
$(".objecty").css({"display":"none"});
},
drag: function(event, ui) {
var inst = $(this).data("draggable"), o = inst.options;
var d = o.tolerance;
$(".objectx").css({"display":"none"});
$(".objecty").css({"display":"none"});
var x1 = ui.offset.left, x2 = x1 + inst.helperProportions.width,
y1 = ui.offset.top, y2 = y1 + inst.helperProportions.height,
xc = (x1 + x2) / 2, yc = (y1 + y2) / 2;
for (var i = inst.elements.length - 1; i >= 0; i--){
var l = inst.elements[i].left, r = l + inst.elements[i].width,
t = inst.elements[i].top, b = t + inst.elements[i].height,
hc = (l + r) / 2, vc = (t + b) / 2;
var ls = Math.abs(l - x2) <= d;
var rs = Math.abs(r - x1) <= d;
var ts = Math.abs(t - y2) <= d;
var bs = Math.abs(b - y1) <= d;
var hs = Math.abs(hc - xc) <= d;
var vs = Math.abs(vc - yc) <= d;
if(ls) {
ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l - inst.helperProportions.width }).left - inst.margins.left;
$(".objectx").css({"left":l-d-4,"display":"block"});
}
if(rs) {
ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r }).left - inst.margins.left;
$(".objectx").css({"left":r-d-4,"display":"block"});
}
if(ts) {
ui.position.top = inst._convertPositionTo("relative", { top: t - inst.helperProportions.height, left: 0 }).top - inst.margins.top;
$(".objecty").css({"top":t-d-4,"display":"block"});
}
if(bs) {
ui.position.top = inst._convertPositionTo("relative", { top: b, left: 0 }).top - inst.margins.top;
$(".objecty").css({"top":b-d-4,"display":"block"});
}
if(hs) {
ui.position.left = inst._convertPositionTo("relative", { top: 0, left: hc - inst.helperProportions.width/2 }).left - inst.margins.left;
$(".objectx").css({"left":hc-d-4,"display":"block"});
}
if(vs) {
ui.position.top = inst._convertPositionTo("relative", { top: vc - inst.helperProportions.height/2, left: 0 }).top - inst.margins.top;
$(".objecty").css({"top":vc-d-4,"display":"block"});
}
};
}
});
$('.other-objects').draggable({
containment: 'parent',
smartguides:".other-objects",
tolerance:5
});
#parent{
width:600px;
height:500px;
border:1px solid #000;
position:relative;
}
.other-objects{
background:#aaa;
width:100px;
height:100px;
display:block;
position:relative;
left:140px;
top:50px;
}
.objectx{
display:none;
//background:#fff;
width:0px;
height:100%;
position:absolute;
top:0px;
left:10px;
border-left: 2px solid red;
}
.objecty{
display:none;
//background:#fff;
width:100%;
height:0px;
position:absolute;
top:10px;
left:0px;
border-bottom: 2px solid red;
}

Related

How to enlarge a leaflet polygon box by 5%?

I create a square polygon by using the min and max values of the latitude and longitude of the furtherst points of my incoming data.
$poly = " $maxLng $maxLat , $minLng $maxLat , $minLng $minLat , $maxLng $minLat , $maxLng $maxLat ";
But this means that at least two markers are always the borders of this box. How can I push out the points and enlarge the overall size of the box by say 5% in all directions but I still need the lat/lon of each of those corners?
A small example of how to use the turfjs library and the transformScale method
const map = L.map('mapid').setView([52.308478623663355, 19.281005859375004], 6);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 18,
attribution: '© OpenStreetMap contributors'
}).addTo(map);
const test = [
[54.80068486732236, 18.292236328125004],
[53.89786522246521, 14.611816406250002],
[51.055207338584964, 15.281982421875002],
[49.57510247172322, 19.138183593750004],
[50.57626025689928, 23.642578125000004],
[52.214338608258224, 23.148193359375004],
[52.86912972768522, 23.741455078125],
[54.29729354239267, 22.928466796875004],
[54.29729354239267, 19.489746093750004],
[54.80068486732236, 18.292236328125004]
];
L.polygon(test, {
color: 'red'
}).addTo(map);
var poly = turf.polygon([test]);
var scaledPoly = turf.transformScale(poly, 1.05);
const {
coordinates
} = scaledPoly.geometry;
L.polygon(coordinates, {
color: 'white'
}).addTo(map);
* {
margin: 0;
padding: 0;
}
html,
body {
height: 100%;
}
body {
min-height: 100%;
}
#mapid {
width: 100%;
height: 100%;
}
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.6.0/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet#1.6.0/dist/leaflet.js"></script>
<script src="https://cdn.jsdelivr.net/npm/#turf/turf#5/turf.min.js"></script>
<div id="mapid"></div>

How to update a graph in D3.js when pressing a button?

I am working on a graph that shows the temperature, date and time. Until now everything is working pretty good, but in order to get the new values from my MySQL database in need to completely refresh my page.
I want to be able to update the graph without pressing the Refresh button.
This is the code:
<?php require($_SERVER['DOCUMENT_ROOT'] . '/assets/php/getTemp.php' ); ?>
<!DOCTYPE html>
<meta charset="utf-8">
<head>
<title>RPi</title>
</head>
<style>
div.tooltip {
position: absolute;
text-align: center;
width: 120px;
height: 28px;
padding: 3px;
font: 12px sans-serif;
background: lightgrey;
border: 0px;
border-radius: 8px;
pointer-events: none;
}
body { font: 14px Arial;}
path {
stroke: #FF8C00;
stroke-width: 3;
fill: none;
}
.axis path,
.axis line {
fill: none;
stroke: black;
stroke-width: 2;
shape-rendering: crispEdges;
}
.grid .tick {
stroke: grey;
stroke-opacity: 0.3;
shape-rendering: geometricPrecision;
}
.grid path {
stroke-width: 0;
}
</style>
<body>
<div id="option">
<input name="updateButton"
type="button"
value="Update"
onclick="updateData()"
/>
</div>
<!-- load the d3.js library -->
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var margin = {top: 30, right: 20, bottom: 30, left: 50},
width = 800 - margin.left - margin.right,
height = 270 - margin.top - margin.bottom;
var parseDate = d3.time.format("%Y-%m-%d %H:%M:%S").parse;
var formatTime = d3.time.format("%d-%m-%Y %H:%M:%S");
var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);
var xAxis = d3.svg.axis().scale(x)
.orient("bottom");
var yAxis = d3.svg.axis().scale(y)
.orient("left").ticks(5);
var valueline = d3.svg.line()
.interpolate("basis")
.x(function(d) { return x(d.datetime); })
.y(function(d) { return y(d.temperature); });
var div = d3.select("body").append("div")
.attr("class", "tooltip")
.style("opacity", 0);
var svg = d3.select("body")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
function make_x_axis() {
return d3.svg.axis()
.scale(x)
.orient("bottom")
.ticks(5)
}
function make_y_axis() {
return d3.svg.axis()
.scale(y)
.orient("left")
.ticks(5)
}
<?php echo "data=".$json_data.";" ?>
data.forEach(function(d) {
d.datetime = parseDate(d.datetime);
d.temperature = +d.temperature;
});
x.domain(d3.extent(data, function(d) { return d.datetime; }));
y.domain([0, d3.max(data, function(d) { return d.temperature; })]);
svg.append("path")
.attr("class", "line")
.attr("d", valueline(data));
svg.selectAll("dot")
.data(data)
.enter().append("circle")
.attr("r", 4)
.attr("cx", function(d) { return x(d.datetime); })
.attr("cy", function(d) { return y(d.temperature); })
.on("mouseover", function(d) {
div.transition()
.duration(200)
.style("opacity", 1);
div.html(formatTime(d.datetime) + "<br/>" + d.temperature + " &#8451")
.style("left", (d3.event.pageX + 16) + "px")
.style("top", (d3.event.pageY + 16) + "px")
.style("position", "absolute");
})
.on("mouseout", function(d) {
div.transition()
.duration(50)
.style("opacity", 0);
});
svg.append("g")
.attr("class", "grid")
.attr("transform", "translate(0," + height + ")")
.call(make_x_axis()
.tickSize(-height, 0, 0)
.tickFormat("")
)
svg.append("g")
.attr("class", "grid")
.call(make_y_axis()
.tickSize(-width, 0, 0)
.tickFormat("")
)
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
</script>
</body>
I tried to do this:
function updateData() {
//d3.json("/assets/php/getTemp.php", function(error, data) {
<?php echo "data=".$json_data.";" ?>
data.forEach(function(d) {
d3.select("body").selectAll("svg")
d.datetime = parseDate(d.datetime);
d.temperature = +d.temperature;
});
x.domain(d3.extent(data, function(d) { return d.datetime; }));
y.domain([0, d3.max(data, function(d) { return d.temperature; })]);
var svg = d3.select("body").transition();
svg.select(".line")
.duration(750)
.attr("d", valueline(data));
svg.select(".x.axis")
.duration(750)
.call(xAxis);
svg.select(".y.axis")
.duration(750)
.call(yAxis);
};
but nothing happens, not even an error.
If it matters this is the PHP code used to get the temperatures and time form MySQL:
<?php
$hostname = 'localhost';
$username = 'root';
$password = 'admin';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=temp_database",
$username, $password);
$sth = $dbh->prepare("
SELECT `datetime`, `temperature` FROM `tempLog`
");
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
$json_data = json_encode($result);
?>
What i need to do ?
Look into using the d3.json function. This lets you get json from php scripts without reloading the entire page from scratch. It's AJAX stuff, but the d3 helper functions hide the details.
https://github.com/mbostock/d3/wiki/Requests
PS. Remember, it will be an asynchronous call, so see the accepted answer here as well:
JSON output from PHP using d3.json
As to why it doesn't work currently, my hunch*, though there's not enough info to confirm, is that there's no change because it's always the same data, so nothing will change
<?php echo "data=".$json_data.";" ?>
That line^^^ in updateData is evaluated once at the start and then the whole function is plonked into the javascript realm. However many times you then call updateData, that previously generated javascript variable (data={some_json}) won't change without reloading the php page that generated updateData, even if you call that database related php that generates the server side variable.
*could be nonsense, but the bit above the line is still right

Q: I need idea to display a string with css, jquery or any other techniques (no php)

I have a big problem. I have a mysql database which contains 12 character length fields. I would like to display somehow.
Sample data from the field:
233215334523
I would like to display 0 and 1 with red background 2 3 with yellow background and 4 5 with green background.
Important! I know str_split could split the string into characters, or I could use $string[1] $string[2] etc. also, but not now, because this cms use the lex parser ( you couldn't use php variables here!).
So I need some great idea how could I split virtual this 12 character length variable. The best should be some which display these numbers with the background colors what I wrote earlier.
I hope someone could help for me, because I have no idea. Many thanks!
Wrap each character in a span, with a classname:
HTML:
<div id="fieldToSplit">233215334523</div>
javascript:
var element = document.getElementById("fieldToSplit")
var data = element.innerHTML.split("");
var wrappedString = "";
for (var i = 0; i < data.length; i++) {
wrappedString += "<span class='shade" + data[i] + "'>" + data[i] + "</span>";
}
element.innerHTML = wrappedString;
CSS:
.shade0, .shade1 {
background-color: #FF0000;
}
.shade2, .shade3 {
background-color: #FFFF00;
}
.shade4, .shade5 {
background-color: #00FF00;
}
This solution allows you to freely style each digit independently, say you wanted a darker green for 5 than for 4. And if later you need styles for 6,7,8, and 9, all you need to do is add classes .shade6, .shade7, .shade8, and .shade9.
Fiddle here:
http://jsfiddle.net/rwbm9ttn/1/
Something like this?
$(document).ready(function() {
var letters = $('.source').html().split(/\s?/)
for (var i = 0; i <= letters.length; ++i) {
$('<span class="lt' + letters[i] + '">').html(letters[i]).appendTo(".letters");
}
});
.lt2 {
background: yellow;
}
.lt3 {
background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div class="source">233215334523</div>
<div class="letters"></div>
Here is a pure jquery & CSS solution:
http://jsfiddle.net/k91ax5g9/1/
HTML
<div class='num'>101234567</div>
<div class='num'>1011223444</div>
<div class='num'>124413223</div>
<div class='num'>323123133</div>
JS
$(".num").each(function(){
var $el = $(this);
var t =$el.html();
$el.html('');
for(var c in t){
var char = t[c];
$el.append($("<span>", {'text_val': char}).html(char));
}
});
CSS
[text_val="0"], [text_val="1"]{
background: red;
}
[text_val="2"], [text_val="3"]{
background: orange;
}
[text_val="4"], [text_val="5"]{
background: green;
}
An entirely jQuery version would be like this -
$(document).ready(function(){
var data = 233215334523;
var str = data.toString();
var hold = '';
for(var i = 0; i<str.length; i++)
{
if(str[i] == 0 || str[i] == 1)
{
hold = hold + '<span style="background-color: red;">'+str[i]+'</span>';
$('.print').html(hold);
}
else if(str[i] == 2 || str[i] == 3)
{
hold = hold + '<span style="background-color: yellow;">'+str[i]+'</span>';
$('.print').html(hold);
}
else if(str[i] == 4 || str[i] == 5)
{
hold = hold + '<span style="background-color: green;">'+str[i]+'</span>';
$('.print').html(hold);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="print"></p>

jquery - multiple image upload form with remove option

I want some suggestions regarding image upload form like facebook and tumblr which can preview multiple images with caption and description fields with each image and if user wants to remove any image before uploading he is able to do that. So please suggest me how to achieve this i have tried this but i am having issue with removing image from input type = file as it is readonly i am facing problem when i am submitting the form on server. Please give me your ideas i really need help i have deadline of this month i am badly stuck in this problem. I am using php and jquery. Note: Please dont suggest any plugins.
Thanks in advance.
I have face same problem like you
now i have found solution for that i think this will be useful for you to solve your problem
<input type="file" id="attachfile" name="replyFiles" multiple> <!--File Element for multiple intput-->
<div id="#filelist"></div>
<script>
var selDiv = "";
var storedFiles = []; //store the object of the all files
document.addEventListener("DOMContentLoaded", init, false);
function init() {
//To add the change listener on over file element
document.querySelector('#attachfile').addEventListener('change', handleFileSelect, false);
//allocate division where you want to print file name
selDiv = document.querySelector("#filelist");
}
//function to handle the file select listenere
function handleFileSelect(e) {
//to check that even single file is selected or not
if(!e.target.files) return;
//for clear the value of the selDiv
selDiv.innerHTML = "";
//get the array of file object in files variable
var files = e.target.files;
var filesArr = Array.prototype.slice.call(files);
//print if any file is selected previosly
for(var i=0;i<storedFiles.length;i++)
{
selDiv.innerHTML += "<div class='filename'> <span class='removefile' data-file='"+storedFiles[i].name+"'> " + storedFiles[i].name + "</span></div>";
}
filesArr.forEach(function(f) {
//add new selected files into the array list
storedFiles.push(f);
//print new selected files into the given division
selDiv.innerHTML += "<div class='filename'> <span class='removefile' data-file='"+storedFiles[i].name+"'> " + f.name + "</span></div>";
});
//store the array of file in our element this is send to other page by form submit
$("input[name=replyfiles]").val(storedFiles);
}
//This function is used to remove the file form the selection
function removeFile(e) {
var file = $(this).data("file"); //To take the name of the file
for(var i=0;i<storedFiles.length;i++) { //for find the file from the array
if(storedFiles[i].name === file) {
storedFiles.splice(i,1); //remove file from the list
break;
}
}
//now store the list of the all remaining file in our element name which will submit with the form
$("input[name=replyfiles]").val(storedFiles);
$(this).parent().remove();
}
$(document).ready(function(){
$("body").on("click", ".removefile", removeFile);
})
</script>
//I added event handler for the file upload control to access the files properties.
document.addEventListener("DOMContentLoaded", init, false);
//To save an array of attachments
var AttachmentArray = [];
//counter for attachment array
var arrCounter = 0;
//to make sure the error message for number of files will be shown only one time.
var filesCounterAlertStatus = false;
//un ordered list to keep attachments thumbnails
var ul = document.createElement("ul");
ul.className = "thumb-Images";
ul.id = "imgList";
function init() {
//add javascript handlers for the file upload event
document
.querySelector("#files")
.addEventListener("change", handleFileSelect, false);
}
//the handler for file upload event
function handleFileSelect(e) {
//to make sure the user select file/files
if (!e.target.files) return;
//To obtaine a File reference
var files = e.target.files;
// Loop through the FileList and then to render image files as thumbnails.
for (var i = 0, f; (f = files[i]); i++) {
//instantiate a FileReader object to read its contents into memory
var fileReader = new FileReader();
// Closure to capture the file information and apply validation.
fileReader.onload = (function(readerEvt) {
return function(e) {
//Apply the validation rules for attachments upload
ApplyFileValidationRules(readerEvt);
//Render attachments thumbnails.
RenderThumbnail(e, readerEvt);
//Fill the array of attachment
FillAttachmentArray(e, readerEvt);
};
})(f);
// Read in the image file as a data URL.
// readAsDataURL: The result property will contain the file/blob's data encoded as a data URL.
// More info about Data URI scheme https://en.wikipedia.org/wiki/Data_URI_scheme
fileReader.readAsDataURL(f);
}
document
.getElementById("files")
.addEventListener("change", handleFileSelect, false);
}
//To remove attachment once user click on x button
jQuery(function($) {
$("div").on("click", ".img-wrap .close", function() {
var id = $(this)
.closest(".img-wrap")
.find("img")
.data("id");
//to remove the deleted item from array
var elementPos = AttachmentArray.map(function(x) {
return x.FileName;
}).indexOf(id);
if (elementPos !== -1) {
AttachmentArray.splice(elementPos, 1);
}
//to remove image tag
$(this)
.parent()
.find("img")
.not()
.remove();
//to remove div tag that contain the image
$(this)
.parent()
.find("div")
.not()
.remove();
//to remove div tag that contain caption name
$(this)
.parent()
.parent()
.find("div")
.not()
.remove();
//to remove li tag
var lis = document.querySelectorAll("#imgList li");
for (var i = 0; (li = lis[i]); i++) {
if (li.innerHTML == "") {
li.parentNode.removeChild(li);
}
}
});
});
//Apply the validation rules for attachments upload
function ApplyFileValidationRules(readerEvt) {
//To check file type according to upload conditions
if (CheckFileType(readerEvt.type) == false) {
alert(
"The file (" +
readerEvt.name +
") does not match the upload conditions, You can only upload jpg/png/gif files"
);
e.preventDefault();
return;
}
//To check file Size according to upload conditions
if (CheckFileSize(readerEvt.size) == false) {
alert(
"The file (" +
readerEvt.name +
") does not match the upload conditions, The maximum file size for uploads should not exceed 300 KB"
);
e.preventDefault();
return;
}
//To check files count according to upload conditions
if (CheckFilesCount(AttachmentArray) == false) {
if (!filesCounterAlertStatus) {
filesCounterAlertStatus = true;
alert(
"You have added more than 10 files. According to upload conditions you can upload 10 files maximum"
);
}
e.preventDefault();
return;
}
}
//To check file type according to upload conditions
function CheckFileType(fileType) {
if (fileType == "image/jpeg") {
return true;
} else if (fileType == "image/png") {
return true;
} else if (fileType == "image/gif") {
return true;
} else {
return false;
}
return true;
}
//To check file Size according to upload conditions
function CheckFileSize(fileSize) {
if (fileSize < 300000) {
return true;
} else {
return false;
}
return true;
}
//To check files count according to upload conditions
function CheckFilesCount(AttachmentArray) {
//Since AttachmentArray.length return the next available index in the array,
//I have used the loop to get the real length
var len = 0;
for (var i = 0; i < AttachmentArray.length; i++) {
if (AttachmentArray[i] !== undefined) {
len++;
}
}
//To check the length does not exceed 10 files maximum
if (len > 9) {
return false;
} else {
return true;
}
}
//Render attachments thumbnails.
function RenderThumbnail(e, readerEvt) {
var li = document.createElement("li");
ul.appendChild(li);
li.innerHTML = [
'<div class="img-wrap"> <span class="close">×</span>' +
'<img class="thumb" src="',
e.target.result,
'" title="',
escape(readerEvt.name),
'" data-id="',
readerEvt.name,
'"/>' + "</div>"
].join("");
var div = document.createElement("div");
div.className = "FileNameCaptionStyle";
li.appendChild(div);
div.innerHTML = [readerEvt.name].join("");
document.getElementById("Filelist").insertBefore(ul, null);
}
//Fill the array of attachment
function FillAttachmentArray(e, readerEvt) {
AttachmentArray[arrCounter] = {
AttachmentType: 1,
ObjectType: 1,
FileName: readerEvt.name,
FileDescription: "Attachment",
NoteText: "",
MimeType: readerEvt.type,
Content: e.target.result.split("base64,")[1],
FileSizeInBytes: readerEvt.size
};
arrCounter = arrCounter + 1;
}
/*Copied from bootstrap to handle input file multiple*/
.btn {
display: inline-block;
padding: 6px 12px;
margin-bottom: 0;
font-size: 14px;
font-weight: normal;
line-height: 1.42857143;
text-align: center;
white-space: nowrap;
vertical-align: middle;
cursor: pointer;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
background-image: none;
border: 1px solid transparent;
border-radius: 4px;
}
/*Also */
.btn-success {
border: 1px solid #c5dbec;
background: #d0e5f5;
font-weight: bold;
color: #2e6e9e;
}
/* This is copied from https://github.com/blueimp/jQuery-File-Upload/blob/master/css/jquery.fileupload.css */
.fileinput-button {
position: relative;
overflow: hidden;
}
.fileinput-button input {
position: absolute;
top: 0;
right: 0;
margin: 0;
opacity: 0;
-ms-filter: "alpha(opacity=0)";
font-size: 200px;
direction: ltr;
cursor: pointer;
}
.thumb {
height: 80px;
width: 100px;
border: 1px solid #000;
}
ul.thumb-Images li {
width: 120px;
float: left;
display: inline-block;
vertical-align: top;
height: 120px;
}
.img-wrap {
position: relative;
display: inline-block;
font-size: 0;
}
.img-wrap .close {
position: absolute;
top: 2px;
right: 2px;
z-index: 100;
background-color: #d0e5f5;
padding: 5px 2px 2px;
color: #000;
font-weight: bolder;
cursor: pointer;
opacity: 0.5;
font-size: 23px;
line-height: 10px;
border-radius: 50%;
}
.img-wrap:hover .close {
opacity: 1;
background-color: #ff0000;
}
.FileNameCaptionStyle {
font-size: 12px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div>
<label style="font-size: 14px;">
<span style='color:navy;font-weight:bold'>Attachment Instructions :</span>
</label>
<!--To give the control a modern look, I have applied a stylesheet in the parent span.-->
<span class="btn btn-success fileinput-button">
<span>Select Attachment</span>
<input type="file" name="files[]" id="files" multiple accept="image/jpeg, image/png, image/gif,"><br />
</span>
<output id="Filelist"></output>
</div>

how to pre-load images from a link in php or jquery

i have searched feverishly for a solution to my gallery, which doesnt apply the centering function to the image as i click it's respective thumbnail. instead i have to click the thumbnail at least twice for the large image to pop up in the center of the page. the gallery is a jquery/php. i have dynamically loaded my thumbnails using php and link them to the respective large image with the same name using php. I am wondering preloading the large image would help this problem if so how can i preload them seeing as though its an entire directory which has alot of pictures, hence why i didnt manually load them. the script is below:
<?php
error_reporting(0);
/* function: returns files from dir */
function get_files($images_dir,$exts = array('jpeg','gif','png','jpg')) {
$files = array();
if($handle = opendir($images_dir)) {
while(false !== ($file = readdir($handle))) {
$extension = strtolower(get_file_extension($file));
if($extension && in_array($extension,$exts)) {
$files[] = $file;
}
}
closedir($handle);
}
return $files;
}
/* function: returns a file's extension */
function get_file_extension($file_name) {
return substr(strrchr($file_name,'.'),1);
}
$images_dir = 'hftpnyc/thumbs/';
$thumbs_dir = 'hftpnyc/thumbs/thumbnails/';
$thumbs_width = 100;
$images_per_row = 11;
$string = "";
/** generate photo gallery **/
$image_files = get_files($images_dir);
if(count($image_files)) {
$index = 0;
foreach($image_files as $index=>$file) {
$index++;
$thumbnail_image = $thumbs_dir.$file;
//if(!file_exists($thumbnail_image)) {
//$extension = get_file_extension($thumbnail_image);
//if($extension) {
//make_thumb($images_dir.$file,$thumbnail_image,$thumbs_width);
//}
//}
error_reporting(0);
echo '<div class="smllpic" style=" padding: 0px; margin: 0px; border: 1px solid black; display: block; width: 100px; height:100px; float: left; "> <img id="thumbs" src="',$thumbnail_image,'" width="100px"/></div>';
if($index % $images_per_row == 0) { echo '<div class="clear"></div>'; }
}
}
else {
echo '<p>There are no images in this gallery.</p>';
}
?>
<script type="text/javascript">
$(document).ready(function(){
$('.smllpic img').hover(function () {
var $this = $(this);
$this.stop().animate({'opacity':'1.0'},200);
},function () {
var $this = $(this);
$this.stop().animate({'opacity':'0.7'},200);
});
function centreit(){
//get the height and width of the modal
var modal_height = $('.box').height();
var modal_width = $('.box').width();
//get the height and width of the page
var window_width = $(window).width();
var window_height = $(window).height();
//calculate top and left offset needed for centering
var topp = (window_height - modal_height)/2;
var left = (window_width - modal_width)/2;
//apply new top and left css values
$('.box').css({'top' : topp+'px' , 'left' : left+'px', 'right': left+'px','bottom':topp+'px'});
$('.motown').css({'top' : topp+'px' , 'left' : left+'px', 'right': left+'px','bottom':topp+'px'});
};
$('.lightbox').click(function(e) {
e.preventDefault(); // keeps new page from loading
var thisPicture = $(this).attr('href'); // path to full sized picture,
function getit(){
$('body').append('<div class="backdrop" label="click to close"></div><div class="box" id="centre" ><div class="close">x</div><div style="cursor:pointer; opacity:1;font-family:Agency FB;margin-top:50%; right:-20px;position:fixed;color:white;font-size:50px; z-index:50;-webkit-border-radius: 5px;-moz-border-radius: 5px;border-radius: 5px;-moz-box-shadow:0px 0px 5px #444444;-webkit-box-shadow:0px 0px 5px #444444;box-shadow:0px 0px 5px #444444;">></div><div style="cursor:pointer; opacity:.35;font-family:Agency FB;margin-top:50%; left:-20px; position:absolute; font-size:50px;color:white; z-index:70;-webkit-border-radius:5px;-moz-border-radius: 5px; border-radius:5px;-moz-box-shadow:0px 0px 5px #444444; -webkit-box-shadow:0px 0px 5px #444444; box-shadow:0px 0px 5px #444444;"><</div><img class="motown" src="'+thisPicture+'" style="max-height:705px;max-width:905px;" ></div>');
};
centreit();
$(window).resize(function(){
$('.box').resize();
$('.motown').resize();
centreit();
});
if ($('.smllpic').click()){
getit();
centreit();
$("html").css("overflow", "hidden");
$('.backdrop').fadeTo(500,0.9);
$('.box').children().fadeIn(1000);
};
//$('.backdrop').css({ 'display' : 'block', opacity : 0});
$('.close').click(function(){
close_box();});
$('.backdrop').click(function(){
close_box();});
function close_box(){
$('.backdrop').remove();
$('.box').remove();
$("html").css("overflow", "");};
});});
</script>
Don't preload the larger images. You are better off using jQuery to display a loading indicator (you can download gif loading indicators from - http://ajaxload.info/) while the image is being loaded. Once the image has been loaded, remove the indicator.

Categories