Display select image with original size - javascript

I've search for simple image cropping and i found one, i study all the part and now i want to add some features, this features is selecting an image and display it immediately i got it, but i have a little confusing problem, the problem is after selecting image it doesnt display the original size of image.
INDEX.PHP
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-type" content="text/html;charset=utf-8">
<title>Jcrop Dynamic Avatar JS/PHP Demo</title>
<link rel="shortcut icon" href="http://teamtreehouse.com/assets/favicon.ico">
<link rel="icon" href="http://teamtreehouse.com/assets/favicon.ico">
<link rel="stylesheet" type="text/css" href="css/styles.css">
<link rel="stylesheet" type="text/css" href="css/jquery.Jcrop.css">
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Wellfleet">
<script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="js/jquery.Jcrop.js"></script>
<script type="text/javascript" src="js/cropsetup.js"></script>
<script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>
<!--This is what i add---->
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('.sep').attr('src', e.target.result);
$('.jcrop-preview').attr('src', e.target.result);
};
reader.readAsDataURL(input.files[0]);
}
}
</script>
<!--END---->
</head>
<body>
<div id="wrapper">
<div class="jc-demo-box">
<header>
<h1><span>Create your profile</span></h1>
</header>
<div id="ew" style="width: 500px; height:500px; background: rgb(102,102,102);">
<img src="" id="target" class="sep" alt="crop image"/> //THIS IS THE IMAGE I WANT TO SHOW THE ORIGINAL SIZE AFTER SELECTING FROM FILES
</div>
<div id="button_upload"><span>Select Image</span>
<input type="file" name="fileToUpload" id="fileToUpload" onchange="readURL(this);">
</div>
<div id="mo">
<div id="preview-pane">
<div class="preview-container">
<div id="ew2"> <img src="" class="jcrop-preview" alt="Preview" /> </div>
</div>
</div>
</div>
<!-- #end #preview-pane -->
<div id="form-container">
<form id="cropimg" name="cropimg" method="post" action="crop.php" target="_blank">
<input type="hidden" id="x" name="x">
<input type="hidden" id="y" name="y">
<input type="hidden" id="w" name="w">
<input type="hidden" id="h" name="h">
<input type="submit" id="submit" value="Crop Image!">
</form>
</div>
<!-- #end #form-container -->
</div>
<!-- #end .jc-demo-box -->
</div>
<!-- #end #wrapper -->
</body>
</html>
CROPSETUP.JS
$(function($){
// Create variables (in this scope) to hold the API and image size
var jcrop_api,
boundx,
boundy,
// Grab some information about the preview pane
$preview = $('#preview-pane'),
$pcnt = $('#preview-pane .preview-container'),
$pimg = $('#preview-pane .preview-container img'),
xsize = $pcnt.width(),
ysize = $pcnt.height();
$('#target').Jcrop({
onChange: updatePreview,
onSelect: updatePreview,
bgOpacity: 0.5,
aspectRatio: xsize / ysize
},function(){
// Use the API to get the real image size
var bounds = this.getBounds();
boundx = bounds[0];
boundy = bounds[1];
jcrop_api = this; // Store the API in the jcrop_api variable
// Move the preview into the jcrop container for css positioning
$preview.appendTo(jcrop_api.ui.holder);
});
function updatePreview(c) {
if (parseInt(c.w) > 0) {
var rx = xsize / c.w;
var ry = ysize / c.h;
$('#x').val(c.x);
$('#y').val(c.y);
$('#w').val(c.w);
$('#h').val(c.h);
$pimg.css({
width: Math.round(rx * boundx) + 'px',
height: Math.round(ry * boundy) + 'px',
marginLeft: '-' + Math.round(rx * c.x) + 'px',
marginTop: '-' + Math.round(ry * c.y) + 'px'
});
}
}
});
**Also how can i save the image after submit? here is the code for submit but i'm failed for getting the image after croping.
CROP.PHP
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$targ_w = $targ_h = 180;
$jpeg_quality = 90;
if(!isset($_POST['x']) || !is_numeric($_POST['x'])) {
die('Please select a crop area.');
}
$src = //This where i want to put the image after scrop but i dont know how
$img_r = imagecreatefromjpeg($src);
$dst_r = ImageCreateTrueColor($targ_w, $targ_h);
imagecopyresampled($dst_r,$img_r,0,0,$_POST['x'],$_POST['y'],
$targ_w,$targ_h,$_POST['w'],$_POST['h']);
header('Content-type: image/jpeg');
imagejpeg($dst_r,null,$jpeg_quality); // NULL will output the image directly
exit;
}
?>
Thanks!!!

