I realise this and similar questions / answers exist already. But I've looked at a lot now and just not sure what simple thing I'm doing wrong. I'm just getting to grips with this.
I have the error "Can't find variable: getElementById" I've try changing the order of the script and HTML.
I used this random method which works fine Get random item from JavaScript array Its just applying it to the src...
This video was also helpful https://www.youtube.com/watch?v=pqLS4oyJ8cA
Here is my code: http://jsfiddle.net/udkhpytm/
<div>
<script id="IntroAnimation" type="text/javascript" charset="utf-8" src=""></script>
</div>
<script type="text/javascript">
var my_array = ['FILE1', 'FILE2', 'FILE3'];
var ri = Math.floor(Math.random() * my_array.length); // Random Index position in the array
getElementById("IntroAnimation").src = ri;
</script>
I'm trying to get a random item from the array and place it in the src of my Script by the scripts ID.
getElementById is a method belonging to the document object. It isn't a standalone function. Change:
getElementById("IntroAnimation").src = my_array[ri];
To:
document.getElementById("IntroAnimation").src = my_array[ri];
Note that I've also changed ri to my_array[ri] as otherwise you're passing in the index position as the src rather than the contents of the array at that specific position.
You need to grab that item from the array, all you did was just get a random number based on the array length.
var my_array = ['FILE1', 'FILE2', 'FILE3'];
var ri = Math.floor(Math.random() * my_array.length);
var file = my_array[ri];
Then you need to add document before getElementById:
doucment.getElementById("IntroAnimation").src = file;
Related
I'm building a site in WordPress and the plugins come with a few unwanted css files.
I'm trying to remove these stylesheets via JS but encountering a Failed to execute 'querySelector' on 'Document': '0' is not a valid selector. error.
I'm trying to make it reusable so that I can add stylesheets to the array and remove easily, maybe even scripts too.
Unsure where I'm going wrong in my JS?
const assets = ["link[href*='/wp-content/plugins/js_composer/assets/css/js_composer.min.css']",
"link[href*='/wp-includes/css/dist/block-library/style.min.css']"
]
for (var i in assets) {
var cssElement = document.querySelector(i);
cssElement.disabled = true;
cssElement.remove();
console.log(cssElement);
}
First of all, the i in your for .. in loop holds the index of the item at the current iteration, so on the first iteration, i will be equal to 0. So to get the selector from you selector array, at each iteration, you'd need to pass assets[i] to the quesrySelector method.
Another thing, at every iteration, you should check if querySelector has found an element or not before trying to remove the expected element.
const assets = [
"link[href*='/wp-content/plugins/js_composer/assets/css/js_composer.min.css']",
"link[href*='/wp-includes/css/dist/block-library/style.min.css']"
];
let cssElement;
for (var i in assets) (cssElement = document.querySelector(assets[i])) && cssElement.remove();
/** the above line will only executed when "querySelector" has found an element on the page */
Another possible way to have the same effect is to use the forEach method:
const assets = [
"link[href*='/wp-content/plugins/js_composer/assets/css/js_composer.min.css']",
"link[href*='/wp-includes/css/dist/block-library/style.min.css']"
];
let cssElement;
assets.forEach(s => (cssElement = document.querySelector(s)) && cssElement.remove());
Learn more about the forEach method.
Use for of not for in. i in your case is the index but you want it to be the element in the array.
The error is saying that you passed 0 (which is the first index) to the querySelector which is not a valid DOM element
const assets = ["link[href*='/wp-content/plugins/js_composer/assets/css/js_composer.min.css']",
"link[href*='/wp-includes/css/dist/block-library/style.min.css']"
]
for (var i in assets) {
var cssElement = document.querySelector(assets[i]);
cssElement.disabled = true;
cssElement.remove();
console.log(cssElement);
}
<link href="/wp-content/plugins/js_composer/assets/css/js_composer.min.css" rel='stylesheet'/>
<link href="/wp-includes/css/dist/block-library/style.min.css" rel='stylesheet'/>
I'm trying to make a simple javascript command that I can run from the console in Chrome. I have a webpage which is filled with links that all follow the same format such as:
Example
This would take it to www.site/e/example.html
I want to be able to randomly pick on of them and follow the link. I've tried doing it using a regex but can't work out how to use it in the console. Any help here would be appreciated!
This is the simple expression I made (just extracts the "e/example" part):
$ <a href="(.+?).html">.+?<\/a>
You can use document.getElementsByTabName and select all a-elements on page. I guess, it is resilient way than regexp.
https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName
First select all the links with querySelectorAll:
let links = document.querySelectorAll("a");
Then pick a random value, randomIndex returns an Integer between 0 and the array length.
let randomIndex = Math.floor(Math.random() * links.length);
let randomLink = links[randomIndex].href;
randomLink should now contain a randomly chosen link on the webpage.
What you can do is to list all a elements using document.querySelectorAll. You can then loop through them and extract their href property like so:
const links = [...document.querySelectorAll("a")].map(x => x.href);
Then just select a random element from this array:
const link = links[Math.floor(Math.random() * links.length)];
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 want to change the content of a div randomly by .InnerHTML. The text are saved as variables. The random number is another variable. The Problem is, that if I put text and random number together it will print text1 for example.
Can someone help me with that?
function switchText(){
var text1 = "hello";
var text2 = "there";
var text3 = "ObiWan";
var randomNumber = Math.floor(Math.random() * 3) + 1;//creates random No. from 1 - 3
document.getElementById("randomText").innerHTML = "text" + randomNumber;
//the problem
}
<div id="randomText" onclick="switchText();">click here</div>
How about storing all random strings in an array, like so:
function switchText(){
var randomWords = ["hello", "there", "ObiWan"];
var randomIndex = Math.floor(Math.random() * 3);//creates random No. from 1 - 3
document.getElementById("randomText").innerHTML = randomWords[randomIndex];
//the problem
}
Actually you can access those variables by using index notation (it's described really nicely here) so in your specific case of function you just need to change the line where you try to access the variable to
document.getElementById("randomText").innerHTML = this['text' + randomNumber];
However though such notation is not something I would recommend. Usage of array as it was suggested is much more readable in fact.
Store those texts into an array and use the random number.
Get the random number as follow: Math.floor(Math.random() * 3)
function switchText(){
var texts = ["hello", "there", "ObiWan"];
var randomNumber = Math.floor(Math.random() * 3);//creates random No. from 1 - 3
console.log(randomNumber)
document.getElementById("randomText").innerHTML = texts[randomNumber];
//the problem
}
<div id="randomText" onclick="switchText();">click here</div>
You can store those texts into an object as well.
function switchText() {
var texts = {
"text1": "hello",
"text2": "there",
"text3": "ObiWan"
};
var randomNumber = Math.floor(Math.random() * 3) + 1; //creates random No. from 1 - 3
console.log(randomNumber)
document.getElementById("randomText").innerHTML = texts[`text${randomNumber}`];
//the problem
}
<div id="randomText" onclick="switchText();">click here</div>
Your question is focused on how to dynamically construct a variable name, but usually this problem comes up because the solution you are attempting is based on a coding pattern that has boxed you into a corner. Instead of writing a potentially hazardous solution or one that is overly complex, re-think your approach.
Whenever you have several pieces of data to store that don't have key names to go with them, you should be storing those data in an Array. The advantages to storing data in an array are huge. So, you should place the strings into an array instead of individual variables that all have to have similar names. So, now you have less variables to worry about and no variable names that have to be set to certain values and the problem of dynamically creating a variable name is gone entirely.
All you need to do now is to use the random number as an index to the array. Don't adjust the random to make it 1-based, because arrays are 0-based. And, when you get the random, multiply it by the length of the array, rather than hard code a number. This way, all you have to do is add/remove strings to the array for them to become possible resulting strings.
This structure and solution make your code simpler and more flexible.
Also, don't set up your event handlers using HTML event attributes. There are many reasons why you shouldn't use this 25+ year old technique. Do it in JavaScript.
var strings = ["hello","there","ObiWan"]; // Store the possible strings in an array
var btn = document.getElementById("randomText"); // Get a reference to the trigger element
var output = document.getElementById("output"); // And the output area
// Set up the event handler in JavaScript, not HTML
btn.addEventListener("click", function(){
// Set the output to a string from the array using a random index
output.innerHTML = strings[Math.floor(Math.random() * strings.length)];
});
<button id="randomText">click here</button>
<div id="output"></div>
When making a JavaScript script to iterate through a set of elements with the same class name, you can alter each of their properties individually.
How does the script know which element to edit if they don't have unique IDs? If they do in fact have unique ID's, how do you retrieve them? Using alert(); to display what is held in the node array from a simple document.getElementsByClassName(''); seems to display the type of element.
Could I actually store these results in an array for later use?
If on the documents load, I fetch an array of elements with a certain class name:
<script>
var buttonArray = document.getElementsByClassName('button');
</script>
Then iterate through this, and add the result at 'r' position to an object:
<script>
var buttonArray = document.getElementsByClassName('button');
var buttonObject = {};
for(r=0;r<buttonArray.length;r+=1)
{
buttonObject[buttonArray[r]] = [r*5,r*5,r*5];
}
</script>
Would I be able to find the array for each individual element with classname 'button' like so:
<script>
var buttonArray = document.getElementsByClassName('button');
var buttonObject = {};
function changeCol(buttonID)
{
var red = buttonObject[buttonID][0];
var green = buttonObject[buttonID][1];
var green = buttonObject[buttonID][2];
buttonID.style.backgroundColor = "rgb("+red+","+green+","+blue+")";
}
for(r=0;r<buttonArray.length;r+=1)
{
buttonObject[buttonArray[r]] = [r*5,r*5,r*5];
buttonArray[r].onclick = function(){ changeCol(this); };
}
</script>
I thought the this part of onclick = function(){ changeCol(this); }; would hold the same unique ID as I stored in the buttonObject object, as the variable name that held the array?
Should this work? I can't seem to get it to on my web page, so instead, I used the buttons innerHTML in the buttonObject as the variable name that held the array for that object. The problem with that, is that I will probably need two or more buttons to have the same innerHTML.
Here's the webpage as it currently is:
http://www.shadespeed.com
I need to re-make the script to allow buttons to have the same name.
Any tips / advice would be greatly appreciated.
Many thanks!
- Dan. :)
Let's say I have a deck of cards spread out on my desk, face up. I want to flip over all the red ones. I might do this:
desk.getCardsByColour("red").forEach(flipit);
// note, obviously not real JavaScript for a not real situation :p
So I scan through my cards, finding all the red ones. Then I flip them over. What you're asking is basically "how do I know which cards to flip over if they don't have unique IDs?" Well, do I need an ID to iterate through a collection of objects, in this case a set of cards? Of course not.
(Note that while cards in a deck do have a unique property in their content, let's just assume that's the element's content and not an id attribute, kay?)
Now, here's how I'd do what you're doing:
for( r=0; r<buttonArray.length; r++) {
buttonArray[r].buttonObject = [r*5,r*5,r*5];
buttonArray[r].onclick = changeCol;
}
function changeCol(button) {
var red = button.buttonObject[0];
var green = button.buttonObject[1];
var blue = button.buttonObject[2];
button.style.backgroundColor = "rgb("+red+","+green+","+blue+")";
}