How do I replace gradient with an image? - javascript

This code is meant to generate an ID Card with a picture
as the background. What should I use to replace the below line please?
co.fillRect(0.5,75.5,319,164.5)
Here is the full code
var c = document.getElementById('new')
var co = c.getContext('2d')
function save() {
datau = c.toDataURL('image/jpeg;base64;') //.replace("image/png", "image/octet-stream");
//window.location.href=datau
anchor = document.getElementById('download')
anchor.href = datau
anchor.innerHTML = ' Download'
}
function gene() {
sra = document.getElementById('srava').value
if (sra.length || des.length > 0) {
r = confirm("" + sra + ", Do you want to Update ID card?")
if (r == true) {
c = document.getElementById('new')
co = c.getContext('2d')
co.clearRect(0, 0, 320, 240)
init()
co.font = '20px Arial'
co.strokeText(sra, 50, 323)
idnu = Math.random() * 10000
co.font = '0px Arial'
co.fillStyle = '#000000'
co.fillText('ID:' + Math.round(idnu), 200, 100)
youphot = document.getElementById('uploadPreview')
co.drawImage(youphot, 100, 145, 149, 149)
document.getElementById('sav').disabled = false
} else {
document.write('Cancelled!')
}
} else {
alert('Fill the form')
}
}
function init() {
co.fillRect(0.5, 75.5, 319, 164.5)
}
init()
function first() {
co.font = '20px Arial'
co.strokeText(' ', 120, 325)
co.font = '15px Arial'
co.fillStyle = '#000000'
co.fillText(' ', 120, 325)
}
first()
function PreviewImage() {
var prr = new FileReader();
prr.readAsDataURL(document.getElementById("imagefile").files[0]);
prr.onload = function(ev) {
document.getElementById("uploadPreview").src = ev.target.result;
};
};
function rese() {
init()
first()
}
<div class='container'>
<canvas id='new' width='673' height='500' style='border:1px solid #fff;'>
</canvas>
<p>
<button id='sav' type="button" class="btn btn-default btn-sm" onClick=save(); disabled>
<span class="glyphicon glyphicon-floppy-disk"></span> Generate
</button>
</p>
<h3>Generate Membership ID</h3>
You may use blank space <b>" "</b> adjust your <b>Name</b> as you wish <br>
<input type='text' id='srava' placeholder='Your Full Name!' required/>
<p/> Passport Photograph:<br>
<input type='file' id='imagefile' onChange="PreviewImage();" />
<img id="uploadPreview" style="width: 20px; height: 20px:; border-radius: 50px" />
<p/>
<input type='button' id='upd' value='Inscribe!' onClick=gene();>
<input type='button' id='res' value='Reset' onClick=window.location.reload();>
</div>
I want picture as background instead of gradients.

Related

How to save canvas into database

Im doing a project which is web based abc tracing program.In my program,i should have a save button which will convert the drawing in canvas into image any automatically save the image in database.I dont know how to do this.I can convert the drawing into image but i dont know how to save into database.
This is my coding
html
<html>
<link href="https://fonts.googleapis.com/css?family=Playfair+Display+SC:700" rel="stylesheet" type="text/css" />
<link href="https://fonts.googleapis.com/css?family=Playball" rel="stylesheet" type="text/css" />
<link rel="stylesheet" type="text/css" href="cssdrawing.css">
<script src="a.js"></script>
<body>
<div style="background:A5F0FA;padding:10px;padding-bottom:20px">
<h1 style="font-family: 'Playfair Display SC', serif;text-align:center;margin-bottom:10px">Lets Trace!</h1>
<hr style="margin-bottom:15px;padding-top:0px;" width="500px" />
<center>
<div align="center" id="MainDiv" style="background:#FAA5EE;box-shadow:5px 5px 5px silver;padding:10px;max-width:90%;">
<canvas id="painter" height="300px" width="500" style="background: url('./images/vtr.jpg')"></canvas>
<br />
<div class="holder">
<span>Colors:</span>
<input type="button" style="background-color:FF0000;padding:10px 24px" onclick="Color('red')"></button>
<input type="button" style="background-color:0000FF;padding:10px 24px" onclick="Color('blue')"></button>
<input type="button" style="background-color:DE5616;padding:10px 24px" onclick="Color('brown')"></button>
<input type="button" style="background-color:FFFF00;padding:10px 24px" onclick="Color('yellow')"></button>
<input type="button" style="background-color:008000;padding:10px 24px" onclick="Color('green')"></button>
<input type="button" style="background-color:DE168F;padding:10px 24px" onclick="Color('pink')"></button>
<input id="color" type="color" onclick="Color(this.value)" onchange="Color(this.value)"></input>
<br /></div>
<div class="holder">
<span>Thickness:</span>
<input value="30" id="number" min="30" max="100" type="number"></input><br /></div>
<div class="holder">
<span>Other:</span>
<button onclick="Color('white')">Eraser</button>
<button onclick="ClearCanvas()">Clear Canvas</button>
<a id="download" download="img.jpg"><button type="button" onClick="download()">Save</button></a>
</div>
</div>
</center>
</div>
</body>
</html>
Javascript
function Color(a) {
var offset = function(obj) {
var curleft = 0, curtop = 0;
if (obj.offsetParent) {
do {
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
} while (obj = obj.offsetParent);
return { x: curleft, y: curtop };
}
return undefined;
}
var canvas = document.getElementById("painter");
var context = canvas.getContext("2d");
var draw = false;
var pos = offset(canvas);
canvas.onmousemove = function(e) {
if (draw == false) { return; }
var x = e.pageX - pos.x;
var y = e.pageY - pos.y;
console.log(x,y);
context.lineTo(x, y);
context.stroke();
}
canvas.onmousedown = function(e) {
draw = true;
var x = e.pageX - pos.x;
var y = e.pageY - pos.y;
context.fillStyle = "red";
context.beginPath();
context.moveTo(x, y);
context.lineWidth= document.getElementById("number").value;
context.strokeStyle=a;
}
canvas.onmouseup = function(e) {
draw = false;
}
}
function ClearCanvas() {
var c=document.getElementById("painter");
var ctx=c.getContext("2d");
ctx.clearRect(0,0,880,300);
}
function Preview() {
var canvas = document.getElementById("painter");
var dataUrl = canvas.toDataURL();
window.open(dataUrl, "", "width=880, height=300");
}
function download(){
var download = document.getElementById("download");
var image = document.getElementById("painter").toDataURL("image/jpg")
.replace("image/jpg", "image/octet-stream");
download.setAttribute("href", image);
//download.setAttribute("download","archive.jpg");
$.ajax({
method: 'POST',
url: 'photo_upload.php',
data: {
photo: photo
}
});
}
Send that dataUrl back to your server with an AJAX post
$.ajax({
type: "POST",
url: "photo_upload.php",
data: {photo : dataUrl}
})
.done(function(respond){console.log("done: "+respond);})
.fail(function(respond){console.log("fail");})
.always(function(respond){console.log("always");})
On the PHP side, save the incoming dataURL to a database:
<?php
$sql="insert into table_name(photo) values(:photo)";
// INSERT with named parameters
$conn = new PDO('mysql:host=localhost;dbname=myDB', "root", "myPassword");
$stmt = $conn->prepare($sql);
$stmt->bindValue(":photo",$_POST["photo"]);
$stmt->execute();
$affected_rows = $stmt->rowCount();
echo $affected_rows;
?>

