I made a jquery script and I need help on how to make it auto switch between the 4 [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am trying to make this script auto change between the four after 30 seconds, I am not to good at jquery but I wanted to give it a try. This is all on a .php page I am using to bring up the javascript from my other folders.
<div id="subnavi">
<div id="subnavi-user">
<div style="margin-top:7px"><b>Fact:</b> <script language="JavaScript">
var r_text = new Array ();
r_text[0] = "{hotelName} was founded in 2011 by Kyle";
r_text[1] = "{hotelName} strives to remain as professional as possible.";
r_text[2] = "{hotelName} will only keep on growing if you vote daily!";
r_text[3] = "Purchasing VIP in the forums helps with the monthly server costs.";
r_text[4] = "{hotelName} Is a new and developing RP!";
window.setInterval(function(){
var i = Math.floor(4 * Math.random())
document.write(r_text[i]);
var random = r_text[1];
}, 5000);
</script>
</div>
</div>
<div id="subnavi-search">
<div id="subnavi-search-upper">
<ul id="subnavi-search-links">
<li>Sign Out</li>

I am not sure if this is what you are looking for but here it is:
This script will run every time you reload the page. IF you need it to work in a different way just update your question and i will update my script.
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
var r_text = new Array();
r_text[0] = "Hello";
r_text[1] = "Test";
r_text[2] = "We are the lions";
r_text[3] = "Fight";
r_text[4] = "Switch!";
window.setInterval(function(){
var i = Math.floor(5 * Math.random())
var random = r_text[i];
$('#r_text').html(random);
}, 5000); // you can change the interval here
The HTML part
<div id="r_text"></div>
Check this out here
Update
Change your Math.floor to count to 5 because your array has 5 elements in it not 4
Update 2 Your file should look like something like this
<!Document html>
<head>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
var r_text = new Array();
r_text[0] = "Hello";
r_text[1] = "Test";
r_text[2] = "We are the lions";
r_text[3] = "Fight";
r_text[4] = "Switch!";
window.setInterval(function(){
var i = Math.floor(5 * Math.random())
var random = r_text[i];
$('#r_text').html(random);
}, 5000); // you can change the interval here
</script>
</head>
<body>
//Add your html/php code here and pick a place where to show the response of your function. Something like <div id="r_text"></div>
</body>
</html>

Related

How to display random images from array [duplicate]

This question already has answers here:
Getting a random value from a JavaScript array
(28 answers)
Closed 5 years ago.
So im creating an app that helps you decide on a movie to watch. one of the functions on the app is a randomizer button which randomly displays a movie based on the genre you selected but not sure how to display the image. heres what i have so far. Thank you!
<body>
<button id='randomBut'>RANDOMIZE</button>
<div id='movieImg'><img src='movie1.svg'></div>
</body
<script>
var randomizer = document.getElementById("randomBut");
var randimg = document.getElementById("movieImg");
var movieimages = ["movie1.svg", "movie2.svg", "movie3.svg"];
document.getElementById("movieImg").innerHTML = movieimages;
randomizer.addEventListener("click", function(){
var randimg = document.createElement("img");
randimg.src = "movieimages" ;
</script>
put the id on the image and then create a random number generator. use that random number and choose the image from the array and assign it to the image src
<button id='randomBut'>RANDOMIZE</button>
<div><img id='movieImg' src='http://placehold.it/100x100'></div>
<script>
var randomizer = document.getElementById("randomBut");
var randimg = document.getElementById("movieImg");
var movieimages = ["http://placehold.it/100x100", "http://placehold.it/150x100", "http://placehold.it/100x150"];
randomizer.addEventListener("click", function(){
var randNum = Math.floor(Math.random() * movieimages.length) + 0
randimg.src = movieimages[randNum] ;
});
</script>

JavaScript Display Image and Text Rather than Alert Message

I'm a newbie and starting to learn coding. I have a question regarding the famous "How many fingers am I holding up?" project. So instead of an alert message, I want the actual image of a finger with 1-5 and the message of either it is correct or not.
I think there are jquery codes.. but i don't want to jump to jquery and learn hardcore javascript first. I'm stuck with creating image Arrays and cannot manage to make the image come up.
Here's the code I have:
<body>
<p>How many fingers am I holding up?</p>
<p><input type="text" id="guess"> <button id="checkGuess">Guess!</button></p>
<div id="image"></div>
<div id="text"></div>
<script type="text/javascript">
var imgArray = new Array();
imgArray[1] = new Image();
imgArray[1].src="images/1.png";
imgArray[2] = new Image();
imgArray[2].src="images/2.png";
imgArray[3] = new Image();
imgArray[3].src="images/3.png";
imgArray[4] = new Image();
imgArray[4].src="images/4.png";
imgArray[5] = new Image();
imgArray[5].src="images/5.png";
document.getElementById("checkGuess").onclick = function() {
var randomNumber = Math.random();
randomNumber = randomNumber * 6;
randomNumber = Math.floor(randomNumber);
if (document.getElementById("guess").value == randomNumber) {
doument.getElementById("image").innerHTML = imgArray[num] + alert("Well done! You got it!");
} else {
alert("Nope! The number was " + randomNumber);
}
}
</script>
</body>
Thanks Guys! Appreciate your help!
Cheers!
Char
I think you can do something like this fiddle.
https://jsfiddle.net/6a4p2po4/5/
What I did was to make the imgArray an array of src of images, and updated the img src depending on the result.
I noticed while working you have some typos and unset variables.
For example, "doument" is misspelled, and "'num'" is not set.
doument.getElementById("image").innerHTML = imgArray[num] + alert("Well done! You got it!");
It might help to use Chrome or another browser to check the console (F12). It will definitely help you debug.
Using console.log() instead of alert() will make it show up as a log instead of a pop up window, so you can check the values that you stored on variables, i.e. console.log(randomNumber);
You're on the right track! Good job so far!
You said
So instead of an alert message, I want the actual image of a finger...
which leads me to think that we never want to call alert() and instead want to display an image and a message. Assuming I am correct in my supposition, here is some code...
<html>
<head>
<!-- some other stuff... -->
<!-- CSS is your friend! -->
<style>
.hidden {
display: none;
}
</style>
</head>
<body>
<p>How many fingers am I holding up?</p>
<p>
<input type="text" id="guess">
<button id="checkGuess" onclick="checkGuess()">Guess!</button>
</p>
<div id="image">
<!-- We can put the images in here then just hide/show them, which is much easier! -->
<img class="hidden" src="./images/1.png"/>
<img class="hidden" src="./images/2.png"/>
<img class="hidden" src="./images/3.png"/>
<img class="hidden" src="./images/4.png"/>
<img class="hidden" src="./images/5.png"/>
</div>
<div id="text"></div>
<script>
function checkGuess(){
var actualFingerCount = Math.floor(Math.random() * (5 - 1 + 1)) + 1;
//the `+` casts the value into a number
var userGuess = +document.getElementById('guess').value;
//get all of our images
var images = document.querySelectorAll('img');
//hide all of them just to be safe
images.forEach(function(img){
img.classList.add('hidden');
});
//then show the one we want
images[actualFingerCount - 1].classList.remove('hidden');
var textDiv = document.getElementById('text');
if(actualFingerCount === userGuess) {
textDiv.innerHTML = 'Yay, you got it!';
}
else {
textDiv.innerHTML = 'Whoops, try again! The number was ' + actualFingerCount + '.';
}
}
</script>
</body>
</html>
And there you have it!
Notice that this is a contrived example. In the real world, you should never define functions in the global namespace, nor should you rely on elements being in a certain order, like I did with the images. Maybe you can take it and improve it to follow better coding standards!

how to use javascript pass value to php or txt file [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 7 years ago.
<?php
$myFile = "new.txt";
$fileOpen = fopen($myFile, 'w') or die("can't open file");
$stringData = "total;
fwrite($fileOpen, $stringData);
fclose($fileOpen);
?>
<html>
<head>
<script>
var defaultValue = 5;
var plus = 1;
var max = 100;
var total = defaultValue;
window.setInterval(
function () {
if (total > max){
total = defaultValue;
}
document.getElementById("demo1").innerHTML = total;
total = total + plus;
}, 1000);
</script>
</head>
<body>
<p id="demo"></p>
<p id="demo1"></p>
<p id="demo2"></p>
</body>
</html>
I need save the total value into txt file, and than read by txt. so that, when i refresh the browser will not re-looping, but how i get value from javascript or from div into php? (read and write per second)
You can use an AJAX request to a php file where you can save it to txt file or a database.
But, making an ajax call every second would be unnecessary traffic. Instead I think using window.onunload would be a better choice, which saves the value when the page is redirected or refrshed.
You can use the jquery bind for that as below:
$(window).bind('beforeunload', function(){
// make ajax call here
});
If you want to save very small amount of data, like here you need to save the value of total then you can use HTML 5 provided local storage which can easily contain on average 5 MB of data. Its nothing but a storage in each domain(origin) which can store 5 MB on any individual client.
It is very easy to use like.
enter code here
// Store
localStorage.totalValueHolder = total;
// Retrieve
var totalStringValue = localStorage.totalValueHolder;
total = parseInt(totalStringValue, 10)
OR
// Store`enter code here`
localStorage.setItem("totalValueHolder ", total);
// Retrieve
var totalStringValue = localStorage.getItem("totalValueHolder");
total = parseInt(totalStringValue, 10)
Hope it will answer your question. If you have further query please let us know.

Need Help: Make the quiz random [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm having trouble making the questions random. If you could help, it would be awesome!
(If you have spear time; I've been given the task to mark correct answer with a green feather and wrong answers with red feather, for instance, if you get 3 correct and 2 wrong. It will show 3 green feathers and 2 red feathers as score.) Thank you!
<script type="text/javascript">
var questions = [
['firstcar.gif','0'],
['secondcar.gif','1'],
['thirdcar.gif','2'],
['firstcar.gif','0'],
['secondcar.gif','1'],
['thirdcar.gif','2'] // Note: no comma after last entry
];
var qNo = 0;
var correct = 0;
var cnt = 0;
function NextQuestion(response) {
if ((qNo < questions.length) && (response == questions[qNo][1])) {
correct++;
}
document.getElementById('score').innerHTML = 'Correct ' + correct + ' of 6 questions';
qNo++;
if (qNo < questions.length) {
document.getElementById('Pic').src = questions[qNo][0];
cnt++;
}else{
alert('Quiz is done. You got ' + correct + ' points!');
}
}
onload = function() {
document.getElementById('Pic').src = questions[0][0];
}
</script>
</head>
<body>
<div align="center">
<h1>Which car is it?</h1>
<img src="" id="Pic" height="200" width="250">
<p>Is it
<button onclick="NextQuestion('0')">Red</button>
<button onclick="NextQuestion('1')">Black</button>
<button onclick="NextQuestion('2')">Yellow</button>
<p>Your score: <br>
<span id="score"></span>
</div>
</body>
</html>
Well, your questions are in an array. So what you should be researching is how to randomise the order of an array.
questions.sort(function() { return Math.floor(Math.random() * 2); });

How short can this script be and still achieve the same thing - display a message "loading.." followed by an extra period every 1 second for 7 seconds [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
<script>
var dot = ".";
var counter = 0;
var message = "Loading Page";
function writeLoadingMessage(){
if (counter > 6) return;
setTimeout('writeMessage();',1000);
}
function writeMessage(){
document.getElementById('loadingMessageSpan').innerHTML = message + dot;
message += dot
counter++
writeLoadingMessage();
}
</script>
<BODY>
<span style="font-weight:bold;" id="loadingMessageSpan"></span>
<SCRIPT>writeLoadingMessage();</SCRIPT>
</BODY>
(function(){var i=6,a=setInterval(function(){document.getElementById('loadingMessageSpan').innerHTML+=".";!i--&&clearInterval(a);},1E3)})()
You will need to have Loading already in your span tag. As a note it is pointless to worry about getting it this small though. Also, the page will will have to be already loaded.
If you want it shorter: http://jsfiddle.net/pimvdb/wBFSy/.
<script>
var counter = 0;
function writeMessage() {
document.getElementById('loadingMessageSpan').innerHTML += ".";
if(++counter < 7) {
setTimeout(writeMessage, 1000);
}
}
window.onload = writeMessage;
</script>
<body>
<span style="font-weight:bold;" id="loadingMessageSpan">Loading Page</span>
</body>
Minifying also helps :)
var a=0;function b(){document.getElementById("loadingMessageSpan").innerHTML+=".";++a<7&&setTimeout(b,1E3)}window.onload=b
1) User setInterval instead.
2) Just set the message once and append . to end
3) Put all the js at the bottom
<body>
<span style="font-weight:bold;" id="loadingMessageSpan">Loading Page</span>
<script type="text/javascript">
var counter = 0;
var id = setInterval(function(){
document.getElementById('loadingMessageSpan').innerHTML += ".";
if(++counter>6) {
clearInterval(id);
}
}, 1000);
</script>
</body>
If you really want it short you can go this route:
<BODY>
<span style="font-weight:bold;" id="loadingMessageSpan">Loading Page</span>
<script>
var counter = 0;
var interval = setInterval(function(){
document.getElementById('loadingMessageSpan').innerHTML += ".";
if(++counter > 6)
clearInterval(interval);
},1000)
</script>
</BODY>
http://jsfiddle.net/kc3fb/2/

Categories