Related

Send multiple cropped images in cropper.js using PHP [duplicate]

I am trying to crop image and send the cropped data to server side. I am using imgareaselect plugin. I get the coordinates of selection but could not crop the image. All the solutions available on internet is to preview cropped image using css. But how can I get the cropped data? No need of preview the cropped image. My code is
cropw = $('#cropimg').imgAreaSelect({
maxWidth: 300, maxHeight: 300,
aspectRatio: '1:1',
instance: true,
handles: true,
onSelectEnd: function (img, selection) {
x1 = selection.x1;
y1 = selection.y1;
x2 = selection.x2;
y2 = selection.y2;
}
});
Hey #Shahbaz I was trying out a solution for you using cropper.js.
This is what you can do
Download cropper.js from here
//link the js files
<head>
<script src="jquery.js"></script> // optional
<link href="cropper.min.css" rel="stylesheet">
<script src="cropper.min.js"></script>
</head>
Body
<input type="file" name="image" id="image" onchange="readURL(this);"/>
<div class="image_container">
<img id="blah" src="#" alt="your image" />
</div>
<div id="cropped_result"></div> // Cropped image to display (only if u want)
<button id="crop_button">Crop</button> // Will trigger crop event
Javascript
<script type="text/javascript" defer>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result)
};
reader.readAsDataURL(input.files[0]);
setTimeout(initCropper, 1000);
}
}
function initCropper(){
var image = document.getElementById('blah');
var cropper = new Cropper(image, {
aspectRatio: 1 / 1,
crop: function(e) {
console.log(e.detail.x);
console.log(e.detail.y);
}
});
// On crop button clicked
document.getElementById('crop_button').addEventListener('click', function(){
var imgurl = cropper.getCroppedCanvas().toDataURL();
var img = document.createElement("img");
img.src = imgurl;
document.getElementById("cropped_result").appendChild(img);
/* ---------------- SEND IMAGE TO THE SERVER-------------------------
cropper.getCroppedCanvas().toBlob(function (blob) {
var formData = new FormData();
formData.append('croppedImage', blob);
// Use `jQuery.ajax` method
$.ajax('/path/to/upload', {
method: "POST",
data: formData,
processData: false,
contentType: false,
success: function () {
console.log('Upload success');
},
error: function () {
console.log('Upload error');
}
});
});
----------------------------------------------------*/
})
}
</script>
Hope this helps. Thanks.
Added this one based on the accepted answer, In case anyone is using the jquery wrapper for cropper
let ICropper = (function($) {
let $cropperCanvasImage = $('#cropper-canvas-image');
return {
readUrl,
cropImage
}
function readUrl(input) {
if (input.files && input.files[0]) {
let reader = new FileReader();
reader.onload = function(e) {
$cropperCanvasImage.attr('src', e.target.result)
};
reader.readAsDataURL(input.files[0]);
setTimeout(initCropper, 1000);
}
}
function initCropper() {
$cropperCanvasImage.cropper({
aspectRatio: 1 / 1
});
}
function cropImage() {
let imgUrl = $cropperCanvasImage.data('cropper').getCroppedCanvas().toDataURL();
let img = document.createElement("img");
img.src = imgUrl;
$("#cropped-result").append(img);
}
})(jQuery)
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.4.1/cropper.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script name="jquery-croper-script">
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(require("jquery"),require("cropperjs")):"function"==typeof define&&define.amd?define(["jquery","cropperjs"],r):r(e.jQuery,e.Cropper)}(this,function(c,s){"use strict";if(c=c&&c.hasOwnProperty("default")?c.default:c,s=s&&s.hasOwnProperty("default")?s.default:s,c.fn){var e=c.fn.cropper,d="cropper";c.fn.cropper=function(p){for(var e=arguments.length,a=Array(1<e?e-1:0),r=1;r<e;r++)a[r-1]=arguments[r];var u=void 0;return this.each(function(e,r){var t=c(r),n="destroy"===p,o=t.data(d);if(!o){if(n)return;var f=c.extend({},t.data(),c.isPlainObject(p)&&p);o=new s(r,f),t.data(d,o)}if("string"==typeof p){var i=o[p];c.isFunction(i)&&((u=i.apply(o,a))===o&&(u=void 0),n&&t.removeData(d))}}),void 0!==u?u:this},c.fn.cropper.Constructor=s,c.fn.cropper.setDefaults=s.setDefaults,c.fn.cropper.noConflict=function(){return c.fn.cropper=e,this}}});
</script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.4.1/cropper.min.css" />
<input type="file" name="source-image" id="sourceImage" onchange="ICropper.readUrl(this);" />
<div class="image-container">
<img id="cropper-canvas-image" src="#" alt="your image" />
</div>
<div id="cropped-result"></div>
<button onclick="ICropper.cropImage(this)">Crop</button>
Did you try using a crop plugin for Jquery, like:
https://fengyuanchen.github.io/cropper/
You have to import the scripts in your page:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$targ_w = $targ_h = 150;
$jpeg_quality = 90;
$src = 'demo_files/pool.jpg';
$img_r = imagecreatefromjpeg($src);
$dst_r = ImageCreateTrueColor( $targ_w, $targ_h );
imagecopyresampled($dst_r,$img_r,0,0,$_POST['x'],$_POST['y'],
$targ_w,$targ_h,$_POST['w'],$_POST['h']);
header('Content-type: image/jpeg');
imagejpeg($dst_r,null,$jpeg_quality);
exit;
}
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="http://deepliquid.com/Jcrop/js/jquery.Jcrop.min.js"></script>
<script src="../js/jquery.Jcrop.js"></script>
<link rel="stylesheet" href="../css/jquery.Jcrop.css" type="text/css" />
<link rel="stylesheet" href="demo_files/demos.css" type="text/css" />
<script language="Javascript">
$(function(){
$('#cropbox').Jcrop({
aspectRatio: 1,
onSelect: updateCoords
});
});
function updateCoords(c)
{
$('#x').val(c.x);
$('#y').val(c.y);
$('#w').val(c.w);
$('#h').val(c.h);
};
function checkCoords()
{
if (parseInt($('#w').val())) return true;
alert('Selecione a área para recorte.');
return false;
};
</script>
</head>
<body>
<div id="outer">
<div class="jcExample">
<div class="article">
<h1>Crop jQuery</h1>
<img src="demo_files/pool.jpg" id="cropbox" />
<form action="crop.php" method="post" onsubmit="return checkCoords();">
<input type="hidden" id="x" name="x" />
<input type="hidden" id="y" name="y" />
<input type="hidden" id="w" name="w" />
<input type="hidden" id="h" name="h" />
<input type="submit" value="Crop Image" />
</form>
</div>
</div>
</div>
</body>
</html>