Issue when trying to change font size and color in canvas

I'm trying to change my font size and color in my canvas on a photo. So you have to upload a photo before you're able to add text to the image. After you add the photo and add text, then you're able to change the color and font, but when trying to do so you have to re-submit or the changes are not applied. Any ideas on what is happening? Do I have to re-draw it when they change colors or font sizes? Thanks In advance.
HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input id="theText" type="text">
<button id="submit">Draw text on canvas</button>
<br>
<canvas id="canvas" width="1000" height="500" class="playable-canvas"></canvas>
<div id="image_div">
<h1> Choose an Image to Upload </h1>
<input type='file' name='img' id='uploadimage' />
</div>
<div class="playable-buttons">
  <input id="edit" type="button" value="Edit" />
  <input id="reset" type="button" value="Reset" />
</div>
<textarea id="code" class="playable-code">
ctx.filter = 'blur(0px)';
</textarea>
<!-- Change Font Size -->
<div class="radio">
<input type="radio" name="radio" id="size16" onclick="size16()" checked="">
<label for="size16"> Font Size 16 </label>
</div>
<div class="radio">
<input type="radio" name="radio" id="size20" onclick="size20()" >
<label for="size20"> Font Size 20 </label>
</div>
<div class="radio">
<input type="radio" name="radio" id="size25" onclick="size25()" >
<label for="size25"> Font Size 25 </label>
</div>
<div class="radio">
<input type="radio" name="radio"id="size30" onclick="size30()" >
<label for="size30"> Font Size 30</label>
</div>
<div class="radio">
<input type="radio" name="radio" id="size35" onclick="size35()" >
<label for="size35"> Font Size 35 </label>
</div>
<div class="radio">
<input type="radio" name="radio" id="size40" onclick="size40()" >
<label for="size40"> Font Size 40 </label>
</div>
<div class="radio">
<input type="radio" name="radio" id="size45" onclick="siz45()" >
<label for="size45"> Font Size 45 </label>
</div>
<div class="radio">
<input type="radio" name="radio" id="size50" onclick="size50()" >
<label for="size50"> Font Size 50 </label>
</div>
<Br>
<!-- Change Color on Text -->
<div class="col-lg-2 col-md-2 col-xs-12">
<div class="radio">
<input type="radio" name="radio" id="black" onclick="BlackText()" checked="">
<label for="radio1"> Black </label>
</div>
<div class="radio">
<input type="radio" name="radio" id="white" onclick="WhiteText()" >
<label for="radio1"> White </label>
</div>
<div class="radio">
<input type="radio" name="radio" id="yellow" onclick="YellowText()" >
<label for="radio1"> Yellow </label>
</div>
<div class="radio radio-primary">
<input type="radio" name="radio" id="blue" onclick="BlueText()" >
<label for="radio3"> Blue </label>
</div>
<div class="radio radio-success">
<input type="radio" name="radio" id="green" onclick="GreenText()" >
<label for="radio4"> Green </label>
</div>
<div class="radio radio-danger">
<input type="radio" name="radio"id="red" onclick="RedText()" >
<label for="radio6"> Red </label>
</div>
<div class="radio radio-warning">
<input type="radio" name="radio" id="orange" onclick="OrangeText()" >
<label for="radio7"> Orange </label>
</div>
<div class="radio radio-purple">
<input type="radio" name="radio"id="purple" onclick="PurpleText()" >
<label for="radio8"> Purple </label>
</div>
</div>
Javscript:
//===========================================================================================================================
// Javascript that loads Image into canvas
//===========================================================================================================================
var drawnImage;
function drawImage(ev) {
console.log(ev);
var ctx = document.getElementById('canvas').getContext('2d'),
img = new Image(),
f = document.getElementById("uploadimage").files[0],
url = window.URL || window.webkitURL,
src = url.createObjectURL(f);
img.src = src;
img.onload = function() {
drawnImage = img;
ctx.drawImage(img, 0, 0);
url.revokeObjectURL(src);
}
}
document.getElementById("uploadimage").addEventListener("change", drawImage, false);
//===========================================================================================================================
// Javascript for input in textbox
//===========================================================================================================================
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var textarea = document.getElementById('code');
var reset = document.getElementById('reset');
var edit = document.getElementById('edit');
var code = textarea.value;
function drawCanvas() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
eval(textarea.value);
drawImage();
}
reset.addEventListener('click', function() {
textarea.value = code;
drawCanvas();
});
edit.addEventListener('click', function() {
textarea.focus();
})
textarea.addEventListener('input', drawCanvas);
window.addEventListener('load', drawCanvas);
//===========================================================================================================================
// Javascript for Moving Text around.
//===========================================================================================================================
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var $canvas = $("#canvas");
var canvasOffset = $canvas.offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;
var scrollX = $canvas.scrollLeft();
var scrollY = $canvas.scrollTop();
var startX;
var startY;
var texts = [];
var selectedText = -1;
function draw() {
ctx.rect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < texts.length; i++) {
var text = texts[i];
// ctx.fillStyle = "blue";
ctx.fillText(text.text, text.x, text.y);
}
}
function redraw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(drawnImage, 0, 0);
draw();
}
function textHittest(x, y, textIndex) {
var text = texts[textIndex];
return (x >= text.x && x <= text.x + text.width && y >= text.y - text.height && y <= text.y);
}
function handleMouseDown(e) {
e.preventDefault();
startX = parseInt(e.clientX - offsetX);
startY = parseInt(e.clientY - offsetY);
for (var i = 0; i < texts.length; i++) {
if (textHittest(startX, startY, i)) {
selectedText = i;
}
}
}
function handleMouseUp(e) {
e.preventDefault();
selectedText = -1;
}
function handleMouseOut(e) {
e.preventDefault();
selectedText = -1;
}
function handleMouseMove(e) {
if (selectedText < 0) {
return;
}
e.preventDefault();
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
var dx = mouseX - startX;
var dy = mouseY - startY;
startX = mouseX;
startY = mouseY;
var text = texts[selectedText];
text.x += dx;
text.y += dy;
redraw();
}
$("#canvas").mousedown(function(e) {
handleMouseDown(e);
});
$("#canvas").mousemove(function(e) {
handleMouseMove(e);
});
$("#canvas").mouseup(function(e) {
handleMouseUp(e);
});
$("#canvas").mouseout(function(e) {
handleMouseOut(e);
});
$("#submit").click(function() {
var y = texts.length * 20 + 20;
var text = {
text: $("#theText").val(),
x: 20,
y: y
};
// ctx.font = "16px verdana";
text.width = ctx.measureText(text.text).width;
text.height = 16;
texts.push(text);
draw();
});
//===========================================================================================================================
// Javascript for Text Size :)
//===========================================================================================================================
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
function size16 () {
ctx.font = "16px verdana";
}
function size20 () {
ctx.font = "20px verdana";
}
function size25 () {
ctx.font = "25px verdana";
}
function size30 () {
ctx.font = "30px verdana";
}
function size35 () {
ctx.font = "35px verdana";
}
function size40 () {
ctx.font = "40px verdana";
}
function size45 () {
ctx.font = "45px verdana";
}
function size50 () {
ctx.font = "50px verdana";
}
//===========================================================================================================================
// Javascript for Drop down for Text Color :)
//===========================================================================================================================
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
function PurpleText () {
ctx.fillStyle= 'purple';
}
function BlackText () {
ctx.fillStyle= 'black';
}
function YellowText () {
ctx.fillStyle= 'yellow';
}
function OrangeText () {
ctx.fillStyle = "orange";
}
function BlueText () {
ctx.fillStyle= 'blue';
}
function WhiteText () {
ctx.fillStyle = "white";
}
function GreenText () {
ctx.fillStyle= 'green';
}
function RedText () {
ctx.fillStyle = "red";
}
You have either to draw again the canvans or draw (refresh) it continuosly every xxx milliseconds.

