javascript random flashing words - javascript

Here's a fun little script I'm trying to make. Flash words from an array with random colors from another array. (I'm mostly thinking about having a moving bg type deal.)
I'm having problems with creating some sort of loop to cause the words to "flash/change" so far all it does is change on page reload.
*new*
Well I changed it so now it is just one function... and it WORKS!! but it seems that it uses the browsers memory or something and crashes.... oops... is there a clear memory or something for javascript that I should use??
<html>
<head>
<style>
body
{
color:black;
}
#quotes
{
}
</style>
</head>
<body>
<script type="text/javascript">
function showQuote()
{
pickWords =
[
"Hi!",
"Welcome!",
"Hello!"
]
var word22 = pickWords[Math.floor(Math.random()*pickWords.length)];
pickColors =
[
"#aa2233",
"#00cc44",
"#F342AA"
]
var Color22 = pickColors[Math.floor(Math.random()*pickColors.length)];
var Top22 = (Math.floor(Math.random()*800));
var Left22 = (Math.floor(Math.random()*800));
var style33 = '<h4 style="padding-bottom:0px; padding-top:'+Top22+'px; padding-left:'+Left22+'px; font-size: 2.3em; color:'+Color22+';">';
var style34 = '</h4>';
var finWord22 = style33 + word22 + style34;
var duration = 400;
document.getElementById("quotes").innerHTML=finWord22;
setInterval('showQuote()',duration);
}
onload = function()
{
showQuote();
}
</script>
<div id="quotes"></div>
</body>

You would need to 'pickword' inside the showQuote() function.
Right now, you are picking a word onload, and use that word on every timeout.
Wrap your whole code into a function and call that function on load.
function ShowQuote(){
//...
setTimeout(ShowQuote, duration);
}
ShowQuote();

You're calling setinterval in the function, where as you should use settimeout. That should help you out with the crashing :P

Related

JavaScript Countdown with argument passing in

You are given an integer called start_num. Write a code that will countdown from start_num to 1, and when the countdown is finished, will print out "Liftoff!".
I am unsure how to do this and keep getting stuck.
This is the code I am provided with at the beginning of the problem:
function liftoff_countdown(start_num) {
// My code goes here!
}
And then they want me to pass in a value such as the 5:
liftoff_countdown(5);
And then this will be my output:
6
5
4
3
2
1
"Liftoff!"
Thanks!
Look at this maybe help you to create your own code
make two file in a same folder (script.js and index.html)
index.html
<!doctype html>
<head>
<title>Countdown</title>
</head>
<body>
<div id="container">
<div id="inputArea">
</div>
<h1 id="time">0</h1>
</div>
<script src="script.js"></script>
</body>
</html>
script.js
var valueRemaining;
var intervalHandle;
function resetPage() {
document.getElementById("inputArea").style.display = "block";
}
function tick() {
var valueDisplay = document.getElementById("time");
valueDisplay.innerHTML = valueRemaining;
if (valueRemaining === 0) {
valueDisplay.innerHTML = "Liftoff!";
clearInterval(intervalHandle);
resetPage();
}
valueRemaining--;
}
function startCountdown() {
var count = document.getElementById("count").value;
if (isNaN(count)) {
alert("Please enter a number!");
return;
}
valueRemaining = count;
intervalHandle = setInterval(tick, 1000);
document.getElementById("inputArea").style.display = "none";
}
// as soon as the page is loaded...
window.onload = function () {
var inputValue = document.createElement("input");
inputValue.setAttribute("id", "count");
inputValue.setAttribute("type", "text");
// create a button
var startButton = document.createElement("input");
startButton.setAttribute("type", "button");
startButton.setAttribute("value", "Start Countdown");
startButton.onclick = function () {
startCountdown();
};
// add to the DOM, to the div called "inputArea"
document.getElementById("inputArea").appendChild(inputValue);
document.getElementById("inputArea").appendChild(startButton);
};
in this example you have many things to understand how javascript works behind scenes.
How about this...
function liftoff_countdown()
{
var span=document.getElementById('num');
var i=document.getElementById('num').innerText;
i=i-1;
span.innerText=i;
if (i==0){
span.innerText='Liftoff!';
clearInterval(count_down)
}
}
var count_down=setInterval(liftoff_countdown,1000);
<span id="num">5</span>
You can achieve this with a simple recursive function and the use of setTimeout to recursively call the function after a time lapse of 1 second.
function lift_off(seconds) {
if(seconds == 0) {
console.log('liftoff');
} else {
console.log(seconds--);
setTimeout(function(){lift_off(seconds);},1000);
}
}
lift_off(10);
Here is a working JSFiddle
Preface
A lot of these answers seem to be focused on doing things with timers and recursion. I do not believe that is your intent. If your only goal is to print those values to the console, you could simply do the following (see the comments for an explanation).
The Answer
function liftoff_countdown(start_num) {
// Loops through all values between 0 and start_num
for(int i = 0; i < start_num; i++) {
// Prints the appropriate value by subtracting from start_num
console.log( start_num - i );
}
// Upon exiting the loop, prints "Liftoff!"
console.log("Liftoff!");
}
Additional Thoughts
You could just as easily loop backwards through the numbers instead of forward like so:
for(int i = start_num; i > 0; i--){
console.log( i );
}
I tend to lean towards iterating forwards just because it's more common, and it's often easy to confuse readers of your code if they gloss over the loop initialization.
Additionally, I am working with the assumption that when you say "print" you mean "console.log()". If this is untrue, you could of course use any other function in its place (e.g. alert( "Liftoff!" );).

Trying to get an image to show dependent on a result of a previous function

I am very new to javascript so please be very gentle and explain things as much as you can be bothered to please ;)
I am trying to create a button that will randomly select a name from a list and display it with an image of the person (hero if you know what this is for).
I have so far the a button that runs a function that selects the name randomly, I'm just having difficulty getting the image to show...
<html>
<body>
<button onclick="myFunction()">Random</button>
<script>
function myFunction()
{
var strings = ['Axe', 'Bane', 'Batrider' ];
var randomIndex = Math.floor(Math.random() * strings.length);
var randomString = strings[randomIndex];
document.write(' ' + randomString);
}
</script>
<script type="text/javascript">
var picData = [
['Axe','http://ponky.org/~ropedy/DC/icons/heroes/Axe.png'],
['Bane','http://ponky.org/~ropedy/DC/icons/heroes/Bane.png'],
['Batrider','http://ponky.org/~ropedy/DC/icons/heroes/Batrider.png']
];
window.onload=myFunction(){
var cookieValue = 'Axe';
for(i=0; i < picData.length; i++){
if(cookieValue == picData[i][0]) {
document.getElementById('imgCont').src = picData[i][1];
i=picData.length;
}
}
}
</script>
<div>
<img id="imgCont" src="" alt="" />
</div>
Change your window.onload to something like this:
window.onload = function() {
myFunction();
// then the rest of your stuff to set the .src
}
But it looks like what you actually want to do is move the stuff for setting the .src to a separate function so you can call it in response to your button click.
Something like:
var picData = [
['Axe','http://ponky.org/~ropedy/DC/icons/heroes/Axe.png'],
['Bane','http://ponky.org/~ropedy/DC/icons/heroes/Bane.png'],
['Batrider','http://ponky.org/~ropedy/DC/icons/heroes/Batrider.png']
];
function myFunction()
{
var randomIndex = Math.floor(Math.random() * picData.length);
var randomString = picData[randomIndex][0];
document.write(' ' + randomString); // Note: I'd generally avoid document.write
document.getElementById('imgCont').src = picData[randomIndex][1];
}
Now you can call this both from onload and onclick if you want to give you a random image when first loaded and a random image each time you click the button.
For easy to read and maintain code, I'd also replace your array or arrays with an array of object literals:
var picData = [
{name:'Axe', imageUrl:'http://ponky.org/~ropedy/DC/icons/heroes/Axe.png'},
{name:'Bane', imageUrl:'http://ponky.org/~ropedy/DC/icons/heroes/Bane.png'},
{name:'Batrider', imageUrl:'http://ponky.org/~ropedy/DC/icons/heroes/Batrider.png'}
];
Why? Because now instead of:
picData[randomIndex][1];
I can write:
picData[randomIndex].imageUrl;
Which is a lot more readable and makes it clearer what you are actually doing.

