Dynamically adding variables to a URL - javascript

I am trying to dynamically add parts to a URL by passing variables to the URL dynamically such as in the code below. How can I get the code below to work so that the URL comes out looking like this:
http://www.test.com/test/Test_1/ato.50/[atc1.100/atc2.200/atc3.RandomNumber/atc3.RandomNumber/atc3.RandomNumber/atc4.400
where RandomNumber is a randomly generated number using Math.floor(Math.random() * 10 * 10());
(The repeat of passing a number to atc3. is intentional.)
Code:
<html>
<body>
<script>
var orderID = 50;
var Red = 100;
var Blue = 200;
var Green = [Math.floor(Math.random() * 10 * 10), Math.floor(Math.random() * 10 * 10), Math.floor(Math.random() * 10 * 10)];
var Yellow = 400;
var tag = '<s'+'cript language="JavaScript" src="http://www.test.com/test/Test_1/ato.' + orderID + '/[atc1.' + Red + '/atc2.' + Blue + '/atc3.' + Green[0];
i = 1;
while (i < Green.length){
var tag_two[i] ='/atc3.' + Green[i];
}
var tag_three ='/atc4.' + Yellow + ']"></s'+'cript>';
document.write(tag);
for (i = 0, i < Green.length, i++){
document.write(tag_two[i]);
}
document.write(tag_three);
</script>
</body>
</html>
Thanks!

Instead of creating the new variable , you have to concatinate the string to the existing variable :
here is the working example http://jsfiddle.net/afsar_zan/aAbD6/
sample code
var orderID = 50;
var Red = 100;
var Blue = 200;
var Green = [Math.floor(Math.random() * 10 * 10), Math.floor(Math.random() * 10 * 10), Math.floor(Math.random() * 10 * 10)];
var Yellow = 400;
var i = 0;
var tag = '<script language="JavaScript" src="http://www.test.com/test/Test_1/ato.' + orderID + '/[atc1.' + Red + '/atc2.' + Blue + '/atc3.' + Green[0];
while (Green.length>i){
tag += '/atc3.' + Green[i];
i++;
}
tag +='/atc4.' + Yellow + ']"></s'+'cript>';
alert(tag);

I have found some problems in your code. so I have corrected them and here is you code.
<html>
<body>
<script>
var orderID = 50;
var Red = 100;
var Blue = 200;
var Green = new Array(Math.floor(Math.random() * 10 * 10), Math.floor(Math.random() * 10 * 10), Math.floor(Math.random() * 10 * 10));
var Yellow = 400;
var tag = '<s'+'cript language="JavaScript" src="http://www.test.com/test/Test_1/ato.' + orderID + '/[atc1.' + Red + '/atc2.' + Blue + '/atc3.' + Green[0];
i = 1;
var tag_two=new Array();
while (i < Green.length){
tag_two[i] ='/atc3.' + Green[i];
i++;
}
var tag_three ='/atc4.' + Yellow + ']"></s'+'cript>';
document.write(tag);
for (i = 0; i < Green.length; i++){
document.write(tag_two[i]);
}
document.write(tag_three);
</script>
</body>
</html>
The way you adding variables to url seems to be correct. Variables can be passed by using simple concatenate operator '+'

Related

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!

Js function working only once

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

Get position in javascript not working

I want to make a small game, but I have some start up problems.
When I try to get the position of track or trackCont, it always returns x: 0, y: 0. Doesn't get right position moving the DIV with:
float: right;
display: block;
and even doesn't work using:
position: absolute;
left: 100px;
Here's the code I am using:
var Player = new Array();
var trackEntity;
function getPosition(elem){
xPos = 0;
yPos = 0;
while(elem){
xPos += (elem.offsetLeft + elem.clientLeft);
yPos += (elem.offsetTop + elem.clientTop);
elem = elem.offsetParent;
}
return {x: xPos, y: yPos};
}
window.onload = function(){
trackEntity = document.getElementById("trackCont");
for (i = 0; i < 4; i += 1){
Player[i] = new Object();
document.body.innerHTML += "<div id='p" + i + "' class='player'></div>";
Player[i].entity = document.getElementById("p" + i);
Player[i].entity.style.backgroundColor = "rgb("
+ Math.floor(Math.random() * 256) + ", "
+ Math.floor(Math.random() * 256) + ", "
+ Math.floor(Math.random() * 256) +
")";
Player[i].entity.style.left = (getPosition(trackEntity).x) + 20;
Player[i].entity.style.top = (getPosition(trackEntity).y) + 20;
}
}
http://jsfiddle.net/dh8uf6Lp/
You need to supply a unit to when assigning a value to css left.
Player[i].entity.style.left = (getPosition(trackEntity).x) + 20 +"px";
If you assign a value to a css dimension or position property it will not update when no unit is given.
It seems that when getPosition(trackEntity) is called it doesn't know where it is in the DOM. This is caused by
document.body.innerHTML += "<div id='p" + i + "' class='player'></div>";
This causes the browser to redraw all elements and trackEntity loses it reference.
Solution: do not insert html via innerHTML, but create the div and append it to the DOM.
Player[i].entity = document.createElement("div");
Player[i].entity.id = "p" + i;
//etc.
document.body.appendChild(Player[i].entity);
//Run position code.
http://jsfiddle.net/dh8uf6Lp/3/