Editor controls for iText on double-click

How would I achieve displaying text editing controls on-click, like here for example (see: Add Text)? I've managed to incorporate some menu text editing controls before but would like to give this a go. I tried posting the code here but the JS/HTML/CSS snippet tool was breaking for me.
Thanks in advance!
Edited with answer:
// Add image from local
var canvas = new fabric.Canvas('c');
// display/hide controls on double click
fabric.util.addListener(canvas.upperCanvasEl, 'dblclick', function(e) {
if (canvas.findTarget(e)) {
let objType = canvas.findTarget(e).type;
if (objType === 'i-text') {
document.getElementById('textControls').hidden = false;
}
}
});
canvas.on('before:selection:cleared', function(e) {
document.getElementById('trash').hidden = true;
document.getElementById('forward').hidden = true;
document.getElementById('back').hidden = true;
if (e.target.type === 'i-text') {
document.getElementById('textControls').hidden = true;
}
});
document.getElementById('file').addEventListener("change", function(e) {
var file = e.target.files[0];
var reader = new FileReader();
reader.onload = function(f) {
var data = f.target.result;
fabric.Image.fromURL(data, function(img) {
var oImg = img.set({
left: 0,
top: 0,
angle: 00,
stroke: '#F0F0F0', //<-- set this
strokeWidth: 40 //<-- set this
}).scale(0.2);
canvas.add(oImg).renderAll();
//var a = canvas.setActiveObject(oImg);
var dataURL = canvas.toDataURL({
format: 'png',
quality: 1
});
});
};
reader.readAsDataURL(file);
});
// Delete selected object
window.deleteObject = function() {
canvas.getActiveObject().remove();
}
// Refresh page
function refresh() {
setTimeout(function() {
location.reload()
}, 100);
}
// Add text
function Addtext() {
canvas.add(new fabric.IText('Tap and Type', {
left: 50,
top: 100,
fontFamily: 'helvetica neue',
fill: '#333',
stroke: '#F0F0F0',
strokeWidth: 1,
fontSize: 45
}));
}
document.getElementById('text-color').onchange = function() {
canvas.getActiveObject().setFill(this.value);
canvas.renderAll();
};
document.getElementById('text-color').onchange = function() {
canvas.getActiveObject().setFill(this.value);
canvas.renderAll();
};
document.getElementById('text-bg-color').onchange = function() {
canvas.getActiveObject().setBackgroundColor(this.value);
canvas.renderAll();
};
document.getElementById('text-lines-bg-color').onchange = function() {
canvas.getActiveObject().setTextBackgroundColor(this.value);
canvas.renderAll();
};
document.getElementById('text-stroke-color').onchange = function() {
canvas.getActiveObject().setStroke(this.value);
canvas.renderAll();
};
document.getElementById('text-stroke-width').onchange = function() {
canvas.getActiveObject().setStrokeWidth(this.value);
canvas.renderAll();
};
document.getElementById('font-family').onchange = function() {
canvas.getActiveObject().setFontFamily(this.value);
canvas.renderAll();
};
document.getElementById('text-font-size').onchange = function() {
canvas.getActiveObject().setFontSize(this.value);
canvas.renderAll();
};
document.getElementById('text-line-height').onchange = function() {
canvas.getActiveObject().setLineHeight(this.value);
canvas.renderAll();
};
document.getElementById('text-align').onchange = function() {
canvas.getActiveObject().setTextAlign(this.value);
canvas.renderAll();
};
radios5 = document.getElementsByName("fonttype"); // wijzig naar button
for (var i = 0, max = radios5.length; i < max; i++) {
radios5[i].onclick = function() {
if (document.getElementById(this.id).checked == true) {
if (this.id == "text-cmd-bold") {
canvas.getActiveObject().set("fontWeight", "bold");
}
if (this.id == "text-cmd-italic") {
canvas.getActiveObject().set("fontStyle", "italic");
}
if (this.id == "text-cmd-underline") {
canvas.getActiveObject().set("textDecoration", "underline");
}
if (this.id == "text-cmd-linethrough") {
canvas.getActiveObject().set("textDecoration", "line-through");
}
if (this.id == "text-cmd-overline") {
canvas.getActiveObject().set("textDecoration", "overline");
}
} else {
if (this.id == "text-cmd-bold") {
canvas.getActiveObject().set("fontWeight", "");
}
if (this.id == "text-cmd-italic") {
canvas.getActiveObject().set("fontStyle", "");
}
if (this.id == "text-cmd-underline") {
canvas.getActiveObject().set("textDecoration", "");
}
if (this.id == "text-cmd-linethrough") {
canvas.getActiveObject().set("textDecoration", "");
}
if (this.id == "text-cmd-overline") {
canvas.getActiveObject().set("textDecoration", "");
}
}
canvas.renderAll();
}
}
// Send selected object to front or back
var selectedObject;
canvas.on('object:selected', function(event) {
selectedObject = event.target;
});
var sendSelectedObjectBack = function() {
canvas.sendToBack(selectedObject);
}
var sendSelectedObjectToFront = function() {
canvas.bringToFront(selectedObject);
}
body {
padding: 10px 10px 10px 10px;
font-family: "HelveticaNeue";
}
canvas {
border: 1px solid grey;
margin: 10px 0px 0px 0px;
}
.myFile {
position: relative;
overflow: hidden;
float: left;
clear: left;
}
.myFile input[type="file"] {
display: block;
position: absolute;
top: 0;
right: 0;
opacity: 0;
font-size: 30px;
filter: alpha(opacity=0);
}
.footerheader {
margin-top: 10px;
font-weight: bold;
}
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.min.js"></script>
Testing
<br>
<br>
<label class="myFile">
<button>+ Photo</button>
<input type="file" id="file" />
</label>
<button onclick="Addtext()">+ Text</button> / Selected Object:
<button id="trash" onClick="deleteObject()">Trash</button>
<button id="forward" onclick="sendSelectedObjectToFront()">Forward</button>
<button id="back" onclick="sendSelectedObjectBack()">Back</button> /
<button onclick="refresh()">Clear All</button>
<canvas id="c" width="800" height="600"></canvas>
<div id="textControls" hidden>
<h2>Test Text Controls</h2>
<div id="text-wrapper" style="margin-top: 10px" ng-show="getText()">
<div id="text-controls">
<input type="color" id="text-color" size="10">
<label for="font-family" style="display:inline-block">Font family:</label>
<select id="font-family">
<option value="arial">Arial</option>
<option value="helvetica" selected>Helvetica</option>
<option value="myriad pro">Myriad Pro</option>
<option value="delicious">Delicious</option>
<option value="verdana">Verdana</option>
<option value="georgia">Georgia</option>
<option value="courier">Courier</option>
<option value="comic sans ms">Comic Sans MS</option>
<option value="impact">Impact</option>
<option value="monaco">Monaco</option>
<option value="optima">Optima</option>
<option value="hoefler text">Hoefler Text</option>
<option value="plaster">Plaster</option>
<option value="engagement">Engagement</option>
</select>
<br>
<label for="text-align" style="display:inline-block">Text align:</label>
<select id="text-align">
<option value="left">Left</option>
<option value="center">Center</option>
<option value="right">Right</option>
<option value="justify">Justify</option>
</select>
<div>
<label for="text-bg-color">Background color:</label>
<input type="color" id="text-bg-color" size="10">
</div>
<div>
<label for="text-lines-bg-color">Background text color:</label>
<input type="color" id="text-lines-bg-color" size="10">
</div>
<div>
<label for="text-stroke-color">Stroke color:</label>
<input type="color" id="text-stroke-color">
</div>
<div>
<label for="text-stroke-width">Stroke width:</label>
<input type="range" value="1" min="1" max="5" id="text-stroke-width">
</div>
<div>
<label for="text-font-size">Font size:</label>
<input type="range" min="1" max="120" step="1" id="text-font-size">
</div>
<div>
<label for="text-line-height">Line height:</label>
<input type="range" min="0" max="10" step="0.1" id="text-line-height">
</div>
</div>
<div id="text-controls-additional">
<input type='checkbox' name='fonttype' id="text-cmd-bold"> Bold
<input type='checkbox' name='fonttype' id="text-cmd-italic"> Italic
<input type='checkbox' name='fonttype' id="text-cmd-underline"> Underline
<input type='checkbox' name='fonttype' id="text-cmd-linethrough"> Linethrough
<input type='checkbox' name='fonttype' id="text-cmd-overline"> Overline
</div>
<div class="footer">
<div class="footerheader">asdasd</div>
<ul>
<li>1</li>
<li>1</li>
<li>1</li>
</ul>
</div>
</div>
</div>
You could use fabric.util.addListener method to detect double click event on fabricjs canvas and upon double click you'd have to check whether you clicked on a text object (iText) or not, henceforth display the text editing controls accordingly.
fabric.util.addListener(canvas.upperCanvasEl, 'dblclick', function(e) {
if (canvas.findTarget(e)) {
let objType = canvas.findTarget(e).type;
if (objType === 'i-text') {
document.getElementById('textControls').hidden = false; //show controls
}
}
});
ᴅᴇᴍᴏ ⧩
// Add image from local
var canvas = new fabric.Canvas('c');
// display/hide controls on double click
fabric.util.addListener(canvas.upperCanvasEl, 'dblclick', function(e) {
if (canvas.findTarget(e)) {
let objType = canvas.findTarget(e).type;
if (objType === 'i-text') {
document.getElementById('textControls').hidden = false;
}
}
});
canvas.on('before:selection:cleared', function(e) {
document.getElementById('trash').hidden = true;
document.getElementById('forward').hidden = true;
document.getElementById('back').hidden = true;
if (e.target.type === 'i-text') {
document.getElementById('textControls').hidden = true;
}
});
document.getElementById('file').addEventListener("change", function(e) {
var file = e.target.files[0];
var reader = new FileReader();
reader.onload = function(f) {
var data = f.target.result;
fabric.Image.fromURL(data, function(img) {
var oImg = img.set({
left: 0,
top: 0,
angle: 00,
stroke: '#F0F0F0', //<-- set this
strokeWidth: 40 //<-- set this
}).scale(0.2);
canvas.add(oImg).renderAll();
//var a = canvas.setActiveObject(oImg);
var dataURL = canvas.toDataURL({
format: 'png',
quality: 1
});
});
};
reader.readAsDataURL(file);
});
// Delete selected object
window.deleteObject = function() {
canvas.getActiveObject().remove();
}
// Refresh page
function refresh() {
setTimeout(function() {
location.reload()
}, 100);
}
// Add text
function Addtext() {
canvas.add(new fabric.IText('Tap and Type', {
left: 50,
top: 100,
fontFamily: 'helvetica neue',
fill: '#333',
stroke: '#F0F0F0',
strokeWidth: 1,
fontSize: 45
}));
}
document.getElementById('text-color').onchange = function() {
canvas.getActiveObject().setFill(this.value);
canvas.renderAll();
};
document.getElementById('text-color').onchange = function() {
canvas.getActiveObject().setFill(this.value);
canvas.renderAll();
};
document.getElementById('text-bg-color').onchange = function() {
canvas.getActiveObject().setBackgroundColor(this.value);
canvas.renderAll();
};
document.getElementById('text-lines-bg-color').onchange = function() {
canvas.getActiveObject().setTextBackgroundColor(this.value);
canvas.renderAll();
};
document.getElementById('text-stroke-color').onchange = function() {
canvas.getActiveObject().setStroke(this.value);
canvas.renderAll();
};
document.getElementById('text-stroke-width').onchange = function() {
canvas.getActiveObject().setStrokeWidth(this.value);
canvas.renderAll();
};
document.getElementById('font-family').onchange = function() {
canvas.getActiveObject().setFontFamily(this.value);
canvas.renderAll();
};
document.getElementById('text-font-size').onchange = function() {
canvas.getActiveObject().setFontSize(this.value);
canvas.renderAll();
};
document.getElementById('text-line-height').onchange = function() {
canvas.getActiveObject().setLineHeight(this.value);
canvas.renderAll();
};
document.getElementById('text-align').onchange = function() {
canvas.getActiveObject().setTextAlign(this.value);
canvas.renderAll();
};
radios5 = document.getElementsByName("fonttype"); // wijzig naar button
for (var i = 0, max = radios5.length; i < max; i++) {
radios5[i].onclick = function() {
if (document.getElementById(this.id).checked == true) {
if (this.id == "text-cmd-bold") {
canvas.getActiveObject().set("fontWeight", "bold");
}
if (this.id == "text-cmd-italic") {
canvas.getActiveObject().set("fontStyle", "italic");
}
if (this.id == "text-cmd-underline") {
canvas.getActiveObject().set("textDecoration", "underline");
}
if (this.id == "text-cmd-linethrough") {
canvas.getActiveObject().set("textDecoration", "line-through");
}
if (this.id == "text-cmd-overline") {
canvas.getActiveObject().set("textDecoration", "overline");
}
} else {
if (this.id == "text-cmd-bold") {
canvas.getActiveObject().set("fontWeight", "");
}
if (this.id == "text-cmd-italic") {
canvas.getActiveObject().set("fontStyle", "");
}
if (this.id == "text-cmd-underline") {
canvas.getActiveObject().set("textDecoration", "");
}
if (this.id == "text-cmd-linethrough") {
canvas.getActiveObject().set("textDecoration", "");
}
if (this.id == "text-cmd-overline") {
canvas.getActiveObject().set("textDecoration", "");
}
}
canvas.renderAll();
}
}
// Send selected object to front or back
var selectedObject;
canvas.on('object:selected', function(event) {
selectedObject = event.target;
});
var sendSelectedObjectBack = function() {
canvas.sendToBack(selectedObject);
}
var sendSelectedObjectToFront = function() {
canvas.bringToFront(selectedObject);
}
body {
padding: 10px 10px 10px 10px;
font-family: "HelveticaNeue";
}
canvas {
border: 1px solid grey;
margin: 10px 0px 0px 0px;
}
.myFile {
position: relative;
overflow: hidden;
float: left;
clear: left;
}
.myFile input[type="file"] {
display: block;
position: absolute;
top: 0;
right: 0;
opacity: 0;
font-size: 30px;
filter: alpha(opacity=0);
}
.footerheader {
margin-top: 10px;
font-weight: bold;
}
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.min.js"></script>
Testing
<br>
<br>
<label class="myFile">
<button>+ Photo</button>
<input type="file" id="file" />
</label>
<button onclick="Addtext()">+ Text</button> / Selected Object:
<button id="trash" onClick="deleteObject()">Trash</button>
<button id="forward" onclick="sendSelectedObjectToFront()">Forward</button>
<button id="back" onclick="sendSelectedObjectBack()">Back</button> /
<button onclick="refresh()">Clear All</button>
<canvas id="c" width="800" height="600"></canvas>
<div id="textControls" hidden>
<h2>Test Text Controls</h2>
<div id="text-wrapper" style="margin-top: 10px" ng-show="getText()">
<div id="text-controls">
<input type="color" id="text-color" size="10">
<label for="font-family" style="display:inline-block">Font family:</label>
<select id="font-family">
<option value="arial">Arial</option>
<option value="helvetica" selected>Helvetica</option>
<option value="myriad pro">Myriad Pro</option>
<option value="delicious">Delicious</option>
<option value="verdana">Verdana</option>
<option value="georgia">Georgia</option>
<option value="courier">Courier</option>
<option value="comic sans ms">Comic Sans MS</option>
<option value="impact">Impact</option>
<option value="monaco">Monaco</option>
<option value="optima">Optima</option>
<option value="hoefler text">Hoefler Text</option>
<option value="plaster">Plaster</option>
<option value="engagement">Engagement</option>
</select>
<br>
<label for="text-align" style="display:inline-block">Text align:</label>
<select id="text-align">
<option value="left">Left</option>
<option value="center">Center</option>
<option value="right">Right</option>
<option value="justify">Justify</option>
</select>
<div>
<label for="text-bg-color">Background color:</label>
<input type="color" id="text-bg-color" size="10">
</div>
<div>
<label for="text-lines-bg-color">Background text color:</label>
<input type="color" id="text-lines-bg-color" size="10">
</div>
<div>
<label for="text-stroke-color">Stroke color:</label>
<input type="color" id="text-stroke-color">
</div>
<div>
<label for="text-stroke-width">Stroke width:</label>
<input type="range" value="1" min="1" max="5" id="text-stroke-width">
</div>
<div>
<label for="text-font-size">Font size:</label>
<input type="range" min="1" max="120" step="1" id="text-font-size">
</div>
<div>
<label for="text-line-height">Line height:</label>
<input type="range" min="0" max="10" step="0.1" id="text-line-height">
</div>
</div>
<div id="text-controls-additional">
<input type='checkbox' name='fonttype' id="text-cmd-bold"> Bold
<input type='checkbox' name='fonttype' id="text-cmd-italic"> Italic
<input type='checkbox' name='fonttype' id="text-cmd-underline"> Underline
<input type='checkbox' name='fonttype' id="text-cmd-linethrough"> Linethrough
<input type='checkbox' name='fonttype' id="text-cmd-overline"> Overline
</div>
<div class="footer">
<div class="footerheader">asdasd</div>
<ul>
<li>1</li>
<li>1</li>
<li>1</li>
</ul>
</div>
</div>
</div>

