Js function working only once - javascript

I'm working on a simple javascript photo editor, and I'm stuck on this part:
var opacity = document.getElementById("opacity").value;
var contrast = document.getElementById("contrast").value;
var saturate = document.getElementById("saturate").value;
var brightness = document.getElementById("brightness").value;
var color = document.getElementById("color").value;
var sepia = document.getElementById("sepia").value;
function filter() {
document.getElementById("output").style.filter = "hue-rotate(" + color + "deg) sepia(" + sepia + "%) brightness(" + brightness * 3 + "%) saturate(" + saturate + "%) contrast(" + contrast * 2 + "%)";
}
var filters = document.getElementsByClassName("slider");
for (i = 0; i < filters.length; i++) {
filters[i].addEventListener("click", filter);
}
This function works only once. Similar function for opacity:
function opacity() {
var a = document.getElementById("opacity").value;
document.getElementById("output").style.opacity = a / 10;
}
document.getElementById("opacity").addEventListener("change", opacity);
works fine. Any ideas why? I tried doing it this way:
/*
function contrast() {
var b = document.getElementById("contrast").value;
document.getElementById("output").style.filter = "contrast(" + b * 2 + "%)";
}
document.getElementById("contrast").addEventListener("change", contrast);
function saturate() {
var c = document.getElementById("saturate").value;
document.getElementById("output").style.filter = "saturate(" + c + "%)";
}
document.getElementById("saturate").addEventListener("change", saturate);
function brightness() {
var d = document.getElementById("brightness").value;
document.getElementById("output").style.filter = "brightness(" + d * 3 + "%)";
}
document.getElementById("brightness").addEventListener("change", brightness);
function color() {
var e = document.getElementById("color").value;
document.getElementById("output").style.filter = "hue-rotate(" + e + "deg)";
}
document.getElementById("color").addEventListener("change", color);
function sepia() {
var f = document.getElementById("sepia").value;
document.getElementById("output").style.filter = "sepia(" + c + "%)";
}
document.getElementById("sepia").addEventListener("change", sepia);
/*
And everything is ok, but then I'm unable to apply multiple filters. Any help appreciated!

You have to get the value every time you click
var contrast = document.getElementById("contrast");
var saturate = document.getElementById("saturate");
var brightness = document.getElementById("brightness");
var color = document.getElementById("color");
var sepia = document.getElementById("sepia");
function filter() {
//You have to convert to number to do arithmetic
var _brightness = ~~brightness.value;
document.getElementById("output").style.filter = "hue-rotate(" + color.value + "deg) sepia(" + sepia.value + "%) brightness(" + _brightness * 3 + "%) saturate(" + saturate.value + "%) contrast(" + contrast.value * 2 + "%)";
}
and so on

Related

Photoshop script to get image layer transform information(not bounds)

the bounds of this image
I can get the bounds by the activeLayer.layer.bounds[0]. but it's not include transparent area
and the information what i need is:
2
how can i get it.
This is an old script (from 2010) by pattesdours, hopefully it will give you want you are after:
// This script exports extended layer.bounds information
// by pattesdours
// Switch off any dialog boxes
displayDialogs = DialogModes.NO; // OFF
var srcDoc = activeDocument;
var docWidth = srcDoc.width.value;
var docHeight = srcDoc.height.value;
var theLayer = activeDocument.activeLayer;
var layerData = cLayer(srcDoc, theLayer);
var str = theLayer.name + "\n"
+ "pos " + leftTop + "\n"
+ "width " + layerData.layerWidth + "\n"
+ "height " + layerData.layerHeight + "\n" + "\n"
alert(str);
displayDialogs = DialogModes.ALL; // ON
// class using a contructor
function cLayer(doc, layer)
{
this.layerWidth = layer.bounds[2].value - layer.bounds[0].value;
this.layerHeight = layer.bounds[3].value - layer.bounds[1].value;
// these return object coordinates relative to canvas
this.upperLeftX = layer.bounds[0].value;
this.upperLeftY = layer.bounds[1].value;
this.upperCenterX = this.layerWidth / 2 + layer.bounds[0].value;
this.upperCenterY = layer.bounds[1].value;
this.upperRightX = layer.bounds[2].value;
this.upperRightY = layer.bounds[1].value;
this.middleLeftX = layer.bounds[0].value;
this.middleLeftY = this.layerHeight / 2 + layer.bounds[1].value;
this.middleCenterX = this.layerWidth / 2 + layer.bounds[0].value;
this.middleCenterY = this.layerHeight / 2 + layer.bounds[1].value;
this.middleRightX = layer.bounds[2].value;
this.middleRightY = this.layerHeight / 2 + layer.bounds[1].value;
this.lowerLeftX = layer.bounds[0].value;
this.lowerLeftY = layer.bounds[3].value;
this.lowerCenterX = this.layerWidth / 2 + layer.bounds[0].value;
this.lowerCenterY = layer.bounds[3].value;
this.lowerRightX = layer.bounds[2].value;
this.lowerRightY = layer.bounds[3].value;
// I'm adding these for easier editing of flash symbol transformation point (outputs a 'x, y' format)
// because I like to assign shortcut keys that use the numeric pad keyboard, like such:
// 7 8 9
// 4 5 6
// 1 2 3
//
this.leftBottom = this.lowerLeftX + ", " + this.lowerLeftY;
this.bottomCenter = this.lowerCenterX + ", " + this.lowerCenterY;
this.rightBottom = this.lowerRightX + ", " + this.lowerRightY;
this.leftCenter = this.middleLeftX + ", " + this.middleLeftY;
this.center = this.middleCenterX + ", " + this.middleCenterY;
this.rightCenter = this.middleRightX + ", " + this.middleRightY;
this.leftTop = this.upperLeftX + ", " + this.upperLeftY;
this.topCenter = this.upperCenterX + ", " + this.upperCenterY;
this.rightTop = this.upperRightX + ", " + this.upperRightY;
// these return object coordinates relative to layer bounds
this.relUpperLeftX = layer.bounds[1].value - layer.bounds[1].value;
this.relUpperLeftY = layer.bounds[0].value - layer.bounds[0].value;
this.relUpperCenterX = this.layerWidth / 2;
this.relUpperCenterY = layer.bounds[0].value - layer.bounds[0].value;
this.relUpperRightX = this.layerWidth;
this.relUpperRightY = layer.bounds[0].value - layer.bounds[0].value;
this.relMiddleLeftX = layer.bounds[1].value - layer.bounds[1].value;
this.relMiddleLeftY = this.layerHeight / 2;
this.relMiddleCenterX = this.layerWidth / 2;
this.relMiddleCenterY = this.layerHeight / 2;
this.relMiddleRightX = this.layerWidth;
this.relMiddleRightY = this.layerHeight / 2;
this.relLowerLeftX = layer.bounds[1].value - layer.bounds[1].value;
this.relLowerLeftY = this.layerHeight;
this.relLowerCenterX = this.layerWidth / 2;
this.relLowerCenterY = this.layerHeight / 2;
this.relLowerRightY = this.layerHeight;
this.relLowerRightX = this.layerWidth;
this.relLowerRightY = this.layerHeight;
return this;
}

is there a way to use a variable from one function to another? -Javascript

function GradingScheme()
{
var quiz1, quiz2, quiz3, ass1, ass2, lab1, lab2, lab3, pegrade;
quiz1 = parseFloat(document.getElementById("quiz1").value);
quiz2 = parseFloat(document.getElementById("quiz2").value);
quiz3 = parseFloat(document.getElementById("quiz3").value);
ass1 = parseFloat(document.getElementById("ass1").value);
ass2 = parseFloat(document.getElementById("ass2").value);
lab1 = parseFloat(document.getElementById("lab1").value);
lab2 = parseFloat(document.getElementById("lab2").value);
lab3 = parseFloat(document.getElementById("lab3").value);
pegrade = parseFloat(document.getElementById("pegrade").value);
quiz4 = ((quiz1 + quiz2 + quiz3) / 3 );
ass3 = ((ass1 + ass2) / 2 );
lab4 = ((lab1 + lab2 + lab3) / 3 );
var cs = ((quiz4 * 0.60) + (ass3 * 0.20) + (lab4 * 0.20) );
var pg = (cs*.50) + (pegrade*.50);
document.getElementById("demo").innerHTML = "Your Prelim grade is: " + pg.toFixed(1);
}
function MIDTERM()
{
quiz1 = parseFloat(document.getElementById("2quiz1").value);
quiz2 = parseFloat(document.getElementById("2quiz2").value);
quiz3 = parseFloat(document.getElementById("2quiz3").value);
ass1 = parseFloat(document.getElementById("2ass1").value);
ass2 = parseFloat(document.getElementById("2ass2").value);
lab1 = parseFloat(document.getElementById("2lab1").value);
lab2 = parseFloat(document.getElementById("2lab2").value);
lab3 = parseFloat(document.getElementById("2lab3").value);
Midterm = parseFloat(document.getElementById("mgrade").value);
quiz4 = ((quiz1 + quiz2 + quiz3) / 3 );
ass3 = ((ass1 + ass2) / 2 );
lab4 = ((lab1 + lab2 + lab3) / 3 );
var cs = ((quiz4 * 0.60) + (ass3 * 0.20) + (lab4 * 0.20));
var tmg = (cs *.50) + (Midterm *.50);
mg = (1/3*pg) + (2/3*tmg)
document.getElementById("demo").innerHTML = "Your Midterm grade is: " + mg.toFixed(1);
}
I wish to use the computed pg variable from the GradingScheme function for the MIDTERM function formula.
var pg = (cs*.50) + (pegrade*.50);
The midterm function formula would be like this:
var cs = ((quiz4 * 0.60) + (ass3 * 0.20) + (lab4 * 0.20)); var tmg = (cs *.50) + (Midterm *.50); mg = (1/3*pg) + (2/3*tmg);
However, I do not know how to get the pg value from the previous function.
I am still new to JavaScript, any help would be appreciated.
As you want to use the calculation of pg in 2 places, it would make sense to separate out the logic for calculating it into its own function:
function calculatePG(){
var quiz1, quiz2, quiz3, ass1, ass2, lab1, lab2, lab3, pegrade;
quiz1 = parseFloat(document.getElementById("quiz1").value);
quiz2 = parseFloat(document.getElementById("quiz2").value);
quiz3 = parseFloat(document.getElementById("quiz3").value);
ass1 = parseFloat(document.getElementById("ass1").value);
ass2 = parseFloat(document.getElementById("ass2").value);
lab1 = parseFloat(document.getElementById("lab1").value);
lab2 = parseFloat(document.getElementById("lab2").value);
lab3 = parseFloat(document.getElementById("lab3").value);
pegrade = parseFloat(document.getElementById("pegrade").value);
quiz4 = ((quiz1 + quiz2 + quiz3) / 3 );
ass3 = ((ass1 + ass2) / 2 );
lab4 = ((lab1 + lab2 + lab3) / 3 );
var cs = ((quiz4 * 0.60) + (ass3 * 0.20) + (lab4 * 0.20) );
return (cs*.50) + (pegrade*.50);
}
You can then use this in 2 places
function GradingScheme()
{
varpg = calculatePG();
document.getElementById("demo").innerHTML = "Your Prelim grade is: " + pg.toFixed(1);
}
function MIDTERM()
{
quiz1 = parseFloat(document.getElementById("2quiz1").value);
quiz2 = parseFloat(document.getElementById("2quiz2").value);
quiz3 = parseFloat(document.getElementById("2quiz3").value);
ass1 = parseFloat(document.getElementById("2ass1").value);
ass2 = parseFloat(document.getElementById("2ass2").value);
lab1 = parseFloat(document.getElementById("2lab1").value);
lab2 = parseFloat(document.getElementById("2lab2").value);
lab3 = parseFloat(document.getElementById("2lab3").value);
Midterm = parseFloat(document.getElementById("mgrade").value);
quiz4 = ((quiz1 + quiz2 + quiz3) / 3 );
ass3 = ((ass1 + ass2) / 2 );
lab4 = ((lab1 + lab2 + lab3) / 3 );
var cs = ((quiz4 * 0.60) + (ass3 * 0.20) + (lab4 * 0.20));
var tmg = (cs *.50) + (Midterm *.50);
var pg = calcuylatePG();
mg = (1/3*pg) + (2/3*tmg)
document.getElementById("demo").innerHTML = "Your Midterm grade is: " + mg.toFixed(1);
}
There arwe furrther improvments that can be made to your code - generally separate out code which reads/updates the UI from code which does calculations. But the above should get you started.

How to make "Download Background Image" button in JavaScript?

I made a random background color generator in HTML/JavaScript. Now, I want to add "Download Background Image" button. But I don't know how.
Here is my code:
function randomBgColor() {
var rmin = +rmintxt.value;
var rmax = +rmaxtxt.value;
var gmin = +gmintxt.value;
var gmax = +gmaxtxt.value;
var bmin = +bmintxt.value;
var bmax = +bmaxtxt.value;
var r = Math.floor(Math.random() * (rmax - rmin + 1) + rmin);
var g = Math.floor(Math.random() * (gmax - gmin + 1) + gmin);
var b = Math.floor(Math.random() * (bmax - bmin + 1) + bmin);
var r2 = Math.floor(Math.random() * 255);
var g2 = Math.floor(Math.random() * 255);
var b2 = Math.floor(Math.random() * 255);
var rhex = r.toString(16);
var ghex = g.toString(16);
var bhex = b.toString(16);
var bgColor = "rgb(" + r + "," + g + "," + b + ")";
var bgColor2 = "rgb(" + r2 + "," + g2 + "," + b2 + ")";
document.body.style.background = bgColor;
rgb.innerHTML = "RGB: " + r + ", " + g + ", " + b;
rgb.style.color = bgColor2.toString(16);
hex.innerHTML = "Hex: #" + rhex.toUpperCase() + ghex.toUpperCase() + bhex.toUpperCase();
hex.style.color = bgColor2.toString(16);
}
I don't know why it doesn't work on StackOverflow, but on my computer it works well. Try to copy-paste and check it out.
var theCanva = document.querySelector('canvas');
var twoD = theCanva.getContext("2d");
var theBtn = document.querySelector('.btn');
function random_rgba() {
var o = Math.round, r = Math.random, s = 255;
return 'rgba(' + o(r()*s) + ',' + o(r()*s) + ',' + o(r()*s) + ',' + r().toFixed(1) + ')';
}
twoD.width = window.innerWidth;
twoD.height = window.innerHeight;
var link = document.createElement('a');
link.innerHTML = 'Download';
link.addEventListener('click', function(ev) {
link.href = theCanva.toDataURL("image/png");
link.download = "test";
}, false);
theBtn.addEventListener('click', () => {
var color = random_rgba();
twoD.fillStyle = color;
twoD.fillRect(0, 0, 1200, 800);
document.body.appendChild(link);
});
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
canvas {
position: fixed;
width: 100%;
height: 100vh;
z-index: -1;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
<button class="btn">Generate random background color</button>
<canvas></canvas>
If you would like to have the button be able to have a file selector where you could make the page's background be the selected image, then you would need to have a file input, so that you can get the image that the user would like to use as a background to be displayed. In the JS, then you will need to create a variable to get the data of what the chosen file is. Now, you will need to have a conditional that checks if there even is a picture. So you can just do this:
if (/**Over here, you must check if the file exists and it is an image.**/) {
//Over here, you would want to turn the page's background into the image.
}
But, you need to have a function, or else the whole thing will only run at the very start of the page's load. You need to add an event listener or something that checks when the file is chosen. If you don't know how to do that, then you can just search it up. Or, you could find something on Stack Overflow that relates to it. Like this:
How to check if input file is empty in jQuery
Hope this helps! If you have any further questions, please tell me. I am new on Stack Overflow, so I need to know how I can improve. Thanks!