Can I overide CSS values after form submit using JavaScript Function?

I have a simple form where you can upload html files. I have 3 files:
Main HTML file - which contains my form and JavaScript function.
Secondary HTML file - this is used to upload to the form.
CSS file - this is for the secondary HTML file.
I want to override the CSS value of the uploaded html file using this function in my main HTML file:
<!DOCTYPE html>
<html>
<head>>
<meta charset="UTF-8">
<title>Changing the style of another HTML File</title>
<script type="text/javascript">
function updateSize() {
var nBytes = 0,
oFiles = document.getElementById("uploadInput").files,
nFiles = oFiles.length;
for (var nFileId = 0; nFileId < nFiles; nFileId++) {
nBytes += oFiles[nFileId].size;
}
var sOutput = nBytes + " bytes";
// optional code for multiples approximation
for (var aMultiples = ["KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"], nMultiple = 0, nApprox = nBytes / 1024; nApprox > 1; nApprox /= 1024, nMultiple++) {
sOutput = nApprox.toFixed(3) + " " + aMultiples[nMultiple] + " (" + nBytes + " bytes)";
}
// end of optional code
document.getElementById("fileNum").innerHTML = nFiles;
document.getElementById("fileSize").innerHTML = sOutput;
}
function extract() {
var el = document.getElementById("test");
el.style.background = 'green';
el.style.color = 'red';
}
</script>
<body onload="updateSize();">
<form>
<p><input id="uploadInput" type="file" name="myFiles" onchange="updateSize();" multiple> selected files: <span id="fileNum">0</span>; total size: <span id="fileSize">0</span></p>
<p><input type="button" value="Submit" onclick="extract()"></p>
</form>
</body>
</html>
The Secondary HTML file has the following code (This will be submitted to the form):
<html>
<head>
<link rel="stylesheet" type="text/css" href="test.css" />
</head>
<body>
<div id="test">This is a div</div>
</body>
</html>
This is my CSS file for my Secondary HTML file:
#test {
background-color: red;
color: yellow;
};
However, it doesn't work. Where I'm I going wrong?
You are using input type="submit", which do page reload. So when background change to green and it reload so it is not showing your style changes. So remove type ="submit". use input type="button.and then onclick function in button. You ca use this code:-
<html>
<head>
<link rel="stylesheet" type="text/css" href="test.css" />
</head>
<body>
<div id="test">This is a div</div>
<form >
<p><input id="uploadInput" type="file" name="myFiles" onchange="updateSize();" multiple> selected files: <span id="fileNum">0</span>; total size: <span id="fileSize">0</span></p>
<p><input type="button" value="Submit" onclick="extract()"></p>
</form>
<script type="text/javascript">
function extract() {
var el = document.getElementById("test");
el.style.background = 'green';
el.style.color = 'red';
}
</script>
</body>
</html>
When a form is submitted the page reloads, so...
Form is submitted,
CSS changed,
Page reloaded,
CSS is at it's default
Try using AJAX

