JavaScript for loop not changing link text - javascript

I have a nested for loop inside a for loop that is supposed to change the link text to a random number between 1 and 5. The ID of the links are "aX_Y", X and Y being numbers. The links are arranged in a 4x3 square. The problem is that the random numbers for the link text is only displayed for the last row:
<!DOCTYPE html>
<html>
<head>
<title>RISK</title>
<style type="text/css" media="screen">
a:link, a:visited {color: #eee;border:3px solid #ccc;text-decoration:none;padding:20px;}
.one {background: #7B3B3B;}
.two {background: #547980;}
#status {color: #eee;padding:1px;text-align:center}
.current {border:3px solid #000;}
</style>
<script type="text/javascript" charset="utf-8">
var xTurn = true;
var gameOver = false;
var numMoves = 0;
function newgame()
{
var status = document.getElementById('status');
numMoves = 0;
gameOver = false;
xTurn = true;
status.innerHTML = 'Player One\'s turn';
for(var x = 0; x < 4; x++)
{
for(var y = 0; y < 3; y++)
{
document.getElementById('a' + x + '_' + y).innerHTML = Math.floor(Math.random()*5 + 1);
console.log('a' + x + '_' + y);
}
}
}
function current(selected)
{
var status = document.getElementById('status');
var value = selected.value;
}
//document.getElementById("status").setAttribute("class", "two");
</script>
<meta name="viewport" content="user-scalable=no, width=device-width" />
</head>
<body onload='newgame();'>
<p id="status" class="one">Player One's turn</p>
<br />
<br />
<br />
<br /><br />
<p><input type="button" id="newgame" value="New Game" onclick="newgame();" /></p>
</body>
</html>
Here is a direct link to it:
https://dl.dropbox.com/u/750932/iPhone/risk.html

This change to your CSS fixes the issue:
a:link, a:visited
{
color: #eee;
border:3px solid #ccc;
text-decoration:none;
display:inline-block;
padding:20px;
}

(Tested in Firefox)
Your Javascript code is fine; all of the grid squares are getting populated with random numbers. What I am seeing instead is that each row of links is overlapping the previous row, so the numbers in the previous row are being hidden.
Is the overlapping intentional?

All the random numbers are being generated correctly. The top 2 rows are just hidden due to your CSS rules. You can prove this by making the following CSS change:
Change the line that looks like this:
a:link, a:visited {color: #eee;border:3px solid #ccc;text-decoration:none;padding:20px;}
to this:
a:link, a:visited {color: #eee;border:3px solid #ccc;text-decoration:none;}
And voila, it's all working beautifully.

Heh, I'm pretty sure it is working...the other boxes are just overlapped by the ones in front and you can't see them. Firebug shows values inside all the boxes.
a {
display:block;
float:left;
}
br {
clear:both;
}
...though actually those top-level elements shouldn't be restyled like that necessarily, I'd put it all in a <div id="game"></div> and make them .game a and .game br.

Related

I cant make it so after 5 tries it counts as dead

I keep trying to make it work but it simply won't. Please help.
Btw I want it so that when you die it resets.
<!DOCTYPE html>
<html>
<head>
<style>
html,button{
font-family: monospace, monospace;
width:20%;
padding:0%;
margin:0%;
}
button{
text-align: left;
height:150px;
position:absolute;
background-color:transparent;
border:transparent;
outline:none;
}
div{
position:absolute;
transform:translate(20px,-40px);
}
</style>
<script>
var roll = 0;
function play(){//begin
var rep = Math.floor(Math.random() * 6);
if (rep == 0 && roll !== 6){
roll+=1
document.getElementById("hk").innerHTML = "._______<br>\\(#)----'<br>/ /\\<br>(_(<br>";
setTimeout(4000);
setTimeout(function(){
document.getElementById("hk").innerHTML = ",_______<br>\\(=)----*#<br>/ //<br>(_(<br> DEAD";
}, 500);
}else if (rep !== 0 || roll == 6){
document.getElementById("hk").innerHTML = "._______<br>\\(#)----'<br>/ /\\<br>(_(<br>";
setTimeout(function(){
document.getElementById("hk").innerHTML = ",_______<br>\\(=)----'<br>/ //<br>(_(<br>Click";
}, 500);
var roll = 0;
}
}//end
</script>
</head>
<body>
<h1>Russian<br>Roulette</h1>
<button onClick="play()">
<div id="hk">
,_______<br>
\(=)----'<br>
/ /\<br>
(_(<br>
</div>
</button>
<p>click the gun</p>
</body>
</html>
Please no jquery or anything like it.
The javascript and only the javascript do I need help with.
It doesn't let me post this without adding more text so I am currently adding more text so I can post this.

How to prevent html buttons from moving back and forth when I adjust a range slider

When I adjust this range slider, the coresponding text to the right which indicates the video Playback rate, changes from a single digit (i.e. 1) to multiple digits (i.e 0.95). Everytime I do so it causes the buttons directly to the right of the text to move back and forth. I’m wondering how to prevent this movement from happening? I’ve tried adding some space, padding, margin, etc. between the text and buttons but I can’t seem to make it stop. I would defenitely like to keep all of the objects on the same line. Is there a way for example to make the default number of digits constant? For example when it’s set to 1, could it be 1.00 instead, and when it’s .8 can it be 0.80 isntead? I’m not sure if that would work since the playbackrate atribute seems to require a specific number of digits.
<!DOCTYPE html>
<html>
<head>
<style>
div#videoPlayerBox{ width:550px; background:#000; margin:0px auto;}
div#videoControlsBar{ background: #333; padding:10px; color:#CCC; font-family:"Trebuchet MS", Arial, Helvetica, sans-serif;}
#pbr{ width:40%;}
div#PlaybackRateBox{ margin:left; width:28%; text-align:center; border: solid 3px #000; background:#FFF; padding:0px;}
</style>
<script>
var v,p,c;
function myFunction(){document.getElementById("myForm").reset();}
function setPlaySpeednormal(){ c.innerHTML = 1;v.playbackRate = 1;}
function restartVideo(){v.pause();v.currentTime = 0;v.play();}
window.onload = function() {
v = document.getElementById("myVideo");
p = document.getElementById("pbr");
c = document.getElementById("currentPbr");
p.addEventListener('input',function(){
c.innerHTML = p.value;
v.playbackRate = p.value;
},false);
};
</script>
</head>
<body>
<div id="videoPlayerBox">
<video id="myVideo" width="100%" poster="https://www.dropbox.com/s/8qbvpxvtedcs5lq/2016-07-30_Milonga%20Triste_Guillermo%20Garcia_Tango%20Atipico_San%20Francisco.jpg?raw=1" controls>
<source src="https://www.dropbox.com/s/5rjbtmantuow8vw/testvideo_hfd.mp4?raw=1"
type='video/mp4'/>
Your browser does not support HTML video.
</video>
<div id="videoControlsBar">
<form id= "myForm">
<input id="pbr" type="range" value="1" min="0.5" max="1.2" step="0.05" class="slider">
<span>Speed <span id="currentPbr">1</span>
<input type="button" value="Reset" onclick="myFunction();setPlaySpeednormal();">
<input type="button" value="Restart" onclick="restartVideo();">
</form>
</div>
</div>
</body>
</html>
Try adding this #currentPbr line to your style block as shown below (the last line). Adjust the width to your liking
<style>
div#videoPlayerBox{ width:550px; background:#000; margin:0px auto;}
div#videoControlsBar{ background: #333; padding:10px; color:#CCC; font-family:"Trebuchet MS", Arial, Helvetica, sans-serif;}
#pbr{ width:40%;}
div#PlaybackRateBox{ margin:left; width:28%; text-align:center; border: solid 3px #000; background:#FFF; padding:0px;}
#currentPbr {display: inline-block; min-width: 80px;}
</style>
Here's a function that might help you:
parseNum = (num) => (num == 1 || num === 0) ? num + '.00' : (String(num).length == 3 ? num + '0' : num)
So, now you can call this function before giving value to c.innerHTML. Thus, instead of c.innerHTML = p.value, You can do:
var v,p,c;
function myFunction(){document.getElementById("myForm").reset();}
function setPlaySpeednormal(){ c.innerHTML = 1;v.playbackRate = 1;}
function restartVideo(){v.pause();v.currentTime = 0;v.play();}
const parseNum = (num) => (num == 1 || num === 0) ? num + '.00' : (String(num).length == 3 ? num + '0' : num)
window.onload = function() {
v = document.getElementById("myVideo");
p = document.getElementById("pbr");
c = document.getElementById("currentPbr");
p.addEventListener('input',function(){
c.innerHTML = parseNum(p.value);
v.playbackRate = p.value;
},false);
};
Here's a screenshot of the function in action:
PS Be sure not to use this function with every number. It just works for the domain of the volume.

Div container to expand with dynamic grid

this is kind of a two parter. I have a dynamic grid composed of divs (.unit) that I'm trying to contain in one larger div (#pallet). The grid increases based on the integer the user gives in a prompt. My question is how do I get the larger div to expand relative to the size of my grid without using absolute positioning? Also the grid isn't ever reduced to the user given value, it only increases. Any help would be much appreciated!
$(document).ready(function() {
var userChoice = 10;
for(var x = 0; x < userChoice; x++) {
for(var y = 0; y < userChoice; y++) {
var unit = $("<div class='unit'></div>");
unit.appendTo('#pallet'); //puts div "unit" into div "pallet" using appendTo
}
}
$(".unit").hover(function(){ //jquery selects the "unit" div and issues a function on it to change the css
$(this).css("background-color", "black"); //this is in reference to .unit changing the css to black
});
document.getElementById("reset").onclick = gridReset; //reset is the id of our button, so when it's clicked it will call our function gridReset
function gridReset() { //function grid reset first asks a prompt then stores the user's choice value in a variable and puts it through checks to see if its valid
userChoice = prompt("Between 1 and 64 how big would you like your grid?"); //we put our user choice in the function so as to not call a prompt at the start of the page load AND to store the variable in the scope
if (isNaN(userChoice)) {
alert(userChoice + " is not a number");
}
else if (userChoice >= 65 || userChoice <= 0) {
alert("Choose a number between 1 and 64");
}
else {
$(".unit").empty();
$(".unit").css("background-color", "blue");
for(var x = 0; x < userChoice; x++) { //for loop creates iteration of userChoice
for(var y = 0; y < userChoice; y++) { //for loop creates iteration of userChoice
var unit = $("<div class='unit'></div>"); //creates a variable "unit" = to a jquery div element with a class of unit
unit.appendTo('#pallet'); //puts div "unit" into div "pallet" using appendTo
$(".unit").hover(function(){ //jquery selects the "unit" div and issues a function on it to change the css
$(this).css("background-color", "black"); //this is in reference to
.unit changing the css to black
});
}
}
}
}
});
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Odin Div Project</title>
<link rel="stylesheet" type="text/css" href="styles/styles.css" />
</head>
<body>
<button id="reset" type="button">Reset Grid</button>
<div id="pallet">
</div>
<script type="text/javascript" src="scripts/jquery-3.2.0.min.js">
</script>
<script type="text/javascript" src="scripts/script.js"> </script>
</body>
</html>
CSS:
#pallet {
position: relative;
left: 425px;
top: 150px;
background-color: black;
height: 440px;
width: 440px;
}
.unit {
position: relative;
background-color: blue;
height: 20px;
width: 20px;
margin: 1px;
display: inline-block;
float: left;
}

How to count the letters in a text with Javascript?

I am currently trying to write a ''web application'' that has a simple text area inside, in which I want the letters of the text written to be pointed out.
For example, if I write:
''How old are you? I am 19 years old''
I need a code to tell me how many 'A's and 'Y's and 'D's (and all letters of the alphabet from 0-26) are used in this sentence when I press a button on a HTML/ CSS page.
Could you please tell me what I must write into my .JS file and what I should write into my .HTML file to do this with a click of a button when something is written in the ?
I hope my explanation was detailed enough. Thanks!
Edit (I'm very sorry for the problems I caused) - What I have done so far looks like this:
HTML:
<link rel="stylesheet" type="text/css" href="theme.css">
<meta charset="utf-8">
<script src="test.js" type="text/javascript"></script>
<div class='header'>
Al.Fa.Be
</div>
<div class='yaz'>
<textarea></textarea>
</div>
<div class='description'>
<a href='http://www.google.com'>Ara</a>
</div>
<div class='description2'>
<input id="clickMe" type="button" value="Hesapla" onclick="doFunction();" />
</div>
CSS:
body{
background:white;
}
selection{
background:#CCC;
}
#clickMe{
background:#CCC;
border:1px solid #333;
}
.header{
font-size:70px;
font-weight:bold;
font-family:Arial;
color:#333;
margin-left:580px;
padding-top:200px;
}
textarea{
width:1210px;
height:40px;
color:black;
margin-top:20px;
margin-left:100px;
padding-left:10px;
padding-top:10px;
font-size:18px;
font-family:Arial;
}
.description{
background:#f2f2f2;
padding:6px;
width:50px;
text-align:center;
border:1px solid #ddd;
font-family:Arial;
margin-left:620px;
margin-top:20px;
font-size:14px;
}
.description a{
color:#555;
text-decoration:none;
}
.description2{
background:#f2f2f2;
padding:6px;
width:60px;
text-align:center;
border:1px solid #ddd;
font-family:Arial;
margin-left:750px;
margin-top:-30px;
font-size:14px;
}
.description2 a{
color:#555;
text-decoration:none;
}
.yaz{
color:white;
}
Javascript:
// Input name. Count number of alphabets a-z
class program                                                         
{
    public static void main(String[] args)
    {
        String name = args[0];
        int count[] = new int[29];
        int i,p;
        int n = name.length();
        name = name.toUpperCase();
        char c;
        for (i=0; i<29; i++)
        {
            count[i] = 0;  
        }
        for (i=0; i<n; i++)
        {
            c = name.charAt(i);
            p = (int) c;
            count[p-65]++;
        }
        for (i=0; i<29 ; i++)
        {
            if (count[i] >0)
            {
                System.out.println((char)(i+65) + " occurs " + count[i] + " times");
            }
        }
    }
}
PS: Please remember that I really suck at this and I need to know how to do this in a specific way.
This is how I would do it.
var count = {};
var msg = "Your message";
for(var i = 0; i < msg.length; i++) {
var c = msg[i];
c = c.toLowerCase();
if(typeof(count[c]) == "undefined") {
count[c]=1;
}
else {
count[c]++;
}
}
If you want, you can check for only letters like this:
if('a'.charCodeAt(0) <= c <= 'z'.charCodeAt(0))
//This is a small letter
Try this:
var str = "How old are you? I am 19 years old";
str = str.toLowerCase();// search is case sensitive
var counta = str.match(/a/g);
var countd = str.match(/d/g);
var county = str.match(/y/g);
alert("a:"+counta.length+" d:"+countd.length+" y:"+county.length);
Fiddle here:
Check out this article: http://davidwalsh.name/javascript-unique-letters-string.
It's just what are you looking for.
Edit:
HTML:
<link rel="stylesheet" type="text/css" href="theme.css">
<meta charset="utf-8">
<script src="test.js" type="text/javascript"></script>
<textarea rows="5" cols="10" id="str" value="Insert the string" />
<input type="button" value="Submit" id="button" />
JS:
document.getElementById('button').onclick = function() {
/* returns the size/length of an object */
Object.size = function(obj) {
var size = 0;
for(key in obj) {
if(obj.hasOwnProperty(key)) size++;
}
return size;
}
//initial vars
var str = document.getElementById('str').val;
var letters = new Object;
//loop, figure it out
for(x = 0, length = str.length; x < length; x++) {
var l = str.charAt(x)
letters[l] = (isNaN(letters[l]) ? 1 : letters[l] + 1);
}
//output count!
for(key in letters) {
console.log(key + ' :: ' + letters[key]);
}
console.log(Object.size(letters));
}
PS: your "javascript" doesn't look like javascript... It looks like java...

Letter Shadows from User Input

Goal: User types name into user input field, selects Animate button, and name is printed vertically with each letter containing a drop shadow of each letter. The Javascript library Raphael may be desirable.
Problem: So far what I have is the name being printed vertically twice side by side. Obviously the second column should be the letters as drop shadows, but I don't know how to change the style of them to look like shadows.
My manager gave me one hint: "I had to create a 2nd text line placed underneath the text...and I used the .blur() method on it. If I have to give you another hint I'll be hinting you to the door."
I'm in some real trouble here. If anyone has suggestions, solutions, anything it would be very much appreciated.
<html>
<head>
<script src="raphael-min.js"></script>
<script src="jquery-1.7.2.js"></script>
<script type="text/javascript">
function animate() {
var txt = document.getElementById("words").value;
var area = txt;
var splittxt = txt.split("");
document.getElementById("letters").innerHTML = "";
document.getElementById("letters2").innerHTML = "";
var i;
for (i = 0; i < splittxt.length; i++) {
document.getElementById("letters").innerHTML = document.getElementById("letters").innerHTML + splittxt[i] + "<br>";
document.getElementById("letters2").innerHTML = document.getElementById("letters2").innerHTML + splittxt[i] + "<br>";
}
//displays how many symbols are in text box and what is in text box
document.getElementById("num").innerHTML= txt.length;
document.getElementById("msg").innerHTML = txt;
r.clear();
// Make our pink rectangle
ellipse = r.ellipse(40, 15, 30, 5).attr({"fill": "#969696", "stroke": "none"});
ellipse.glow({width:10});
}
</script>
<style type="text/css">
#letters
{
background-color:yellow;
width:25px;
float:left;
}
#letters2
{
letter-spacing:0px;
display:block;
-moz-transform: rotate(80deg);
margin-left:90px;
margin-top:80px;
width:25px;
color:#DEDEDE;
}
</style>
</head>
<body>
Text: <input type="text" id="words" value="" />
<input type="button" value="Animate" onclick="animate()" />
<div id='msg'></div>
<div id='num'></div>
<div id='letters'></div>
<div id="letters2"></div>
<div id="draw-here-raphael" style="height: 200px; width: 400px; margin-top:0px;">
</div>
<div id="elps" style="margin-left:100px;"/>
<script type="text/javascript"> //all your javascript goes here
var r = new Raphael("draw-here-raphael");
</script>
</body>
</html>
Live Long and Prosper.
Do you really need raphael? What I did was simply print out your words onto an element and get the shadow with css's text-shadow. To get the vertical text I added a </br> after each letter.
Take a look at the fiddle: http://jsfiddle.net/joplomacedo/wVGbF/
Here's the code in case you can't see the fiddle:
HTML
Text: <input type="text" id="words" value="" />
<input id="animateBtn" type="button" value="Animate" />
<div class="print"></div>
CSS
.print {
font: 44px/0.8em "Lobster", cursive;
color: gold;
text-shadow: 2px 2px 3px rgba(0, 0, 0, 0.6);
}​
JS
var join = Array.prototype.join;
$('#animateBtn').on('click', function() {
var txt = $('#words').val(),
spaced_txt = join.call(txt, "</br>");
$('.print').html(spaced_txt);
});​
Here is also the text output function with Raphael:
function draw_text() {
var txt = document.getElementById("words").value;
var posy = txt.length*10;
r.clear();
var attr = {font: "50px Helvetica", opacity: 0.5};
var text = r.text(40, 40+posy, txt).attr(attr).attr({fill: "#0f0"}); // underlayer or "shadow"
text.attr({transform: "r270"}); // rotate 270 degrees
var text2 = r.text(43, 43+posy, txt).attr(attr).attr({fill: "#aa0"}); // text above
text2.attr({transform: "r270"}); // rotate 270 degrees
r.safari();
}
var r = new Raphael("draw-here-raphael");
The full script, based on this example, is here.

Categories

Resources