I am doing a simple math game in HTML and JavaScript for school, this is just a small part of it. Basically I have a button that I want to be able to press, and each time I press it I want it to output a new number to the innerText of a div in the HTML document.
Right now I get the random number, but I have to refresh the page to get a new one since it keeps outputting the same one if I press it again.
const mathQuestion = document.getElementById('math-question')
const newNumbers = document.getElementById('new-btn')
newNumbers.addEventListener('click', setQuestion)
function setQuestion () {
mathQuestion.innerText = calc.toString();
console.log(calc);
}
var calc = Math.floor(Math.random() * 100) + 1;
Yes, it's very simple and probably not the easiest or even the correct way to do it, but I am at a loss here.
I suspect I need to run another function for reseting the text or something after ive set the innerText, but I don't really know where to start.
Currently, you only generate the random number once and when you click the button, you set the same number in the HTML. That is why you see the same number irrespective of how many times you click the button.
Number changes on page reload because each time page reloads, new random number is generated.
You need to re-generate the random number every time the button is clicked. To do this, move the random number generation code inside the event handler function and it should work as expected.
function setQuestion () {
var calc = Math.floor(Math.random() * 100) + 1;
mathQuestion.innerText = calc;
}
Also, there's no need to explicitly convert the number into a string.
Is there any way to make GIFs in Javascript without any library? I've searched half the internet and found nothing.
Note to potential downvoters
I know that this is a low-quality question. However, I believe that the usual reasons for not answering have been invalidated. Seeing as it has been almost a month since it was asked, I doubt I'll be doing their homework as it would probably be past due for weeks at this point. And as for them not taking the time to research this myself, I'm fixing the problem at its source by teaching them how to research it.
Answer
Note that I'm answering this assuming that you know some Javascript, but not all of it, and that you want to learn how to write code that you might not yet know how to do. If you're just looking for the solution, then feel free to copy-paste it or whatever. But reading through this and understanding the process I used to tackle this problem, like how to think through it and look things up, will help you in the future. If you learn how to learn, you'll be a lot better off.
Now, first of all, we need a way to display images. I know from experience that there are two main methods to do this. One involves using the canvas element to draw the image; this is the more complicated method. Method 2 uses the image tag, <img>. I assume this is the method you want. If you didn't know how to draw an image using HTML and Javascript, a simple google search (here's another) can clear that up. (Actually, the second one mostly returns the canvas method-- but you probably knew about the image tag already anyways.)
Next we need a way to change what image is displayed. Well, that should be as simple as changing the thing that tells the image what to display in the first place. The top result from the first example search is a nice documentation page-- perfect. Reading through, I get to this part:
HTML Images Syntax
In HTML, images are defined with the tag.
The tag is empty, it contains attributes only, and does not have a closing tag.
The src attribute specifies the URL (web address) of the image:
<img src="url">
Well that looks like it's what controls what the image is. So we simply have to make a Javascript script that changes this property regularly. To do this right, we need a JS method that will wait for a specified amount of time. Searching "javascript wait" in Google, I see the second result is from the same source webpage that told me about images, so I'll go with that one. In the docs, I see this:
The setInterval() Method
The setInterval() method repeats a given function at every given time-interval.
window.setInterval(function, milliseconds);
The window.setInterval() method can be written without the window prefix.
The first parameter is the function to be executed.
The second parameter indicates the length of the time-interval between each execution.
(It even gives an example!)
This seems to be what we want. Using this method, I can make a simple code to change between two images every second (explanatory comments to the right, scroll to see them better):
function changePicture(){ //Make the function that will change the pictures
var picture = document.getElementById('picture1'); //Get the picture element from the HTML
if(picture.src == "https://vignette.wikia.nocookie.net/starpolar/images/9/96/Paul_blart.jpg/revision/latest?cb=20150419171412"){ //If it's the Paul Blart picture then:
picture.src = "https://i.ytimg.com/vi/A5KWYdrOXDk/movieposter.jpg"; //Set it to the Bee Movie
} else { //If it's not Paul Blart (and is therefore probably the Bee Movie image):
picture.src = "https://vignette.wikia.nocookie.net/starpolar/images/9/96/Paul_blart.jpg/revision/latest?cb=20150419171412"; //Set it to Paul Blart
}
}
setInterval(changePicture, 1000); //Use the new method we learned about to schedule our picture-changing function to happen once every second
<!--This is the image that we will change.-->
<img id="picture1" src="https://vignette.wikia.nocookie.net/starpolar/images/9/96/Paul_blart.jpg/revision/latest?cb=20150419171412"/>
Now, that's a good start-- we can change between 2 different totally definitely random images.
But we need more. We don't want to code in every new image manually; what we need is an array. It's hard to know that through a search, but if you've taken a primer course or learned some JS on your own you should be pretty familiar with arrays and would probably realize that they are a good option here. So we set up the array with all the images we want it to change between (scroll to the right to see it all):
var gifImages = ["https://vignette.wikia.nocookie.net/starpolar/images/9/96/Paul_blart.jpg/revision/latest?cb=20150419171412","https://i.ytimg.com/vi/A5KWYdrOXDk/movieposter.jpg","http://content.tv3.ie/content/images/0647/1_165781.jpg","https://upload.wikimedia.org/wikipedia/en/thumb/4/47/Spongebob-squarepants.svg/1200px-Spongebob-squarepants.svg.png","http://i0.kym-cdn.com/entries/icons/mobile/000/016/958/Dankkkk.jpg"];
Then we need to change our original function. It should cycle through this array of images; to do this, we'll need to make a variable to hold the position in the array.
var currentFrame = 0; //Call it a frame because we're making a gif and every image (so every array index) will be a frame
function changePicture(){
currentFrame++;
}
This should work for now, let's test it:
//Set up the array of frames
var gifImages = ["https://vignette.wikia.nocookie.net/starpolar/images/9/96/Paul_blart.jpg/revision/latest?cb=20150419171412","https://i.ytimg.com/vi/A5KWYdrOXDk/movieposter.jpg","http://content.tv3.ie/content/images/0647/1_165781.jpg","https://upload.wikimedia.org/wikipedia/en/thumb/4/47/Spongebob-squarepants.svg/1200px-Spongebob-squarepants.svg.png","http://i0.kym-cdn.com/entries/icons/mobile/000/016/958/Dankkkk.jpg"];
var currentFrame = 0; //Call it a frame because we're making a gif and every image (so every array index) will be a frame
function changePicture(){
document.getElementById("picture1").src = gifImages[currentFrame]; //Get the gif element and set its source to the current frame
currentFrame++; //Increase the current frame by 1
}
setInterval(changePicture,1000);
<!--This is the image that we will change.-->
<img id="picture1" src="https://vignette.wikia.nocookie.net/starpolar/images/9/96/Paul_blart.jpg/revision/latest?cb=20150419171412"/>
You should notice 2 things. The first is that the images have wildly different sizes and length/width ratios, resulting is the image changing size every time. The second thing you should notice is that when we run out of images, it doesn't loop back. Oops! (Side note: I actually made this mistake. Don't be discouraged by mistakes, we all make them!)
To remedy the first problem, we can look back to the HTML images documentation and see that there are two properties that can help us: width and height. These will lock the image into the specified dimensions. Frame sizes shouldn't be much of a problem with an actual gif, since the frames would probably all be the same size, but it doesn't hurt to be safe:
<img id="picture1" width="100px" height="100px" src="https://vignette.wikia.nocookie.net/starpolar/images/9/96/Paul_blart.jpg/revision/latest?cb=20150419171412"/>
The second problem is a bit harder. But looking through the code, we should be able to spot the bug fairly quickly. (Note: An experienced developer such as myself might be able to see a problem like this in a small, simple program almost instantly. Don't be discouraged if you can't; we all started somewhere and becoming a 1337 hax0r comes with time.)
If we look at how our program operates, we could say it works like this:
Loop forever:
Set the image to the current frame
Increase the frame
It becomes apparent that while we have a limited number of frames, we keep increasing the current one without going back down! Our progress through the gif would look like this (skipping to every 3rd frame and assuming 10 frames total):
|---------
---|------
------|---
---------|
---------- | <-- ???? oh no
This can be solved with a simple if statement that resets the current frame to 0 when we go past the end of our gif (line above is also shown for clarity):
currentFrame++; //Increase the current frame by 1
if(currentFrame >= gifImages.length){ //If we've gone past the end of our array of frames, then:
currentFrame = 0; //Reset back to frame 0
}
With those changes, our gif looks like this:
//Set up the array of frames
var gifImages = ["https://vignette.wikia.nocookie.net/starpolar/images/9/96/Paul_blart.jpg/revision/latest?cb=20150419171412","https://i.ytimg.com/vi/A5KWYdrOXDk/movieposter.jpg","http://content.tv3.ie/content/images/0647/1_165781.jpg","https://upload.wikimedia.org/wikipedia/en/thumb/4/47/Spongebob-squarepants.svg/1200px-Spongebob-squarepants.svg.png","http://i0.kym-cdn.com/entries/icons/mobile/000/016/958/Dankkkk.jpg"];
var currentFrame = 0; //Call it a frame because we're making a gif and every image (so every array index) will be a frame
function changePicture(){
document.getElementById("picture1").src = gifImages[currentFrame]; //Get the gif element and set its source to the current frame
currentFrame++; //Increase the current frame by 1
if(currentFrame >= gifImages.length){ //If we've gone past the end of our array of frames, then:
currentFrame = 0; //Reset back to frame 0
}
}
setInterval(changePicture,1000);
<!--This is the image that we will change.-->
<img id="picture1" width="100px" height="100px" src="https://vignette.wikia.nocookie.net/starpolar/images/9/96/Paul_blart.jpg/revision/latest?cb=20150419171412"/>
Now all we need to do is get the right frames into the array and speed it up! For a real gif, assuming this is a website you're making, the files will probably be named something like gif-frame-1, gif-frame-2, gif-frame-3, etc. Because of this, we can automate making the array, putting it into a for loop:
var gifImages = [];
for(var i=0;i<200;i++){ //Change 200 to the number of frames your gif has
gifImages[i] = "pictures/gif-frame-"+i+".png";
}
That code probably won't work with your website right away-- you have to change around the names of the images and number of frames and things-- but it should help you. If you specify where these pictures are, how they're named, how many there are, etc. then I could help you more, but I don't have enough information to write that part. Also note that this can be sped up about 50 times faster than it's going at the moment, but it looks weird without real frames to be used. For now, we can consider our final code to be:
//Set up the array of frames
var gifImages = ["https://vignette.wikia.nocookie.net/starpolar/images/9/96/Paul_blart.jpg/revision/latest?cb=20150419171412","https://i.ytimg.com/vi/A5KWYdrOXDk/movieposter.jpg","http://content.tv3.ie/content/images/0647/1_165781.jpg","https://upload.wikimedia.org/wikipedia/en/thumb/4/47/Spongebob-squarepants.svg/1200px-Spongebob-squarepants.svg.png","http://i0.kym-cdn.com/entries/icons/mobile/000/016/958/Dankkkk.jpg"];
var currentFrame = 0; //Call it a frame because we're making a gif and every image (so every array index) will be a frame
function changePicture(){
document.getElementById("picture1").src = gifImages[currentFrame]; //Get the gif element and set its source to the current frame
currentFrame++; //Increase the current frame by 1
if(currentFrame >= gifImages.length){ //If we've gone past the end of our array of frames, then:
currentFrame = 0; //Reset back to frame 0
}
}
setInterval(changePicture,100);
<!--This is the image that we will change.-->
<img id="picture1" width="100px" height="100px" src="https://vignette.wikia.nocookie.net/starpolar/images/9/96/Paul_blart.jpg/revision/latest?cb=20150419171412"/>
It's possible to touch it up (for example, you could move the function inside the setInterval itself) but this should work fine.
I hope this answer has helped you to learn how to figure these things out!
I ended up just writing a script to replace the image in a div every second. It's not technically a gif, but it works very similarly.
eval('var frame' + word + ' = 0;');
var bigFrame = 0;
setInterval(function(){ //everysecond
var noSpaces = input.replace(/\s/g, '');
var cLetter = noSpaces[bigFrame];
var thisSource = 'media/signs/alphabet/' + cLetter + '.jpeg';
$('#video').attr("src", thisSource);
$('#video').attr("alt", thisSource);
$('#video').attr("height", "350");
if(bigFrame + 1 >= noSpaces.length){
bigFrame = 0;
} else{
bigFrame = bigFrame +1;
}
for(word = 0; word < wordList.length; word ++){ //for every word
var currentFrame = eval('frame' + word);
currentWord = wordList[word];
currentWord = currentWord.toLowerCase();
console.log('current word is ' + currentWord);
var letterList = currentWord.split('');
var currentLetter = letterList[currentFrame];
var currentSource = 'media/signs/alphabet/' + currentLetter + '.jpeg';
var currentImage = "#" + eval('"image' + word + '"');
$(currentImage).attr("src", currentSource);
$(currentImage).attr("alt", currentSource);
$(currentImage).attr("height", "200");
if(currentFrame + 1 >= letterList.length){
eval('frame' + word + ' = 0');
} else{
eval('frame' + word + ' = currentFrame + 1;');
}
}
}, 1000);
I don't know if this is helpful, or even understandable, but it might help someone. Also, I haven't bothered to edit the code, so there are definitely bits that won't make sense and weird variable names.
A disclaimer: I'm not familiar with Javascript. I've merely cobbled together a basic understanding of what I need to do for this task from Stack Overflow and other resources. My apologies if something below is unclear.
My problem: I need to generate a random number between 0 and 8,764, using Javascript, that will not repeat itself between Qualtrics survey responses.
Currently, I've found code to create an array that contains all numbers between 0 and 8,764, shuffles the array, and pops the last number off the end of the array.
It then adds embedded data to Qualtrics with that popped number, and I can then pipe the embedded data into a Qualtrics question to display it to my survey respondent. See below:
Qualtrics.SurveyEngine.addOnReady(function()
{
for (var i = 0, ar = []; i < 8; i++) {
ar[i] = i;
}
ar.sort(function () {
return Math.random() - 0.5;
});
var randomnumber = ar.pop();
Qualtrics.SurveyEngine.addEmbeddedData("randomnumber", randomnumber);
});
However, as far as I can tell, this Javascript code "resets" itself between survey responses, meaning it will re-create and re-shuffle the array each time a new respondent enters the survey. I'd like to find a way to make it so that it will be impossible for a new respondent to see the same popped "randomnumber" as a previous respondent. So, if the first survey respondent saw a 1, then the next survey respondent could see any number besides a 1 (let's say they see a 100 instead), and the next respondent could see any number except a 1 or a 100, etc etc.
I think it's possible to use embedded data in Javascript code and manipulate it (see here). It seems like there might be a way to access the randomnumber embedded data and write Javascript code to not remove any numbers from the array that match one of the previously popped randomnumbers. I lack the technical knowledge to execute this, if it's even the best way to accomplish the task.
Any and all help appreciated!
You can do what you want with Advanced Randomization in Qualtrics.
Set up a multiple choice question with your numbers 0 through 8,764 as the choices. Then use Advanced Randomization to select a random subset of 1 from all the numbers and click "Evenly Present" (Evenly Present is what tells Qualtrics to use every number before reusing any). Use JavaScript to hide the multiple choice question:
$(this.questionId).hide();
Now you can pipe your unique random number into a subsequent question. For example:
${q://QID1/ChoiceGroup/DisplayedChoices}
I am working on a portion of a project that I am trying to detect when certain divs hit each other. In the code that I made, that doesn't work, I basically say take the first div's left amount, compare it to the other div's left amount, if they are within a certain amount it triggers an alert. If I get that much to work I am going to implant a way to say that if the distance between the two divs is 0 then it will run a certain function. I am afraid the scope of this project is too big for me, even though I am basically at the last part, because I have spent hours researching a simple way to add collision detection, but everything I find looks like rocket science to me, that is why I tried to create my own way below. So in summary, what I want to know is why my collision detection code doesn't work, how I can make it work if possible, and if not possible what is the next best option that I should use.
//Collision
function collision(){
var tri = $('#triangle');
var enemyPos = $('.object1').css('left');
var minHit = enemyPos - 32.5;
var maxHit = enemyPos + 32.5;
var triLoc = tri.css('left');
if(triLoc > minHit && triLoc < maxHit){
alert('hit');
}
}
collision();
}
}
full code: https://jsfiddle.net/kc59vzpy/
If the code you have above is definitely where the problem is, then you need to look at the enemyPos variable. Getting the left position also adds px, so enemyPos is 100px or something like that. When you add 32.5, you get 100px32.5 and when you subtract you get NaN, neither of which you want.
Before you add or subtract, use enemyPos = parseInt($('.object1').css('left')); to turn it into an actual number.
I want a gallery somehow similar like the link below.
https://securemg.lincoln.com/musicselfie/gallery
The codes are too complex. so I dont know how to do it.
Thanks
I don't know if you're a beginner, anyway, is not complicated create random image, for example:
<script language="JavaScript">
<!--
img = new Array()
ran = Math.floor(4 * Math.random());
img[0] = 'immagine1.jpg';
img[1] = 'immagine2.jpg';
img[2] = 'immagine3.gif';
img[3] = 'immagine4.jpg';
document.write("<img src=\""+img[ran]+"\">");
// -->
</script>
I've a data structure to store the web address of the image, has been used a vector, in which I included a link to each "cell" of the vector. Then, using "ran" (random number between 1 and 4) do the choice of the image to display.
The method Math.floor (number) displays the nearest whole to "number".
ES: Math.floor (12.5) becomes 12.
The random number is generated by switching to Math.floor with the Math.random() method (see Example Math.random).
To get a random number between 0 and 4 multiply the random number returned by math.random () for 4.
However you could play around CSS and other tricks to javascript in order to build not only a good code to show the images but also to create a truly personalized slide as the site. You could also take the CSS site and adapt them to your code ...
Well with this consideration the example should be clear.