passing, dynamically created objects, to a function

I've created a jQuery UI Accordion image loader that dynamically adds or removes panels. Inside each panel is an image input form control and at the end of the document is a function that is supposed to change the img src in the panel to the newly selected image. Unfortunately, I am getting: cannot read 'files' of undefined. I understand why its doing this, I just need a way to dynamically add the panels AND be able to update the img src for the panel that loaded the image.
My code, so far, is:
<!DOCTYPE html>
<html lang="en">
<head>
<!-- css links -->
<link href="/Content/bootstrap-theme.css" rel="stylesheet" />
<link href="/Content/bootstrap.css" rel="stylesheet" />
<link href="/Scripts/jquery-ui-1.12.0/jquery-ui.css" rel="stylesheet" />
<!-- /css links -->
<!-- js files -->
<script src="/Scripts/jquery-3.1.0.js"></script>
<script src="/Scripts/jquery-ui-1.12.0/jquery-ui.js"></script>
<!-- /js files -->
</head>
<body id="myPage" data-spy="scroll" data-target=".navbar" data-offset="60">
<script lang="en" type="text/javascript">
$(function () {
$("#PrimaryImageAccordion").accordion({
collapsible: true
});
});
</script>
<br /><br />
<button type='button' onclick='btnAddPrimaryImage_Click();' class='btn btn-default'> Add </button>
<div id="PrimaryImageAccordion">
<h4 class="PrimaryImageTitle">Primary Image</h4>
<div>
<div class="row form-group">
<label for="ImageSelector" class="control-label col-md-2">Project Image</label>
<div class="col-md-10">
<input type="file" id="ImageSelector" onchange="ImageSelector_Change(this);" /><br />
<img id="Image" src="#" style="width: 100px; visibility: hidden;" />
</div>
</div>
</div>
</div>
<script lang="en" type="text/javascript">
function btnAddPrimaryImage_Click() {
var template = "<h4 class='PrimaryImageTitle'>Primary Image<a onclick='removePanel(this);' style='float:right'>X</a></h4>\n";
template += "<div class='AccordionPanel'><div class='row form-group'>\n";
template += "<label for='ImageSelector' class='control-label col-md-2'>Project Image</label>\n";
template += "<div class='col-md-10'>\n";
template += "<input type='file' id='Image1Selector' /><br />\n";
template += "<img id='Image' src='#' style='width: 100px; visibility: hidden;' />\n";
template += "</div></div></div>\n";
$("#PrimaryImageAccordion").append(template);
$("#PrimaryImageAccordion").accordion("refresh");
}
function removePanel(a) {
$(a).parent().next().remove();
$(a).parent().remove();
$("#PrimaryImageAccordion").accordion("refresh");
return false;
}
function ImageSelector_Change(object, input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
object.attr("src", e.target.result);
object.css("visibility", "visible");
}
reader.readAsDataURL(input.files[0]);
}
}
</script>
</body>
</html>
Update 1
Changed my main selector/loader function as follows:
function ImageSelector_Change(input) {
var object = $(input).parent().find('img#Image');
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
object.attr("src", e.target.result);
object.css("visibility", "visible");
}
reader.readAsDataURL(input.files[0]);
}
}
only problem is that it loads the first image only, not the additional images
The IDs must be unique.
So in the function btnAddPrimaryImage_Click I corrected how the new elements are added to the accordion using an incremental variable.
The function ImageSelector_Change needs to get two parameters:
this: in order to get image
image id where to put the loaded image.
Moreover, because you are using bootstrap I suggest you to avoid jQuery 3.x for compatibility issues.
The snippet:
$(function () {
$("#PrimaryImageAccordion").accordion({
collapsible: true
});
});
var idCounter = 0;
function btnAddPrimaryImage_Click() {
idCounter++;
var template = "<h4 class='PrimaryImageTitle'>Primary Image<a onclick='removePanel(this);' style='float:right'>X</a></h4>\n";
template += "<div class='AccordionPanel'><div class='row form-group'>\n";
template += "<label for='ImageSelector'" + idCounter + " class='control-label col-md-2'>Project Image</label>\n";
template += "<div class='col-md-10'>\n";
template += "<input type='file' id='ImageSelector" + idCounter + "' onchange='ImageSelector_Change(this,\"Image" + idCounter + "\");' /><br />\n";
template += "<img id='Image" + idCounter + "' src='#' style='width: 100px; visibility: hidden;' />\n";
template += "</div></div></div>\n";
$("#PrimaryImageAccordion").append(template);
$("#PrimaryImageAccordion").accordion("refresh");
}
function removePanel(a) {
$(a).parent().next().remove();
$(a).parent().remove();
$("#PrimaryImageAccordion").accordion("refresh");
return false;
}
function ImageSelector_Change(object, input) {
if (object.files && object.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
document.getElementById(input).src = e.target.result;
document.getElementById(input).style.visibility = "visible";
}
reader.readAsDataURL(object.files[0]);
}
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<br /><br />
<button type='button' onclick='btnAddPrimaryImage_Click();' class='btn btn-default'> Add </button>
<div id="PrimaryImageAccordion">
<h4 class="PrimaryImageTitle">Primary Image</h4>
<div>
<div class="row form-group">
<label for="ImageSelector" class="control-label col-md-2">Project Image</label>
<div class="col-md-10">
<input type="file" id="ImageSelector" onchange="ImageSelector_Change(this, 'Image');" /><br />
<img id="Image" src="#" style="width: 100px; visibility: hidden;" />
</div>
</div>
</div>
</div>
My finished code:
<!DOCTYPE html>
<html lang="en">
<head>
<!-- css links -->
<link href="/Content/bootstrap-theme.css" rel="stylesheet" />
<link href="/Content/bootstrap.css" rel="stylesheet" />
<link href="/Scripts/jquery-ui-1.12.0/jquery-ui.css" rel="stylesheet" />
<!-- /css links -->
<!-- js files -->
<script src="/Scripts/jquery-3.1.0.js"></script>
<script src="/Scripts/jquery-ui-1.12.0/jquery-ui.js"></script>
<!-- /js files -->
</head>
<body id="myPage" data-spy="scroll" data-target=".navbar" data-offset="60">
<script lang="en" type="text/javascript">
$(function () {
$("#PrimaryImageAccordion").accordion({
collapsible: true
});
});
</script>
<br /><br />
<button type='button' onclick='btnAddPrimaryImage_Click();' class='btn btn-default'> Add </button>
<div id="PrimaryImageAccordion">
<h4 class="PrimaryImageTitle">Primary Image</h4>
<div>
<div class="row form-group">
<label for="ImageSelector" class="control-label col-md-2">Project Image</label>
<div class="col-md-10">
<input type="file" id="ImageSelector" onchange="ImageSelector_Change(this);" /><br />
<img id="Image" src="#" style="width: 100px; visibility: hidden;" />
</div>
</div>
</div>
</div>
<script lang="en" type="text/javascript">
function btnAddPrimaryImage_Click() {
var template = "<h4 class='PrimaryImageTitle'>Primary Image<a onclick='removePanel(this);' style='float:right'>X</a></h4>\n";
template += "<div class='AccordionPanel'><div class='row form-group'>\n";
template += "<label for='ImageSelector' class='control-label col-md-2'>Project Image</label>\n";
template += "<div class='col-md-10'>\n";
template += "<input type='file' id='ImageSelector' onchange='ImageSelector_Change(this);' /><br />\n";
template += "<img id='Image' src='#' style='width: 100px; visibility: hidden;' />\n";
template += "</div></div></div>\n";
$("#PrimaryImageAccordion").append(template);
$("#PrimaryImageAccordion").accordion("refresh");
}
function removePanel(a) {
$(a).parent().next().remove();
$(a).parent().remove();
$("#PrimaryImageAccordion").accordion("refresh");
return false;
}
function ImageSelector_Change(input) {
var object = $(input).parent().find('img#Image');
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
object.attr("src", e.target.result);
object.css("visibility", "visible");
}
reader.readAsDataURL(input.files[0]);
}
}
</script>
</body>
</html>
Found out the hard way that when you add code to the first object (the accordion panel) you also have to add the same code to the template in order to make the image loader work :p.
I think you have to change this function parameters as single like this.
Because your onchange event fires this function with single parameter.
So it will receive the object but your trying to access the input which has the undefined value
Here take one global variable increment because as many times your clicking the button those many times DOM image element having the samaID
var vrImgeID=0;
function btnAddPrimaryImage_Click() {
var template = "<h4 class='PrimaryImageTitle'>Primary Image<a onclick='removePanel(this);' style='float:right'>X</a></h4>\n";
template += "<div class='AccordionPanel'><div class='row form-group'>\n";
template += "<label for='ImageSelector' class='control-label col-md-2'>Project Image</label>\n";
template += "<div class='col-md-10'>\n";
template += "<input type='file' id='Image1Selector' /><br />\n";
template += "<img id='Image"+vrImgeID+"' src='#' style='width: 100px; visibility: hidden;' />\n";
template += "</div></div></div>\n";
$("#PrimaryImageAccordion").append(template);
vrImgeID++;
$("#PrimaryImageAccordion").accordion("refresh");
}
function ImageSelector_Change(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
input.attr("src", e.target.result);
input.css("visibility", "visible");
}
reader.readAsDataURL(input.files[0]);
}
}