Use if statement to get percentage of input?

Everything runs correctly, but I want to add a few things. At the very end of the function I want to change the height of the canvas by comparing how many you got correct out of the amount that you wanted to answer, but with a percentage. Sorry if this is difficult to understand.
JavaScript:
<script type="text/javascript">
function myFunction() {
score = 0;
questionAmount = prompt('How many question would you like to solve?');
for(i = 0; i < questionAmount; i++) {
var x = Math.floor(Math.random() * 13);
var y = Math.floor(Math.random() * 13);
question = prompt('What is ' + x + ' * ' + y + ' = ?');
if(question == null || isNaN(question)) {
break;
}
if(question == x * y) {
score++;
}
}
alert('You got ' + score + ' out of ' + questionAmount + ' correct.');
}
</script>
HTML:
<canvas id="content"></canvas>
<br />
<button onclick="myFunction()">CLICK</button>
Just create the percentage and apply it:
var correctPercent = (parseDouble(score) / parseDouble(questionAmount)) * 100;
//change the target elements style, apply above variable
document.getElementById("content").style.height = correctPercent + "%";

Recognizing variables in external .js file

I'm having an issue here in my code that is driving me nuts. I have all my code and variables declared in an external .js file and I'm trying to print them out into an table which will be created in Javascript. Here is the external .js file and the HTML which references it.
loadImage.js
var pos = [];
var xAvg;
var yAvg;
var cirCtr;
var radAvg;
var defAvg;
var comPer;
var img=new Image();
img.onload=function(){
var can = document.getElementById('C');
var ctx = can.getContext('2d'); //creates canvas and image data
ctx.drawImage(img, 0, 0);
var imgdata = ctx.getImageData(0,0, img.width, img.height);
var data = imgdata.data;
var index = [];
var vertical;
var horizontal;
for (var i = 0; i < data.length; i += 4) {
if (data[i] == 255) { //finds position of piexel in data array
index.push(i);
}
}
for (var i = 0; i < index.length; i++) { //finds coordinate postion of pixel
var vertical =
Math.floor((index[i] / 4) / 400);
var horizontal =
Math.floor((index[i] / 4) % 400);
pos.push(horizontal, vertical);
}
var xTot = 0;
var yTot = 0;
for (var i = 0; i < pos.length; i+=2){
xTot = xTot + pos[i]; //finds x value of circe center
xAvg = xTot/( (pos.length+1) / 2);
};
for (var j = 1; j < pos.length; j+=2){
yTot = yTot + pos[j]; //finds y value of circle center
yAvg = yTot/( (pos.length+1) / 2);
};
cirCtr = [xAvg, yAvg];
alert("The center of the circle is " + cirCtr);
var radTot = 0;
//finds average radius of traced circle
for (var i = 0; i < pos.length; i+=2){
radTot = radTot + Math.sqrt(Math.pow((pos[i+1] - cirCtr[1]), 2) + Math.pow((pos[i] - cirCtr[0]), 2));
radAvg = radTot / ( (pos.length+1) / 2);
}
var defTot = 0;
for (var i = 0; i < pos.length; i+=2) {
defTot = defTot + (Math.abs(Math.sqrt(Math.pow((pos[i+1] - cirCtr[1]), 2) + Math.pow((pos[i] - cirCtr[0]), 2)) - radAvg));
defAvg = defTot / ( (pos.length+1) / 2);
}
comPer= 100 * ((Math.PI * Math.pow(radAvg,2))/(Math.PI * Math.pow((radAvg + defAvg), 2)));
alert(defTot);
alert("The radius of the circle is " + radAvg);
}
img.crossOrigin="anonymous"; //this had to do with the DOM Exception 18 thing
img.src="https://dl.dropboxusercontent.com/u/196150873/tile_0000_session_23220.skl.png";
the HTML
<html>
<head>
<script src="loadImage.js" type="text/javascript"></script>
<script> function();</script>
</head>
<body>
<h1>200 Circles</h1>
<canvas id="C" height="400" width="400"></canvas>
<div>
<table border="1">
<thead>
<tr>
<th>Center</th>
<th>Regular Radius</th>
<th>Derived Radius</th>
<th>Area proportionality</th>
</tr>
</thead>
<tbody id="log"></tbody>
</table>
</div>
<script>
for (var i=0; i < 10; i++) {
addRow();
}
function addRow() {
var newRow =
"<tr>" +
"<td>" + cirCtr + "</td>" +
"<td>" + radAvg + "</td>" +
"<td>" + (radAvg + defAvg) + "</td>" +
"<td>" + comPer + "</td>" +
"</tr>";
document.getElementById("log").innerHTML += newRow;
}
</script>
<body>
</html>
The issue us that the .js file is not loaded yet, when you
are referencing these variables.
I would use jquery ready event - http://api.jquery.com/ready/
If you can't use jquery, then see answers for this question - $(document).ready equivalent without jQuery
Another option is to keep both scripts on the same place, either in js file or in html.

Categories

Resources