How to set to 100% and reset to 0% progress bar

I want to work my progress bar to certain percentage on each click. Now its is working only up to 75%. On saving it should show 100% but it doesn't showing that.
Similarly by clicking back button it is going upto 25% on it should reset to 0% on clicking back button third time.
HTML
<div id="myProgressbar" class="progress" style="height: 2px;">
<div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%; height: 10px;">
<span class="sr-only">0% Complete</span>
</div>
</div>
<div class="btns">
<button type="button" name="sub" id="back" class="btn btn-default btn-lg" onclick="myFunctions()">back</button>
<button type="button" name="add" id="continue" class="btn btn-success btn-lg" onclick="myFunction()" >Continue</button>
</div>
<form action="/action_page.php" id="person" class="form-inline">
<div class="form-group">
<label for="fname">First Name:<input type="text" class="form-control" id="fname" placeholder="First Name" required="" title="First Name"></label>
</div>
<div class="form-group">
<label for="mname">Middle Name:<input type="text" class="form-control" id="mname" placeholder="Middle Name" title="Middle Name"></label>
</div>
<div class="form-group">
<label for="lname">Last name:<input type="text" class="form-control" id="lname" placeholder="Last Name" title="Last Name"></label>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<form action="/action_page.php" id="details" class="form-inline">
<div class="form-group">
<label for="address">Address:<input type="text" class="form-control" rows="5" id="address" placeholder="Enter Address" title="Address"></label>
</div>
<div class="form-group">
<label for="city">City:<input type="text" class="form-control" id="city" placeholder="Enter City"></label>
</div>
<div class="form-group">
<label for="pin">Pin Code:<input type="text" class="form-control" id="pin" placeholder="Enter Pincode"></label>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<form action="/action_page.php" id="account" class="form-inline">
<div class="form-group">
<label for="pis">PIS:<input type="text" class="form-control" id="pis" placeholder="PIS"></label>
</div>
<div class="form-group">
<label for="psp">PSP:<input type="text" class="form-control" id="psp" placeholder="PSP"></label>
</div>
<div class="form-group">
<label for="ped">PED:<input type="text" class="form-control" id="ped" placeholder="PED"></label>
</div>
<div class="form-group">
<label for="pno">PNO:<input type="text" class="form-control" id="pno" placeholder="PNO"></label>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<form action="/action_page.php" id="premium" class="form-inline">
<div class="form-group">
<label for="pis">IPU:<input type="text" class="form-control" id="pis" placeholder="PIS"></label>
</div>
<div class="form-group">
<label for="psp">NCB:<input type="text" class="form-control" id="psp" placeholder="PSP"></label>
</div>
<div class="form-group">
<label for="ped">TP REF:<input type="text" class="form-control" id="ped" placeholder="PED"></label>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<div class="btns">
<button type="button" name="sub" id="back" class="btn btn-default btn-lg" onclick="myFunctions()">back</button>
<button type="button" name="add" id="continue" class="btn btn-success btn-lg" onclick="myFunction()" >Continue</button>
</div>
Javascript
<script>
var num = 1;
document.getElementById("back").disabled = true;
document.getElementById("details").style.display="none";
document.getElementById("person").style.display="block";
document.getElementById("account").style.display="none";
document.getElementById("premium").style.display="none";
function myFunction() {
var listArry = document.getElementsByClassName('list');
for(var i = 0; i < listArry.length; i++){
listArry[i].style.color = "#CCC";
}
if (num==1){
document.getElementById('navlnk1').style.color = "black";
document.getElementById('navlnk').style.color = "#CCC";
document.getElementById("back").disabled = false;
document.getElementById("person").style.display="none";
document.getElementById("details").style.display="block";
var elem = document.getElementById("myProgressbar");
var width = 10;
var id = setInterval(frame, 10);
function frame() {
if (width >= 25) {
clearInterval(id);
} else {
width++;
document.getElementById("myProgressbar").style.backgroundColor = "#0FA561";
elem.style.width = width + '%';
elem.innerHTML = width * 1 + '%';
}
}
num=2;
}
else if(num==2){
document.getElementById('navlnk2').style.color = "black";
document.getElementById("details").style.display="none";
document.getElementById("account").style.display="block";
var elem = document.getElementById("myProgressbar");
var width = 10;
var id = setInterval(frame, 10);
function frame() {
if (width >= 50) {
clearInterval(id);
} else {
width++;
elem.style.width = width + '%';
elem.innerHTML = width * 1 + '%';
}
}
num=3;
}
else if(num==3){
document.getElementById('navlnk3').style.color = "black";
document.getElementById("account").style.display="none";
document.getElementById("premium").style.display="block";
document.getElementById('continue').innerHTML = "Save";
var elem = document.getElementById("myProgressbar");
var width = 10;
var id = setInterval(frame, 10);
function frame() {
if (width >= 75) {
clearInterval(id);
} else {
width++;
elem.style.width = width + '%';
elem.innerHTML = width * 1 + '%';
}
}
}
}
</script>
<script>
var num = 1;
function myFunctions() {
var listArry = document.getElementsByClassName('list');
for(var i = listArry.length; i >0; i--){
}
if (num==3){
document.getElementById('navlnk2').style.color = "black";
document.getElementById('navlnk3').style.color = "#CCC";
document.getElementById('navlnk1').style.color = "#CCC";
document.getElementById('navlnk').style.color = "#CCC";
document.getElementById("premium").style.display="none";
document.getElementById("account").style.display="block";
document.getElementById('continue').innerHTML = "Continue";
var elem = document.getElementById("myProgressbar");
var width = 10;
var id = setInterval(frame, 10);
function frame() {
if (width >= 50) {
clearInterval(id);
} else {
width++;
document.getElementById("myProgressbar").style.backgroundColor = "#0FA561";
elem.style.width = width + '%';
elem.innerHTML = width * 1 + '%';
}
}
num=2;
}
else if (num==2){
document.getElementById('navlnk1').style.color = "black";
document.getElementById('navlnk').style.color = "#CCC";
document.getElementById('navlnk2').style.color = "#CCC";
document.getElementById("account").style.display="none";
document.getElementById("details").style.display="block";
var elem = document.getElementById("myProgressbar");
var width = 10;
var id = setInterval(frame, 10);
function frame() {
if (width >= 25) {
clearInterval(id);
} else {
width++;
document.getElementById("myProgressbar").style.backgroundColor = "#0FA561";
elem.style.width = width + '%';
elem.innerHTML = width * 1 + '%';
}
}
num=1;
}
else if(num==1){
document.getElementById('navlnk').style.color = "black";
document.getElementById('navlnk1').style.color = "#CCC";
document.getElementById("details").style.display="none";
document.getElementById("person").style.display="block";
document.getElementById("back").disabled = true;
}
}
</script>
<script>
var num = 1;
function myFunctions() {
var listArry = document.getElementsByClassName('list');
for(var i = listArry.length; i >0; i--){
}
if (num==3){
document.getElementById('navlnk2').style.color = "black";
document.getElementById('navlnk3').style.color = "#CCC";
document.getElementById('navlnk1').style.color = "#CCC";
document.getElementById('navlnk').style.color = "#CCC";
document.getElementById("premium").style.display="none";
document.getElementById("account").style.display="block";
document.getElementById('continue').innerHTML = "Continue";
var elem = document.getElementById("myProgressbar");
var width = 10;
var id = setInterval(frame, 10);
function frame() {
if (width >= 50) {
clearInterval(id);
} else {
width++;
document.getElementById("myProgressbar").style.backgroundColor = "#0FA561";
elem.style.width = width + '%';
elem.innerHTML = width * 1 + '%';
}
}
num=2;
}
else if (num==2){
document.getElementById('navlnk1').style.color = "black";
document.getElementById('navlnk').style.color = "#CCC";
document.getElementById('navlnk2').style.color = "#CCC";
document.getElementById("account").style.display="none";
document.getElementById("details").style.display="block";
var elem = document.getElementById("myProgressbar");
var width = 10;
var id = setInterval(frame, 10);
function frame() {
if (width >= 25) {
clearInterval(id);
} else {
width++;
document.getElementById("myProgressbar").style.backgroundColor = "#0FA561";
elem.style.width = width + '%';
elem.innerHTML = width * 1 + '%';
}
}
num=1;
}
else if(num==1){
document.getElementById('navlnk').style.color = "black";
document.getElementById('navlnk1').style.color = "#CCC";
document.getElementById("details").style.display="none";
document.getElementById("person").style.display="block";
document.getElementById("back").disabled = true;
}
}
</script>
Hi i have tried workaround for your requirement... Please try it and let us know.
var width = 40;
function move(data) {
var elem = document.getElementById("myBar");
if(data == 'back' && width != 0){
width = width-10;
elem.style.width = width + '%';
}else if(data == 'continue' && width != 100){
width = width+10;
elem.style.width = width + '%';
}
}
<!DOCTYPE html>
<html>
<style>
#myProgress {
width: 100%;
background-color: #ddd;
}
#myBar {
width: 40%;
height: 30px;
background-color: #4CAF50;
}
</style>
<body>
<h1>JavaScript Progress Bar</h1>
<div id="myProgress">
<div id="myBar"></div>
</div>
<br>
<button onclick="move('back')">Back</button>
<button onclick="move('continue')">Continue</button>
</body>
</html>