integrate text and image inside UI widget

hello I would like to know how I can add text and image inside a UI widget I also want it to be without a background please help I want to be able to write my own text and display while I'm writing it.
CSS
.thumbs img{
margin:3px;
width:50px;
float:left;
}
.bottlesWrapper img{
margin:3px;
width:400px;
float:left;
}
#main { border:1px solid #eee; margin:20px; width:410px; height:220px;}
HTML
<html>
<head>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>UI widget</title><link rel="stylesheet"
href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<link rel="stylesheet"
href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
</head>
<body>
<form method="post" action="<?php echo $PHP_SELF;?>">
<textarea rows="5" cols="20" name="quote" wrap="physical">Enter your favorite quote!</textarea><br />
<input type="submit" value="submit" name="submit">
</form>
<div id='main'>
<div class="bottlesWrapper">
<div id="dialog" class="ui-widget-content">
<?
echo "<i>".$quote."</i><br />";
?>
</div>
<img src="http://placehold.it/300x160/f1f" />
</div>
<div class="thumbs">
<img src="http://placehold.it/300x180/444" />
<img src="http://placehold.it/300x160/f1f" />
</div></div>
</body>
</html>
Script
$('.thumbs img').click(function() {
var thmb = this;
var src = this.src;
$(thmb).parent('.thumbs').prev('.bottlesWrapper').find('img').fadeout (400,function(){
thmb.src = this.src;
$(this).fadeIn(400)[0].src = src;
});
});
</script> <script>
$("#dialog").dialog({
open: function(event, ui) {
var vDlg = $(event.target).parent();
var vCont = $('#main');
vDlg.draggable("option", "containment", vCont).appendTo(vCont);
$(this).dialog("option", "position", "center");
}
});
https://jsfiddle.net/barronfidel7/c1yfj0wv/
Your working fiddle.
This is what allows you to see the HTML in the UI widget as you type:
$(document).ready(function(){
$('#dialog').html($('#quote').val());
$('#quote').on('keyup', function(){
$('#dialog').html($(this).val());
});
});
While the input has focus, it assigns the HTML of the widget to it's own value after every keyup event.