How to run and display processing code (currently in part of the document.body) in an html canvas?

NOTE: I know I can import .pde files but I need to run code on screen so I will not be using this.
My three following attempts failed. I do not know which one was closer to achieving and I do not prefer one as long as it produces desired result. Appreciate the help by helping me get any of the attempts working/suggesting a new one.
1ST ATTEMPT) - use getText function written below but then some text that is not code can be found in the resulting jscode variable and thus the processing instance does not work.
function getText(n) {
var s = [];
function getStrings(n, s) {
var m;
if (n.nodeType == 3) { // TEXT_NODE
s.push(n.data);
}
else if (n.nodeType == 1) { // ELEMENT_NODE
for (m = n.firstChild; null != m; m = m.nextSibling) {
getStrings(m, s);
}
}
}
getStrings(n, s);
var result = s.join(" ");
return result;
}
var processingCode = getText(document.body)
processingCode.replace(/<[^>]+>¦&[^;]+;/g,'').replace(/ {2,}/g,' ');
var jsCode = Processing.compile(processingCode).sourceCode;
alert(jsCode);
var canvas = document.getElementById("mysketch");
var processingInstance = new Processing(canvas, jsCode);
....
<span class="sketch">
<canvas id="mysketch"></canvas>
</span>
2ND ATTEMPT) Same as above but added a tag with id="all_processing_code" but couldn't figure out how to get the text within anyway. This did not work:
var processingCode = getText(document.getElementbyId(all_processing_code));
3RD ATTEMPT) Removed getText and tried to use JQuery text() to isolate the code. Was having trouble mixing JS and Jquery though. Tried different stuff and none worked. What would be appropriate way to mix it in? What script type should I use? This was confusing.
<script type="text/jquery">
var processingCode = $('#all_processing_code').text();
//processingCode.replace(/<[^>]+>¦&[^;]+;/g,'').replace(/ {2,}/g,' ');
var jsCode = $.Processing.compile(processingCode).sourceCode;
alert(jsCode);
var canvas = $(#'mysketch');
var processingInstance = new $.Processing($('canvas'), $('jsCode'));
}
</script>
First, check if your processing code is wrapped by an html element (like a div or something else) with an id. If it isn't, please do it!
For exemple:
<div id="mycode">
void setup() {
background(0);
}
</div>
After this, check if you have the getProcessingSketchId() function declared in your code. Processing IDE in JavaScript mode already exports html files with that function. If there isn't, please declare it inside your <head>:
<script type="text/javascript">
// convenience function to get the id attribute of generated sketch html element
function getProcessingSketchId () { return 'yourcanvasid'; }
</script>
You can include JQuery from google api including this line in your html before you use JQuery:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
// convenience function to get the id attribute of generated sketch html element
function getProcessingSketchId () { return 'yourcanvasid'; }
</script>
Assuming that you want to run your processing code when the page just has loaded, just append this code after the getProcessingSketchId() declaration.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
// convenience function to get the id attribute of generated sketch html element
function getProcessingSketchId () { return 'yourcanvasid'; }
$(document).ready(function() {
new Processing(getProcessingSketchId(), $('#mycode').html());
});
</script>
You can create this code inside any other <script type="text/javascript">.
At the end, you will have something like this:
<html>
<head>
<!-- Your title, meta tags, stylesheet and all other stuff here -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
// convenience function to get the id attribute of generated sketch html element
function getProcessingSketchId () { return 'yourcanvasid'; }
$(document).ready(function() {
new Processing(getProcessingSketchId(), $('#mycode').html());
});
</script>
</head>
<body>
<div id="mycode">
void setup() {
background(0);
}
</div>
</body>
</html>

