How our site is setup now is we would like to have a way that a user clicks a button per say, and it automatically selects a random download location that is listed in the code.
For example, user clicks "Download!". It randomly selects a URL to visit in the code that is set for example:
"website.com/blah.zip"
OR
"website2.com/blah.zip"
Is this possible to do? We are trying to ease the bandwidth on our servers by having two download locations, and have the site randomly choose one.
You have tagged php (server-side), this is a part of Javascript (client-side)
When inserting the Download button, randomly select a index value from an array of links :
var arr = ["website.com/blah.zip", "website2.com/blah.zip"];
var len = arr.length;
var x = Math.floor((Math.random() * len) + 1);
Now change download source to arr[x].
Well, an easy way to do it would be:
$array = array("website.com/blah.zip", "website2.com/blah.zip");
$val = array_rand($array);
echo $array[$val];
You can use as many different sites as you want, and it will give you a random site from that array.
EDIT: Solution to the question posed in the comments:
Have you array set up at the top of your file as before:
$array = array("website.com/blah.zip", "website2.com/blah.zip");
Then with each link you'd just need to do:
Download
You could store two URls in an array and pick one like bellow.
$rand_key = array_rand($url_options, 1);
echo $url_options[$rand_key];
Related
I am at starting web dev, already using html/css.
For a little project, I had a look at JavaScript. (My goal is that when people click a button, the site will show a random sentence that will be taken from a google sheet cell.)
Could you tell me please if it is even possible? If so, please share some ideas that I will explore. If not, please give me some alternative ideas... Thanks so much.
Have a good day!
-LeganV9
This is possible using Google Apps Script!
I have a working demo here, with the source being here. I dare you to get the jackpot. :D
In order to make this, you can go to https://script.new. Now, in code.gs put this:
function doGet() {
return HtmlService.createTemplateFromFile("index").evaluate().setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
function getVals(){
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1IDbhQhaImcQB-4j-iByajwAkvxkutptcPMhMTxNrPtU/edit#gid=0");//Put your URL here
var sheet = ss.getSheetByName("Sheet1");//Put your sheet name here
var AMOUNT_OF_SENTENCES = sheet.getMaxRows().toString().replace(".0","");//You can replace this with a number eg 20
var range = sheet.getRange(1, 1,AMOUNT_OF_SENTENCES);
var values = range.getValues();
var newValues = [];
for(var i = 1; i<values.length;i++){
if(values[i][0] === "" || values[i][0] === " "){
}else{
newValues.push(values[i][0]);
}
}
return {valuesVar: newValues };
}
After that, create a new HTML file called "index" and put this in it:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>
The results are: <span id = "results">Loading...</span>
</h1>
<button id = "yourIdHere">Click me!!</button>
<script>
var yourDataList;
function onSuccess(data) {
yourDataList= data.valuesVar;
}
google.script.run.withSuccessHandler(onSuccess).getVals();
var myBtn = document.querySelector("#yourIdHere"); //Declare button, replace yourIdHere with your ID
var randomNum = 0; //Decclre random number
function getRandom() { //Declare your function
randomNum = parseInt(Math.random() * yourDataList.length); //Get random number between 0 and the length of your datalist
return yourDataList[randomNum]; //Return your value
}
myBtn.addEventListener("click", function() { //Bind a listener to the button
document.querySelector("#results").innerText = getRandom(); //Do whatever you want to with the random value
});
document.querySelector("#results").innerText = getRandom();//Change from loading...
</script>
</body>
</html>
Welcome to the world of web development! Hope your project is a success.
It should definitely be possible, since Google Sheets offers an API which has read/write functionality (https://developers.google.com/sheets/api).
You could even later extend this so people can submit their own sentences, given that writing to a Google Sheet is also possible with this API.
However, since you're starting out, consider treating this as an iterative process. You don't have to publish your first version, but just to prevent overwhelming yourself, you might want to set small milestones along the way - each adding more functionality. For example:
Create an array of random sentences (you could, for example, start with using this to keep it simple: https://github.com/JamesFT/Database-Quotes-JSON).
Select and log a random sentence to the console (console.log()) each time the script is executed.
Transfer the random sentence to render in HTML and allow a new sentence to be generated each time a button is pressed.
Move your sentences into a Google Sheet and begin exploring the API.
This way, you achieve something in a much shorter space of time, while working towards your end goal. It's a good way to keep motivated and make things more manageable.
Best of luck!
I would need some help to adjust this code to suit my needs.
I need to build a javascript that will be stored on a SharePoint page in order to generate on demand a NEW random USERID.
The problem is that I have zero knowledge of javascript, but I am very willing to learn.
The ID is built like this : "IT" & "number from 30001 to 79999"
Example: IT30002
The IDs created must always be different, so those "used" have to be permanently stored in a file.
Every time a new ID is prompted, the script will check the history file and provide a new ID.
Is there a way to achieve what I need?
I have looked at these 2 codes examples:
This example has the key functionality of storing the previous choices, so I am sure I will not use the same ID twice, the problem is that I need numbers, not names and also I need the script to store the numbers permanently
The code below has the other functionality of the "button" to press in order to display the ID.
<html>
<body>
<p id="one"></p>
<button onclick="random()">Random</button>
<script>
function random(){
document.getElementById("one").innerHTML = Math.floor(Math.random() * 10);
}
</script>
</body>
randojs.com makes this pretty easy.
Put this in the head of your page:
<script src="https://randojs.com/1.0.0.js"></script>
And then you can use this JavaScript:
var sequence = randoSequence(30001, 79999);
var currentIndex = 0;
function getNewID(){
return "IT" + sequence[currentIndex++];
}
And you can add this button to the body of your page if you need to:
<button onclick="alert(getNewID());">Alert new ID.</button>
Here's all of that together (click "Run" and then click the "Alert new ID." button that shows up to see it work):
var sequence = randoSequence(30001, 79999);
var currentIndex = 0;
function getNewID(){
return "IT" + sequence[currentIndex++];
}
<script src="https://randojs.com/1.0.0.js"></script>
<button onclick="alert(getNewID());">Alert new ID.</button>
Some references to concepts for you: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set and https://www.w3schools.com/jsref/prop_win_localstorage.asp
Well, all you need to do is generate a random number and store it somewhere. Since, you're using javascript at the front-end, you can't write onto a file without using some backend. If you're fine with storing things for a single user's session, you can use localstorage to store your previous findings in a Set. This lets you store stuff in the browser but for a single user only.
Now the question is what to store? Everytime you generate a random number, look for it in the set from localstorage. If it exists, generate the random number again and repeat lookup process. Keep repeating this random number generation and lookup process until a new random number is found.
What to do if a new random number is finally generated i.e. it doesn't exist in the set? You store it into the set and save the set to the localstorage, stop repeating the process and use the newly generated number for your needs.
That's it.
#Rishinder has explained some of your possible approaches. I will share some code to explain the same. This will print the random numbers on the browser
<html>
<body>
<div id="random"></div>
<button onclick="printRandom()">Generate numbers</button>
</body>
<script>
// fetch and prepare the data
var storage = localStorage.getItem('random'),
existingNumbers = storage ? JSON.parse(storage) : {};
// will generate the random number
function generateRandom() {
var loop = true,
newRand;
while (loop) {
newRand = Math.ceil(Math.random() * 1000000) % 79999;
if (existingNumbers[newRand])
continue;
else if (!existingNumbers[newRand] && newRand < 30001)
continue;
else if (!existingNumbers[newRand]) {
existingNumbers[newRand] = true;
localStorage.setItem('random', JSON.stringify(existingNumbers));
loop = false;
}
}
return Object.keys(existingNumbers).join(', ');
}
// print the existing numbers already stored
document.getElementById('random').innerHTML = Object.keys(existingNumbers).join(', ');
function printRandom() {
document.getElementById('random').innerHTML = generateRandom();
}
</script>
</html>
Hope this helps
I am trying to use Javascript to select two random images from a local folder and place on separate Photoshop layers. I have created an array with the filepaths to choose from.
#target photoshop
var allImages = [“file path/img-1.jpg”, "file path/img-2.jpg", "file path/img-3.jpg"];
//this is a large array of file paths to 100 different images
var pickImage = allImages[Math.floor(Math.random() *
allImages.length)];
var imgFile = File(pickImage);
var openFile = app.open(imgFile);
var secondImage = allImages[Math.floor(Math.random() * allImages.length)];
app.activeDocument.artLayers.add(secondImage);
This opens the first image and creates a blank layer above but does not insert the second image. What am I missing?
In javascript, you must first create a file object before you may open an image. All you have to do is create the variable and then point it at secondImage. Just like you did with the first image:
var imgFile = File(pickImage);
In your current approach, your easiest solution would probably be to just make a variable secondPickedImage and assign it to the same thing as pickImage. Although, this leaves the possibility of you picking the same image, you could fix that with an if statement.
I would recommend changing your approach and turning pickImage into a function that you can call that will return a random number for your array - saves space, and cleans up your code. Then put the secondImage assignment in a do while loop that keeps picking a random number until you pick a number different from the pickImage number so your first and second pictures are different.
Source: http://wwwimages.adobe.com/www.adobe.com/content/dam/acom/en/devnet/photoshop/pdfs/photoshop-cc-scripting-guide.pdf page 29.
Solved! - didn't update my random number generation after changing from switch statement to array... ups. - Thanks!
Problem
Building a web comic and wanted to have one of those "random" buttons, where you jump to any of the strips. I'm assuming the best way to do this would be something on the back end (PHP or such), but I want to do it with JavaScript.
I got as far as picking a random page, but had the problem that it would sometimes redirect to the page it's already on (or rather often until I have more pages). I tried to make it take the page out of the array if the current page is the same as the target page, but instead I end up getting redirected to "http://bcitcomp.ca/students/hsloman/Comp1850/final/undefined"
I even made sure to use splice instead of delete. Doesn't that re-index the list?
Code
var pickRandomPage = function () {
// random Pages available
var links = [
"construction.html",
"placeholder.html",
"noplaymobil.html"];
// current Page
var currentURL = window.location.href;
var currentPage = currentURL.substr(currentURL.lastIndexOf('/')+1);
// get rid of current page from array of options
for(var i = 0; i < links.length; i++){
if(links[i] == currentPage){
links.splice(i,1);
}
}
// get a random number, rounded number between 0 and number of links
var randomPage = Math.floor((Math.random() * 3) + 1);
var link = 'http://bcitcomp.ca/students/hsloman/Comp1850/final/' + links[randomPage];
// open it
window.open(link,"_self");
};
Resources used sofar
Get current URL in web browser
window.open() should open the link in same tab
but instead I end up getting redirected to "http://bcitcomp.ca/students/hsloman/Comp1850/final/undefined"
The undefined is because your randomPage variable will contain a number between 1 and 3, but the actual valid indices in your links array are only either 0 or 1 because it will only have two elements after you remove the current page URL.
Change:
var randomPage = Math.floor((Math.random() * 3) + 1);
to:
var randomPage = Math.floor(Math.random() * links.length);
put this right before the window.open(...) line:
if(link === window.location+"") return pickRandomPage();
This is saying, "if the chosen link is the page we're already on, run the function again" ..so it will keep trying until a new page is given. This is easier than trying to splice the array.
See: recursion for more info.
I have 2 index pages with approx. 150 links on each. I would rather maintain 1 page and just generate the links dynamically based on a variable value. For example create a list of links. link1, link2, link3... and based on a variable value being 'true' replace those links with list of alternate links i.e. altlink1, altlink2, altlink3...
I have figured out how to do this once but rather than writing the same code over and over for each link I was wondering if there was a faster way. Like creating a list "a" and corresponding list "b" or something like that. I have included my current code below and I look forward to your advice.
<script type="text/javascript">
// link rewriter
var hostadd = location.host;
var vendor = '999.99.999.99';
var localaccess = 'somesite.com';
$(document).ready (
function link_switcher(){
//if not a vendor route to alternate website
if (hostadd != vendor) { $("a[href= 'https://www.somelink1.com']").attr ('href', 'https://www.alternatelink1.com') }
});
</script>
is it possible to create an array and then javascript that would say replace link1 in array a with alternatelink1 in array b?
It's still not entirely clear what you're trying to do, but if you want to rewrite all links based on a lookup table that tells you what link to convert to what, here's how you could do that:
// Table of links.
// Key is original page source URL
// Data is link to change it to
var linkData = {
"http://www.google.com": "http://www.bing.com/",
"http://mail.google.com/mail/?shva=1#inbox": "http://www.hotmail.com"
};
// find every link in the page and change it if it's value is found in the linkData table
$("a").each(function() {
var link = this.getAttribute("href"); // use getAttribute to get what was actually in the page, perhaps not fully qualified
if (linkData[link]) {
this.href = linkData[link];
}
});
If the link is not found in the table, it will not be modified. If there was some pattern to the modification, it might be possible to code that pattern and not have to list every link in the table, but you haven't shared any info about a pattern.
And, a working jsFiddle example: http://jsfiddle.net/jfriend00/Cvj8C/.