How to stop animation with jQuery timers?

I'm wondering how to stop an animation made with jQuery timers. I think I have tried everything, I would really like your help.
<!DOCTYPE html>
<html>
<head>
<meta content='yes' name='apple-mobile-web-app-capable'>
<meta content='default' name='apple-mobile-web-app-status-bar-style'>
<meta content='width=device-width, minimum-scale=1.0, maximum-scale=1.0' name='viewport'>
<title>HeartMath - Danmark</title>
<script src='http://code.jquery.com/jquery.min.js' type='text/javascript'></script>
<script src='http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.js' type='text/javascript'></script>
<script src='inc/jquery.timers-1.1.2.js' type='text/javascript'></script>
<script type="text/javascript" >
jQuery.fn.log = function (msg) {
console.log("%s: %o", msg, this);
return this;
}; var fixgeometry = function() {
/* Some orientation changes leave the scroll position at something
* that isn't 0,0. This is annoying for user experience. */
scroll(0, 0);
/* Calculate the geometry that our content area should take */
var header = $(".header:visible");
var footer = $(".footer:visible");
var content = $(".content:visible");
var viewport_height = $(window).height();
var content_height = viewport_height - header.outerHeight() - footer.outerHeight();;
/* Trim margin/border/padding height */
content_height -= (content.outerHeight() - content.height());
content.height(content_height);
}; /* fixgeometry */
$(document).ready(function() {
$(window).bind("orientationchange resize pageshow", fixgeometry);
var animationSpeed = 3500;
var animationHeight = $(window).height() * 0.70;
$("input[type='radio']").bind( "change", function(event, ui) {
if($(this).val() == "true") {
startAnimation(animationSpeed);
$(this).log("animationen burde starte");
}
else {
stopAnimation();
$(this).log("animationen burde stopppe");
}
}).log("der blev trykket");
function startAnimation(animationDuration) {
$(".breather").everyTime(10, function(){
$(".breather").animate({top:animationHeight}, animationDuration).animate({top:"0"}, animationDuration);
}).log("startAnimation");
};
function stopAnimation() {
$(".breather").stopTime().stop().log("stopAnimation");
};
});
</script>
<style type="text/css">
html, body {
width: 100%;
}
div.breather {
display: block;
position:relative;
}
}
</style>
<link href='http://code.jquery.com/mobile/1.0a2/jquery.mobile-1.0a2.min.css' rel='stylesheet'>
<link rel="stylesheet" type="text/css" href="jquery-mobile/hm-mobile-theme.css">
</head>
<body>
<div data-role='page' data-theme='a'>
<div class='header' id="header" data-role='header'> <img src="img/hm-logo.png" style="margin:0px auto;" height="40" /> </div>
<div class='content' data-role='content'>
<div class="breather">landscape!</div>
</div>
<div class='footer' data-role='footer'>
<div data-role="fieldcontain">
<fieldset data-role="controlgroup" data-type="horizontal">
<input type="radio" name="ignition" id="start" value="true" />
<label for="start">Start</label>
<input type="radio" name="ignition" id="stop" value="false" checked="checked" />
<label for="stop">Stop</label>
</fieldset>
</div>
</div>
</div>
</body>
</html>
What happens now is that when i press stop.. the animation just reverses and loops again
When you call .stop() to stop the jQuery animation, change it to .stop(true) to clear the animation queue (docs here). I'm not sure why there is a queue, but it looks like it has something to do with the timers plugin that you are using. Use queue().length to see how many animations are left in the queue.
Please make sure that the stopAnimation is being called by adding some debugging (console.log()). You call stopAnimation without an argument, but the function has an argument, that's not used.
So add some debugging to stopanimation and the if(val==false) statement. If that all works as expected we can continue the search.

Categories