Unable to tigger elements inside the webui-popover

I am working on a app dashboard, where I am trying to add a jquery calculator inside webui-popover. the calculator is working fine outside the popover but when it is inside the popover div it is not working. The plugin author said "This problem is caused by that the plugin stop the event bubbling",
I do not have much knowledge about Jquery or Javascript, If anyone can help me with this it will be nice. So, is there any way to make the calculator work inside popover element?.
Calculator Script taken from HERE
Here is the codes
/* WEBUI SCRIPT*/
(function() {
var settings = {
trigger: 'click',
title: '',
width: 320,
multi: true,
closeable: false,
style: '',
delay: 300,
padding: true
};
function initPopover() {
var tableContent = $('#discalc').html(),
tableSettings = {
content: tableContent,
width: 298
};
$('a.showdisclac').webuiPopover('destroy').webuiPopover($.extend({}, settings, tableSettings));
}
initPopover();
})();
/* CALCULATOR */
$("document").ready(function() {
var key = null;
$(document).on("click", ".clean", function() {
$('.input').val("");
});
$(document).on("click", ".Show", function() {
var EText = $('#Result').val();
if (EText != "0") {
var val1 = EText;
var ButtonVal = $(this);
var val2 = ButtonVal.text();
var Res = val1 + val2;
$('#Result').val(Res);
} else {
$('#Result').val();
}
});
$(function(e) {
var interRes = null;
var operator;
$(document).on("click", ".operators", function(e) {
var value1 = $('#Result').val();
if (interRes != null) {
var result = ApplyOperation(interRes, value1, operator);
interRes = result;
} else {
interRes = value1;
}
operator = $(this).text();
$('input').val("");
});
$(document).on("keypress", "#Result", function(e) {
if ((e.keyCode == 61)) {
var op = operator;
var res;
var value2 = $('#Result').val();
if ((value2 != "")) {
var data = value2.split("+");
if (data.length > 2) res = ApplyOperation(interRes, data[data.length - 1], op);
else res = ApplyOperation(interRes, data[1], op);
} else {
res = interRes;
}
$('#Result').val(res);
interRes = null;
} else if ((e.keyCode == 43) || (e.keyCode == 45) || (e.keyCode == 42) || (e.keyCode == 47)) {
var value1 = $('#Result').val();
var inter = (interRes != null);
if (inter) {
var op = operator;
var data = value1.split("+");
if (data.length > 2) {
operator = String.fromCharCode(e.keyCode);
result = ApplyOperation(interRes, data[data.length - 1], op);
interRes = result;
} else {
operator = String.fromCharCode(e.keyCode);
result = ApplyOperation(interRes, data[1], op);
interRes = result;
}
} else {
interRes = value1;
}
operator = String.fromCharCode(e.keyCode);
$('.input').text("");
}
});
$(document).on("click", "#Calculate", function(e) {
var op = operator;
var res;
var value2 = $('#Result').val();
if ((value2 != "")) {
res = ApplyOperation(interRes, value2, op);
} else {
res = interRes;
}
$('#Result').val(res);
interRes = null;
});
});
function ApplyOperation(value1, value2, operator) {
var res;
switch (operator) {
case "+":
res = addition(value1, value2);
break;
case "-":
res = subtraction(value1, value2);
break;
case "*":
res = multiplication(value1, value2);
break;
case "/":
res = division(value1, value2);
break;
}
return res;
}
function addition(first, second) {
var a = parseFloat(first);
var b = parseFloat(second);
var total = a + b;
return total;
}
function subtraction(first, second) {
var a = parseFloat(first);
var b = parseFloat(second);
var sub = a - b;
return sub;
}
function multiplication(first, second) {
var a = parseFloat(first);
var b = parseFloat(second);
var product = a * b;
return product;
}
function division(first, second) {
var a = parseFloat(first);
var b = parseFloat(second);
var divi = a / b;
return divi;
}
});
<link rel="stylesheet" type="text/css" href="http://sandywalker.github.io/webui-popover/dist/jquery.webui-popover.min.css"> .webui-popover-content {
padding: 0;
}
.webui-popover {
padding: 0;
border: none;
border: 0;
background: transparent;
-webkit-box-shadow: none;
-moz-box-shadow: none;
-ms-box-shadow: none;
-o-box-shadow: none;
box-shadow: none;
}
.webui-popover.top>.arrow:after,
.webui-popover.top-right>.arrow:after,
.webui-popover.top-left>.arrow:after {
border-top-color: #525252;
}
.discalc {
display: none;
}
.disresform {
background: #525252;
padding: 20px 5px 20px 5px;
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
-ms-border-radius: 6px;
-o-border-radius: 6px;
border-radius: 6px;
bottom: 0;
position: absolute;
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://sandywalker.github.io/webui-popover/dist/jquery.webui-popover.min.js"></script>
Discount
<div id="discalc" class="discalc">
<div class="disresform">
<h2>Simple Calculator</h2>
<input id="Result" class="input" value="0" />
<div id="keys">
<div id="FirstRow">
<button id="ClearAll" type="reset" value="CE" class="clean">CE</button>
<button id="Clear" type="reset" value="C" class="clean">C</button>
<button id="Add" type="button" value="+" class="operators operand">+</button>
</div>
<div id="SecondRow">
<button id="One" type="button" value="1" class="Show">1</button>
<button id="Two" type="button" value="2" class="Show">2</button>
<button id="Three" type="button" value="3" class="Show">3</button>
<button id="Sub" type="button" value="-" class="operators operand">-</button>
</div>
<div id="ThirdRow">
<button id="Four" type="button" value="4" class="Show">4</button>
<button id="Five" type="button" value="5" class="Show">5</button>
<button id="six" type="button" value="6" class="Show">6</button>
<button id="Mul" type="button" value="*" class="operators operand">*</button>
</div>
<div id="FourthRow">
<button id="Seven" type="button" value="7" class="Show">7</button>
<button id="Eight" type="button" value="8" class="Show">8</button>
<button id="Nine" type="button" value="9" class="Show">9</button>
<button id="Divide" type="button" value="/" class="operators operand">/</button>
</div>
<div id="FifthRow">
<button id="Zero" type="button" value="0" class="Show">0</button>
<button id="Dot" type="button" value="." class="Show">.</button>
<button id="Calculate" type="button" value="=" class="operand">=</button>
</div>
</div>
</div>
</div>
Use dismissible:false
/* WEBUI SCRIPT*/
(function() {
var settings = {
trigger: 'click',
title: '',
width: 320,
multi: true,
closeable: false,
style: '',
delay: 300,
padding: true,
dismissible:false
};
function initPopover() {
var tableContent = $('#discalc').html(),
tableSettings = {
content: tableContent,
width: 298
};
$('a.showdisclac').webuiPopover('destroy').webuiPopover($.extend({}, settings, tableSettings));
}
initPopover();
})();
/* CALCULATOR */
$("document").ready(function() {
var key = null;
$(document).on("click", ".clean", function() {
$('.input').val("");
});
$(document).on("click", ".Show", function() {
var EText = $('#Result').val();
if (EText != "0") {
var val1 = EText;
var ButtonVal = $(this);
var val2 = ButtonVal.text();
var Res = val1 + val2;
$('#Result').val(Res);
} else {
$('#Result').val();
}
});
$(function(e) {
var interRes = null;
var operator;
$(document).on("click", ".operators", function(e) {
var value1 = $('#Result').val();
if (interRes != null) {
var result = ApplyOperation(interRes, value1, operator);
interRes = result;
} else {
interRes = value1;
}
operator = $(this).text();
$('input').val("");
});
$(document).on("keypress", "#Result", function(e) {
if ((e.keyCode == 61)) {
var op = operator;
var res;
var value2 = $('#Result').val();
if ((value2 != "")) {
var data = value2.split("+");
if (data.length > 2) res = ApplyOperation(interRes, data[data.length - 1], op);
else res = ApplyOperation(interRes, data[1], op);
} else {
res = interRes;
}
$('#Result').val(res);
interRes = null;
} else if ((e.keyCode == 43) || (e.keyCode == 45) || (e.keyCode == 42) || (e.keyCode == 47)) {
var value1 = $('#Result').val();
var inter = (interRes != null);
if (inter) {
var op = operator;
var data = value1.split("+");
if (data.length > 2) {
operator = String.fromCharCode(e.keyCode);
result = ApplyOperation(interRes, data[data.length - 1], op);
interRes = result;
} else {
operator = String.fromCharCode(e.keyCode);
result = ApplyOperation(interRes, data[1], op);
interRes = result;
}
} else {
interRes = value1;
}
operator = String.fromCharCode(e.keyCode);
$('.input').text("");
}
});
$(document).on("click", "#Calculate", function(e) {
var op = operator;
var res;
var value2 = $('#Result').val();
if ((value2 != "")) {
res = ApplyOperation(interRes, value2, op);
} else {
res = interRes;
}
$('#Result').val(res);
interRes = null;
});
});
function ApplyOperation(value1, value2, operator) {
var res;
switch (operator) {
case "+":
res = addition(value1, value2);
break;
case "-":
res = subtraction(value1, value2);
break;
case "*":
res = multiplication(value1, value2);
break;
case "/":
res = division(value1, value2);
break;
}
return res;
}
function addition(first, second) {
var a = parseFloat(first);
var b = parseFloat(second);
var total = a + b;
return total;
}
function subtraction(first, second) {
var a = parseFloat(first);
var b = parseFloat(second);
var sub = a - b;
return sub;
}
function multiplication(first, second) {
var a = parseFloat(first);
var b = parseFloat(second);
var product = a * b;
return product;
}
function division(first, second) {
var a = parseFloat(first);
var b = parseFloat(second);
var divi = a / b;
return divi;
}
});
<link rel="stylesheet" type="text/css" href="http://sandywalker.github.io/webui-popover/dist/jquery.webui-popover.min.css"> .webui-popover-content {
padding: 0;
}
.webui-popover {
padding: 0;
border: none;
border: 0;
background: transparent;
-webkit-box-shadow: none;
-moz-box-shadow: none;
-ms-box-shadow: none;
-o-box-shadow: none;
box-shadow: none;
}
.webui-popover.top>.arrow:after,
.webui-popover.top-right>.arrow:after,
.webui-popover.top-left>.arrow:after {
border-top-color: #525252;
}
.discalc {
display: none;
}
.disresform {
background: #525252;
padding: 20px 5px 20px 5px;
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
-ms-border-radius: 6px;
-o-border-radius: 6px;
border-radius: 6px;
bottom: 0;
position: absolute;
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://sandywalker.github.io/webui-popover/dist/jquery.webui-popover.min.js"></script>
Discount
<div id="discalc" class="discalc">
<div class="disresform">
<h2>Simple Calculator</h2>
<input id="Result" class="input" value="0" />
<div id="keys">
<div id="FirstRow">
<button id="ClearAll" type="reset" value="CE" class="clean">CE</button>
<button id="Clear" type="reset" value="C" class="clean">C</button>
<button id="Add" type="button" value="+" class="operators operand">+</button>
</div>
<div id="SecondRow">
<button id="One" type="button" value="1" class="Show">1</button>
<button id="Two" type="button" value="2" class="Show">2</button>
<button id="Three" type="button" value="3" class="Show">3</button>
<button id="Sub" type="button" value="-" class="operators operand">-</button>
</div>
<div id="ThirdRow">
<button id="Four" type="button" value="4" class="Show">4</button>
<button id="Five" type="button" value="5" class="Show">5</button>
<button id="six" type="button" value="6" class="Show">6</button>
<button id="Mul" type="button" value="*" class="operators operand">*</button>
</div>
<div id="FourthRow">
<button id="Seven" type="button" value="7" class="Show">7</button>
<button id="Eight" type="button" value="8" class="Show">8</button>
<button id="Nine" type="button" value="9" class="Show">9</button>
<button id="Divide" type="button" value="/" class="operators operand">/</button>
</div>
<div id="FifthRow">
<button id="Zero" type="button" value="0" class="Show">0</button>
<button id="Dot" type="button" value="." class="Show">.</button>
<button id="Calculate" type="button" value="=" class="operand">=</button>
</div>
</div>
</div>
</div>

Categories