Update total variable when quantity is changed

I'm having trouble updating the total when I change the "Complete E-Book" product quantity. When I first set the quantity and add it to basket it shows the correct total within the basket but when I change the quantity it adds on to the previous total. Overall I want to be able to add multiple products to the basket total (reason for x += p2Total (x var is what holds the total - Line 86) but while allowing for the Quantity of the product to be changed and then updated in the total.
Codepen Here >
Products in question are the top 2
JS:
// JQuery Functions for NavBar - Class Toggle
(function() {
$('.hamburger-menu').on('click', function() {
$('.bar').toggleClass('animate');
})
})();
(function() {
$('.hamburger-menu').on('click', function() {
$('.bar2').toggleClass('ApprDown');
})
})();
/*
START OF BASKET
START OF BASKET
*/
// Get access to add to basket basket button
var addToBasket = document.querySelector('.atbb');
addToBasket.addEventListener('click', P1);
// Formatter simply formats the output into a currceny format istead of a general number format. This is using the ECMAScript Internationalization API
var formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'GBP',
minimumFractionDigits: 2,
});
var totalBasket
var discountLimit = 10
var discount = 3.50
var x = 0.00
// One big function with different condtions based on the differnt products and then simply concatinate the values where needed
function P1() {
var y = document.getElementById("p1Quant").value;
if (+y > discountLimit) {
var z = 15.000
x = parseFloat(+y) * parseFloat(+z); // + will convert the vars into Numbers etc
document.getElementById("BasketSumData").innerHTML = ("Sub Total: ") + formatter.format(x) + ("<br/>") + ("<hr />") + ("<div class='strike'>Plus £3.50 Delivery</div>") + ("<br/>") + ("<hr />") + ("Total: ") + formatter.format(x)
// Jquery Notificaiton
var truckVar = document.getElementById("truck");
truckVar.setAttribute("class", "animateTruck");
} else if (+y <= 0) {
document.getElementById("BasketSumData").innerHTML = ("Sub Total: ") + formatter.format(0) + ("<br/>") + ("Total: ") + formatter.format(0)
} else {
var z = 15.000
var s = 15.000
x = parseFloat(+y) * parseFloat(+z) + 3.50
var sub = parseFloat(+y) * parseFloat(+s)
document.getElementById("BasketSumData").innerHTML = ("Sub Total: ") + formatter.format(sub) + ("<br/>") + ("<hr />") + ("Plus £3.50 Delivery") + ("<br/>") + ("<hr />") + ("Total: ") + formatter.format(x)
}
}
var addToBasket2 = document.querySelector('.atbb2');
addToBasket2.addEventListener('click', P2);
function P2() {
p2Total = 0.00
var y = document.getElementById("p2Quant").value;
var p2 = 8.00
var p2Total = parseFloat(+y) * parseFloat(+p2); // + will convert the vars into Numbers etc
// var totalBasket = + x + x // javascript add value onto set var
x += p2Total // Append the amount to the basket
document.getElementById("BasketSumData").innerHTML = ("Sub Total: ") + formatter.format(x) + ("<br/>") + ("<hr />") + ("<div class='strike'>Plus £3.50 Delivery</div>") + ("<br/>") + ("<hr />") + ("Total: ") + formatter.format(x)
if (+y <= 0) {
p2Total = 0.00
}
}
Don't add the value to x, add x and p2Total into a new temporary value that is scoped to the function itself and use that.
var tmp_total = x + p2Total;
document.getElementById("BasketSumData").innerHTML = ("Sub Total: ") + formatter.format(tmp_total) + ("<br/>") + ("<hr />") + ("<div class='strike'>Plus £3.50 Delivery</div>") + ("<br/>") + ("<hr />") + ("Total: ") + formatter.format(tmp_total)