I can't get my image slideshow to work using JavaScript

I am trying to create a simple image slideshow type thing with the Javascript code below, but what it is doing is displaying the first image in the webpage with everything else, then after 5 seconds clearing the page and displaying the same image, then again every 5 seconds except it doesn't clear the page anymore.
The JavaScript:
var waiPics=new Array();
waiPics[0]='images/path.jpg';
waiPics[1]='images/gorse.jpg';
waiPics[2]='images/stream.jpg';
waiPics[3]='images/pines.jpg';
waiPics[4]='images/stump.jpg';
var time;
function timeUp() {
delete document.write();
nextPic();
}
function nextPic() {
var picNum=0;
if (picNum = waiPics.length) {
picNum=0;
}
else {
picNum++;
}
document.write('<img src="'+waiPics[picNum]+'" title="Waipahihi" alt="Waipahihi">');
time=setTimeout("timeUp()",5000);
}
The HTML:
<script type="text/javascript">
<!-- Begin
nextPic();
// End -->
</script>
Im not very experienced with Javascript, so thanks in advance for the help.
picNum will always be zero because it is declared inside a function and will set to zero every time the function is called. Even if you fix this, your condition is wrong:
if (picNum = waiPics.length) {
The conditional should be:
if (picNum === waiPics.length) {
The single = sign assigns the length to picNum, then converts to a boolean. The array length is nonzero, so it becomes true value. It then resets to zero every time.
Consider using JSLint to check your code for errors and to suggest improvements. It flagged the issue:
"Expected a conditional expression and instead saw an assignment."
if (picNum = waiPics.length) {
In fact, after using JSLint on your code and examining its suggestions, I would use something more like this:
// New array creation syntax
var waiPics = ['images/path.jpg', 'images/gorse.jpg', 'images/stream.jpg', 'images/pines.jpg', 'images/stump.jpg'];
var picNum = 0; // Declare outside inner function so its value is preserved
var myDiv = document.getElementById("ssdiv"); // Get a div element to insert picture into
function nextPic() {
if (picNum === waiPics.length) { // Proper comparison
picNum = 0;
} else {
picNum += 1;
}
// Set picture into div element without evil document.write
myDiv.innerHTML = '<img src="' + waiPics[picNum] + '" title="Waipahihi" alt="Waipahihi">';
// No longer need timeUp; also don't use eval syntax
setTimeout(nextPic, 5000);
}
Assigning innerHTML avoids various problems with document.write and also does not require your page to refresh to change slideshow images. Also note other comments.
You need to use the comparison operator ('==') instead of assigning ('=') here:
//if (picNum = waiPics.length) {
if (picNum == waiPics.length) {
have a look at this example...
http://jsfiddle.net/DaveAlger/eNxuJ/1/
to get your own slideshow working, copy and paste the following html into any text file and save it as slides.html
you can add any number of <img> elements inside the <div class="slideshow">
enjoy!
<html>
<body>
<div class="slideshow">
<img src="http://davealger.info/i/1.jpg" />
<img src="http://davealger.info/i/2.bmp" />
<img src="http://davealger.info/i/3.png" />
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
$(function(){
$('.slideshow img:gt(0)').hide();
setInterval(function(){$('.slideshow :first-child').fadeOut(2000).next('img').fadeIn(2000).end().appendTo('.slideshow');}, 4000);
});
</script>
<style>
.slideshow { position:relative; }
.slideshow img { position:absolute; left:0; top:0; }
</style>
</body>
</html>

Javascript Onclicks not working?

I have a jQuery application which finds a specific div, and edit's its inner HTML. As it does this, it adds several divs with onclicks designed to call a function in my JS.
For some strange reason, clicking on these never works if I have a function defined in my code set to activate. However, it works fine when calling "alert("Testing");".
I am quite bewildered at this as I have in the past been able to make code-generated onclicks work just fine. The only thing new here is jQuery.
Code:
function button(votefor)
{
var oc = 'function(){activate();}'
return '<span onclick=\''+oc+'\' class="geoBut">'+ votefor +'</span>';
}
Elsewhere in code:
var buttons = '';
for (var i = 2; i < strs.length; i++)
{
buttons += button(strs[i]);
}
var output = '<div name="pwermess" class="geoCon"><div class="geoBox" style=""><br/><div>'+text+'</div><br/><div>'+buttons+'</div><br/><div name="percentages"></div</div><br/></div>';
$(obj).html(output);
Elsewhere:
function activate()
{
alert("Testing");
}
You may want to take a look at jQuery.live(eventType, eventHandler), which binds an event handler to objects (matching a selector) whenever they are created, e.g.:
$(".somebtn").live("click", myClickHandler);
Follows a dummy example, may be this can help you.
<!DOCTYPE html>
<html>
<head>
<style>
</style>
<script src="http://cdn.jquerytools.org/1.2.5/jquery.tools.min.js"></script>
<script type="text/javascript">
$(function() {
$('.go-right').click(function(){
c="Hello world";
$("#output").html(c);
});
});
</script>
</head>
<body >
<div id="output"></div>
<a class="go-right">RIGHT</a>
</body>
</html>
Change this:
var oc = 'function(){activate();}'
To be this instead:
var oc = 'activate();'

Categories

Resources