building an ordered list from small to big

I have the following hardcoded JSON:
var myData = [
{"Identifier":1,"Naam":"Van Der Valk","Adres":"Europaweg 218","Postcode":"1238AC","Plaats":"Zoetermeer","Longitude":"4.48822","Latitude":"52.06258", "Status":"Laadpunten Beschikbaar", "lunch":"true", "diner":"true", "meet":"true", "wifi":"true"},
{"Identifier":2,"Naam":"NOT Given","Adres":"NOT Given 1","Postcode":"0000LL","Plaats":"Rotterdam","Longitude":"0.00000","Latitude":"0.00000", "lunch":"false"},
{"Identifier":3,"Naam":"NOT Given","Adres":"NOT Given 6","Postcode":"0000LL","Plaats":"Rotterdam","Longitude":"0.00000","Latitude":"0.00000", "lunch":"false"},
{"Identifier":4,"Naam":"NOT Given","Adres":"NOT Given 1","Postcode":"0000LL","Plaats":"Den Haag","Longitude":"0.00000","Latitude":"0.00000", "lunch":"false"},
{"Identifier":5,"Naam":"plek b met lunch en diner","Adres":"NOT Given 218","Postcode":"0000LL","Plaats":"Zoetermeer","Longitude":"0.00000","Latitude":"0.00000", "lunch":"true", "diner":"true", "wifi":"true"}
];
This json i use in my ios phonegap app.. Each line of code in the Json is a point in the netherlands.. I am trying to build a function which calculates the distance between where the phone is and the lat and long from the json.. eventually these json code needs to come in a ordered list where also the distance are from small to big..
for the distance measurement i Used this:
function haversine() {
$.each(myData, function(index, element) {
var R = 6371; // earth's mean radius in km
var dLat = rad(element.Latitude - lat1);
var dLong = rad(element.Longitude - long1);
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(rad(lat1)) * Math.cos(rad(element.Latitude)) * Math.sin(dLong/2) * Math.sin(dLong/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
//var element = document.getElementById('afstand');
//element.innerHTML = 'afstand: ' + d.toFixed(3);
$('.greenfluxlist').append('<li id="' + element.Identifier + '">' + element.Naam + ' ' + element.Plaats + '<p> <br/>' + element.Adres + ',<br/> ' + element.Postcode + ' ' + element.Plaats + '<br/> Status: ' + element.Status + '</p> <span class="ui-li-count">' + d.toFixed(3) + '</span></li>');
});
$('.greenfluxlist').trigger('create');
$('.greenfluxlist').listview('refresh');
//return d.toFixed(3);
}
What my problem now is, how can i build the ordered list, is it possible to get everything into an array and then loop through it or something else, i think there has to be a simple solution but i don't know.
To sort an array, use the sort method.
You should calculate the distance first, then sort the array, and then generate the list. Something like this:
function calculateDistance(element)
{
var R = 6371; // earth's mean radius in km
var dLat = rad(element.Latitude - lat1);
var dLong = rad(element.Longitude - long1);
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(rad(lat1)) * Math.cos(rad(element.Latitude)) * Math.sin(dLong/2) * Math.sin(dLong/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
return R * c;
}
function generateList(data)
{
for(var i=0; i<data.lenght; i++)
{
var element = data[i];
//var element = document.getElementById('afstand');
//element.innerHTML = 'afstand: ' + element.Distance.toFixed(3);
$('.greenfluxlist').append('<li id="' + element.Identifier + '">' + element.Naam + ' ' + element.Plaats + '<p> <br/>' + element.Adres + ',<br/> ' + element.Postcode + ' ' + element.Plaats + '<br/> Status: ' + element.Status + '</p> <span class="ui-li-count">' + element.Distance.toFixed(3) + '</span></li>');
}
}
for(var i=0; i<myData.length; i++)
{
myData[i].Distance = calculateDistance(myData[i]);
}
myData.sort(function(a,b) {
return a.Distance > b.Distance;
});
generateList(myData);

Categories

Resources