fanofcena wrote:
trinary wrote:
I'm creating a very simple timer with JavaScript and I need some help.
Here is what I have at the moment:
var count = 0;
var timer = setInterval(timerFunction, 1000);
var divrestart = document.getElementById("divrestart");
divrestart.onclick = moveHandler;
function timerFunction()
{
count = count + 1;
var t = document.getElementById("timer");
t.innerHTML = count;
}
function moveHandler(evt)
{
if (!evt)
{
evt = window.event;
}
count = 0;
}
and the HTML:
<!DOCTYPE html>
<html>
<head>
<title>a timer</title>
<script src="js.js" type="text/javascript"></script>
<link rel="stylesheet" href="styles.css" type="text/css">
</head>
<body>
<h1 id="timer">0</h1>
<div id="divrestart">restart</div>
</body>
</html>
However, while the black portion of the JavaScript works well, every time I try adding the red portion, it insists that divrestart is null and it does not seem to function.
If I try using js.js as a userscript it works perfectly, while if I link it in the HTML file, or put it between <script> and </script> elements, it does not.
Does anyone know why?
function moveHandler(evt)
{
evt = evt || window.event ;
count = 0;
}
you know you can use the || operator straightway there. Secondly the javascript is executed as soon as the parser hits it . So as soon as the page hits the <script> tag it gets executed and hence its not working as at that time the lower part of the html document ur <body> is not parsed and it doesnot exist in the DOM.
You can wrap your whole code in a function like
window.onload = function(e){
/* Code here */
};
This function Will get executed when the window gets loaded , that is ur document is fully parsed and DOM is composed from it ..
And to all those who are learning javascript , please dont miss out the bitwise operators they are very useful in cases of binary reading and writing , but arent well documented anywhere.
Thank you for your help with both things.
You're amazingly good at JavaScript.
Offline
Ecliptic wrote:
TorbyFork234 wrote:
bobbybee wrote:
Out of curiosity, are you using jQuery for it? Cause it makes it so much easier.
I don't know what jQuery is... I'm coding it in an app called TextWrangler and I'm using a local server to run it.
Are u kidding me ? jQuery is 35 kb wastage DOM abstraction which shouldn't exist it make stuff go hard , rock hard , slow and performance issues are created on browsers like chrome forget IE . It leaks memory and SHOULD NEVER EVER NEVER BE USED UNLESS YOU UNDERSTAND DOM COMPLETELY.
Sorry fo being harsh but we at stackoverflow deal with lot of "jQuery developers" and we all recommend together not to use jQuery untill unless you know javascript . For a beginner thats NOT USE IT FOR LONG SINCE YOU START UNDERSTANDING HOW DOM WORKS .
for more info read this
Oh now the question.
Since javascript is event based its very hard to check which keys are pressed on an instant , infact you will have to create your own mechanism for that . But its very easy on the other hand using events . Here is how you do it .
// Step 1. Create an object // and add keycodes of all the keys you will be using init. // This will be called our map. var keyboard = (function(){ // This will just create a closure. // Alternatively you can create an array of just keycodes and inser / delete keys from it keycodes which will give u all the keys on keyboard // I use maps with the defined objects as you can simply remap controls on user decision. var map = { 38 : { state : false , name : 'up' }, // Up Arrow 37 : { state : false , name : 'left' }, // Left Arrow 40 : { state : false , name : 'bottom' }, // Bottom Arrow 39 : { state : false , name : 'right' } , // Right Arrow 65 : { state : false , name : 'attack' }, // 'a' - A keep in mind keyCode will return 65 83 : { state : false , name : 'block' }, // 's' 68 : { state : false , name : 'jump' } // 'd' }; // Returns array of all key codes pressed then u can use them programmatically this.getKeys = function(){ var arr = []; for( key in map){ arr.push(key); } return arr; } // Switch the map flag to on. document.addEventLisntener('keydown',function(e){ if( map[e.keyCode] ){ map[e.keyCode].state = true; } },false); // Switches the map back to false document.addEventLisntener('keyup',function(e){ if( map[e.keyCode] ){ map[e.keyCode].state = false; } },false); // Checks if a key or array of key is pressed // Returns True / False for the single key // Returns array of True/ False for an array of keys input. this.isPressed = function(input){ var output = null; if( input.length ){ // this is an array output = []; for( var i = 0 ; i < input.length ; i ++){ output.push(((map[input[i]])?map[input[i]].state : null)); } }else{ output = ((map[input])?map[input].state : null); // Null shows not defined } return output; } });
Last edited by fanofcena (2012-08-10 10:17:13)
Offline
trinary wrote:
fanofcena wrote:
trinary wrote:
I'm creating a very simple timer with JavaScript and I need some help.
Here is what I have at the moment:
var count = 0;
var timer = setInterval(timerFunction, 1000);
var divrestart = document.getElementById("divrestart");
divrestart.onclick = moveHandler;
function timerFunction()
{
count = count + 1;
var t = document.getElementById("timer");
t.innerHTML = count;
}
function moveHandler(evt)
{
if (!evt)
{
evt = window.event;
}
count = 0;
}
and the HTML:
<!DOCTYPE html>
<html>
<head>
<title>a timer</title>
<script src="js.js" type="text/javascript"></script>
<link rel="stylesheet" href="styles.css" type="text/css">
</head>
<body>
<h1 id="timer">0</h1>
<div id="divrestart">restart</div>
</body>
</html>
However, while the black portion of the JavaScript works well, every time I try adding the red portion, it insists that divrestart is null and it does not seem to function.
If I try using js.js as a userscript it works perfectly, while if I link it in the HTML file, or put it between <script> and </script> elements, it does not.
Does anyone know why?
function moveHandler(evt)
{
evt = evt || window.event ;
count = 0;
}
you know you can use the || operator straightway there. Secondly the javascript is executed as soon as the parser hits it . So as soon as the page hits the <script> tag it gets executed and hence its not working as at that time the lower part of the html document ur <body> is not parsed and it doesnot exist in the DOM.
You can wrap your whole code in a function like
window.onload = function(e){
/* Code here */
};
This function Will get executed when the window gets loaded , that is ur document is fully parsed and DOM is composed from it ..
And to all those who are learning javascript , please dont miss out the bitwise operators they are very useful in cases of binary reading and writing , but arent well documented anywhere.Thank you for your help with both things.
You're amazingly good at JavaScript.
Thanks but i personally feel i am not that good at javascript personally i feel Esailija / Raynos / Rlemon / Loktar And most those sit on the StackOverflow chat own me big way when it comes to javascript :-)
Offline
fanofcena wrote:
Oh now the question.
Since javascript is event based its very hard to check which keys are pressed on an instant , infact you will have to create your own mechanism for that . But its very easy on the other hand using events . Here is how you do it .Code:
// Step 1. Create an object // and add keycodes of all the keys you will be using init. // This will be called our map. var keyboard = (function(){ // This will just create a closure. // Alternatively you can create an array of just keycodes and inser / delete keys from it keycodes which will give u all the keys on keyboard // I use maps with the defined objects as you can simply remap controls on user decision. var map = { 38 : { state : false , name : 'up' }, // Up Arrow 37 : { state : false , name : 'left' }, // Left Arrow 40 : { state : false , name : 'bottom' }, // Bottom Arrow 39 : { state : false , name : 'right' } , // Right Arrow 65 : { state : false , name : 'attack' }, // 'a' - A keep in mind keyCode will return 65 83 : { state : false , name : 'block' }, // 's' 68 : { state : false , name : 'jump' } // 'd' }; // Returns array of all key codes pressed then u can use them programmatically this.getKeys = function(){ var arr = []; for( key in map){ arr.push(key); } return arr; } // Switch the map flag to on. document.addEventLisntener('keydown',function(e){ if( map[e.keyCode] ){ map[e.keyCode].state = true; } },false); // Switches the map back to false document.addEventLisntener('keyup',function(e){ if( map[e.keyCode] ){ map[e.keyCode].state = false; } },false); // Checks if a key or array of key is pressed // Returns True / False for the single key // Returns array of True/ False for an array of keys input. this.isPressed = function(input){ var output = null; if( input.length ){ // this is an array output = []; for( var i = 0 ; i < input.length ; i ++){ output.push(((map[input[i]])?map[input[i]].state : null)); } }else{ output = ((map[input])?map[input].state : null); // Null shows not defined } return output; } });
Thanks! I don't understand how this works (partly not knowing/understanding some of the syntax there. such as : ? I've tried learning what the "for (x in object)" but I don't understand it. Thanks so much! but I only use things I understand.
Offline
TorbyFork234 wrote:
fanofcena wrote:
Oh now the question.
Since javascript is event based its very hard to check which keys are pressed on an instant , infact you will have to create your own mechanism for that . But its very easy on the other hand using events . Here is how you do it .Code:
// Step 1. Create an object // and add keycodes of all the keys you will be using init. // This will be called our map. var keyboard = (function(){ // This will just create a closure. // Alternatively you can create an array of just keycodes and inser / delete keys from it keycodes which will give u all the keys on keyboard // I use maps with the defined objects as you can simply remap controls on user decision. var map = { 38 : { state : false , name : 'up' }, // Up Arrow 37 : { state : false , name : 'left' }, // Left Arrow 40 : { state : false , name : 'bottom' }, // Bottom Arrow 39 : { state : false , name : 'right' } , // Right Arrow 65 : { state : false , name : 'attack' }, // 'a' - A keep in mind keyCode will return 65 83 : { state : false , name : 'block' }, // 's' 68 : { state : false , name : 'jump' } // 'd' }; // Returns array of all key codes pressed then u can use them programmatically this.getKeys = function(){ var arr = []; for( key in map){ arr.push(key); } return arr; } // Switch the map flag to on. document.addEventLisntener('keydown',function(e){ if( map[e.keyCode] ){ map[e.keyCode].state = true; } },false); // Switches the map back to false document.addEventLisntener('keyup',function(e){ if( map[e.keyCode] ){ map[e.keyCode].state = false; } },false); // Checks if a key or array of key is pressed // Returns True / False for the single key // Returns array of True/ False for an array of keys input. this.isPressed = function(input){ var output = null; if( input.length ){ // this is an array output = []; for( var i = 0 ; i < input.length ; i ++){ output.push(((map[input[i]])?map[input[i]].state : null)); } }else{ output = ((map[input])?map[input].state : null); // Null shows not defined } return output; } });Thanks! I don't understand how this works (partly not knowing/understanding some of the syntax there. such as : ? I've tried learning what the "for (x in object)" but I don't understand it. Thanks so much! but I only use things I understand.
The ?: is known as conditional operator. its like if(condition){ /* do this */ }else{ /* do that*/ }
var a =(condition) ? (if condition is true ) : (if condition false);
this assigns the value in "a" depending on the condition.
for( x in object){
}
JavaScript object have key values internally , as in they are reffered like an "array"
that means
obj['x'] = 4;
the same as
obj.x = 4;
for (x in object){
}
allows you to traverse through all the references inside the object.
// Suppose the object is { a:400 , b : 500 }
for( var x in object){ object[x] += 10; }
This will actually set value of x first as a , then b . an allows you to access object properties that way.
Offline
fanofcena wrote:
The ?: is known as conditional operator. its like if(condition){ /* do this */ }else{ /* do that*/ }
var a =(condition) ? (if condition is true ) : (if condition false);
this assigns the value in "a" depending on the condition.
So basically this:
var a =(condition) ? (if condition is true ) : (if condition false);
is the same as this:
var a; if (condition){ var a=(condition true); } else{ var a=(condition false); }
Offline
TorbyFork234 wrote:
fanofcena wrote:
The ?: is known as conditional operator. its like if(condition){ /* do this */ }else{ /* do that*/ }
var a =(condition) ? (if condition is true ) : (if condition false);
this assigns the value in "a" depending on the condition.So basically this:
Code:
var a =(condition) ? (if condition is true ) : (if condition false);is the same as this:
Code:
var a; if (condition){ var a=(condition true); } else{ var a=(condition false); }
rather
var age = (prompt()*1) < 18? "You are young":"You are grown up"; console.log(age);
is same as
var age =""; if( prompt()*1 < 18){ age = "You are young"; }else{ age = "You are elder then 18"; } console.log(age);
Offline
Sorry if i am too harsh of something [ to mods ] , but you have to realize that jQuery has been the paining throne of web-development,
Here is my own opinion on jQuery.
Its a dom abstraction but it creates a nice little god-like plugin which promises to do everything for the developer. This is good when you know the language cause it makes the stuff incredibly fast and modularised to develop but when people dont understand javascript and go direct jump towards jQuery it creates what we call "jQuery Developers"
These developers have programming knowledge and can code anything but quality of code is unbearably poor :-) for instance this code fragment.
function ShowMyPower(){ $("#gohan").show(); $("#gohan").css("length",$("#gohan).attr("mywidth")+'px'); }
whats bad in this ?
well the code pretty much forgets the use of creation of variables themselves and over that the attribute also goes totally against the w3 recommendation of data-attributes.
I would recommend not to use jQuery until unless you understand javascript :-)
you can use it for production but not for development ,
Understand dom its faster and better . Most of the times jQuery is 1/8th faster then pure DOM because of its abstraction .
Offline
I'm bumping this up because I want to talk about JS. I'm learning it in Khan Academy.
Offline
Firedrake969 wrote:
I'm bumping this up because I want to talk about JS. I'm learning it in Khan Academy.
John Resig ;-) eh, good idea , you should also consider checking out codeacademy. http://www.codecademy.com/ its pretty intresting place aswell
and as a learning javascript never use W3schools and after you are done with the basics bookmark mdn (mozilla developer network) its the best and the biggest JS reference with deep emphases on best practises also consider joining stackoverflow.com and asking conceptual doubts there :-)
Offline
I just learned about CSS Image Sprites, and I'm wondering how to change the area that it collects from the image via Javascript.
Let's say I have this:
img.image { width:46px; height:44px; background:url(img_sprites.gif) 0 0; }
It's going to take 46x44px starting from 0,0. How can I set it so that in javascript I can change one of the zero's with a variable, so I can change what it's taking from the image sprite via javascript?
Offline
Firedrake969 wrote:
I'm bumping this up because I want to talk about JS. I'm learning it in Khan Academy.
I just saw that you can learn javascript there too!
Based on a quick glance, it appears as though it is set up like Scratch, but for javascript... cool!
Offline
How do you edit Javascript on Chrome; is it in the same place as HTML edits?
Offline
mythbusteranimator wrote:
How do you edit Javascript on Chrome; is it in the same place as HTML edits?
What do you mean? If you're meaning about the HTML of a web page your viewing, it's in the same place as HTML, but there could either be files called name.js, or just tags with the script in the page.
If you're meaning making your own, you could either:
• go to a website that helps with making your own HTML/CSS/Javascript pages
• set up your local server
• go to a website, delete all it's files using web inspector, and write your own.
Offline
TorbyFork234 wrote:
mythbusteranimator wrote:
How do you edit Javascript on Chrome; is it in the same place as HTML edits?
What do you mean? If you're meaning about the HTML of a web page your viewing, it's in the same place as HTML, but there could either be files called name.js, or just tags with the script in the page.
If you're meaning making your own, you could either:
• go to a website that helps with making your own HTML/CSS/Javascript pages
• set up your local server
• go to a website, delete all it's files using web inspector, and write your own.
I meant the former.
And I'll check tommorow, cause you can't do much on a 3DS.
Offline
TorbyFork234 wrote:
I just learned about CSS Image Sprites, and I'm wondering how to change the area that it collects from the image via Javascript.
Let's say I have this:Code:
img.image { width:46px; height:44px; background:url(img_sprites.gif) 0 0; }It's going to take 46x44px starting from 0,0. How can I set it so that in javascript I can change one of the zero's with a variable, so I can change what it's taking from the image sprite via javascript?
there are two methods both are nearly the same just use different techniques
Technique 1 : JavaScript
JavaScript can access styleSheet properties applied to an element , instead of - we use camelCase in here to seperate the words. ( just remove the "-" from a CSS property and capitalize the word that came next to it )
so
Element.style.backgroundPositionY
&
Element.style.backgroundPositionX
Are what you need , you can simply add some javascript in them and use them as sprites :-)
something like
function Change(Element,x,y){ if(y || y === 0) // the y===0 is just to make sure that it catches 0 values Element.style.backgroundPositionY = y + 'px'; // dont forget this 'px' you can also use other units but dont leave em without it if(x || x=== 0) Element.style.backgroundPositionX = x+'px'; } // Now to call it // See ? it was simple :D Change(document.getElementById('foo'),10,10); Change(document.getElementById('foo'),null,10); Change(document.getElementById('foo'),10);
or
there is a css method , with CSS level 3 animations but its too experimental , the first method should serve fine in most cases , i would urge you learn & Practice CSS 3 animations before trying this one .
/* Your keyframes */ @-webkit-keyframes animate{ /* The vendor prefix for webkit , and animate is the name */ 0%{ background-position-x:100px; } 10%{ background-position-x:200px; } 50%{ background-position-x:300px; } 100%{ background-position-x:400px; } } .animatable { background:'img.png'; background-position:400px 200px; /* random values like before*/ -webkit-animation:animate 400ms step; /* The step makes it step the animations and not form a smooth transition */ }
Offline
mythbusteranimator wrote:
How do you edit Javascript on Chrome; is it in the same place as HTML edits?
The chrome console ? the place where u inspect things ? There is a nice lil tab called console . you can straight way run javascript init ^_^
though for learning use something like jsfiddle.net
Offline
BirdByte wrote:
fanofcena wrote:
though for learning use something like jsfiddle.net
Nah, Code Academy is much better, IMHO.
you cant fiddle randomeness on CA ? its like CA is a uni , jsfiddle is ur notebook (x
Offline
fanofcena wrote:
BirdByte wrote:
fanofcena wrote:
though for learning use something like jsfiddle.net
Nah, Code Academy is much better, IMHO.
you cant fiddle randomeness on CA ? its like CA is a uni , jsfiddle is ur notebook (x
This.
Offline
mythbusteranimator wrote:
TorbyFork234 wrote:
mythbusteranimator wrote:
How do you edit Javascript on Chrome; is it in the same place as HTML edits?
What do you mean? If you're meaning about the HTML of a web page your viewing, it's in the same place as HTML, but there could either be files called name.js, or just tags with the script in the page.
If you're meaning making your own, you could either:
• go to a website that helps with making your own HTML/CSS/Javascript pages
• set up your local server
• go to a website, delete all it's files using web inspector, and write your own.I meant the former.
And I'll check tommorow, cause you can't do much on a 3DS.
I still cant find it. I click Inspect Elemtent.
Offline
mythbusteranimator wrote:
mythbusteranimator wrote:
TorbyFork234 wrote:
What do you mean? If you're meaning about the HTML of a web page your viewing, it's in the same place as HTML, but there could either be files called name.js, or just tags with the script in the page.
If you're meaning making your own, you could either:
• go to a website that helps with making your own HTML/CSS/Javascript pages
• set up your local server
• go to a website, delete all it's files using web inspector, and write your own.I meant the former.
And I'll check tommorow, cause you can't do much on a 3DS.I still cant find it. I click Inspect Elemtent.
There's a place where you view all the files of a website, I don't know where it is in chrome though.
Offline
This stuff if all too complicated for me. I do simple Scratch-like projects on JS.
Offline
I just made a project in javascript for homework, and modified it for other user interactivity. It's a sentence scrambler, it takes your sentence (that is less than 61 characters), and scrambles it (where it's still decodable) and adds in random characters.
Here's the HTML:
<!DOCTYPE html> <html> <head> <script type="text/javascript"> var reqLetters=new Array(); var word=prompt("Word(s)?\n(Note:will not work with 62+characters. Spaces will be obvious in the scrambled thing. The part on the bottom is checking if descrambled it contains your sentence)","thisisascrambledsentence"); var maxLetters=61; var inter=8; var Letters=new Array(); var i=0; var b=0; var checking=0; var c; var xyz=20; for (i=0;i<word.length;i++){ reqLetters[i]=word.slice(i,(i+1)); } var allLetters=new Array(); allLetters[0]='a'; allLetters[1]='b'; allLetters[2]='c'; allLetters[3]='d'; allLetters[4]='e'; allLetters[5]='f'; allLetters[6]='g'; allLetters[7]='h'; allLetters[8]='i'; allLetters[9]='j'; allLetters[10]='k'; allLetters[11]='l'; allLetters[12]='m'; allLetters[13]='n'; allLetters[14]='o'; allLetters[15]='p'; allLetters[16]='q'; allLetters[17]='r'; allLetters[18]='s'; allLetters[19]='t'; allLetters[20]='u'; allLetters[21]='v'; allLetters[22]='w'; allLetters[23]='x'; allLetters[24]='y'; allLetters[25]='z'; var maxLetters=61; var inter=8; var Letters=new Array(); var i=0; var b=0; var checking=0; var c; var xyz=20; for (i=0;i<maxLetters;i++){ var random=Math.round(Math.random()*25); var randomletter=allLetters[random]; Letters[i]=randomletter; } for (i=0;i<reqLetters.length;i++){ c=i; b=(c*inter)%maxLetters; Letters[b]=reqLetters[c] } c=""; i=0; for (i=0;i<reqLetters.length;i++){ c=c+Letters[((i*inter)%maxLetters)]; if (c!="knowledgeispower"){ xyz=1; } } var hgj=""; i=0; for (i=0;i<maxLetters;i++){ hgj=hgj+""+Letters[i]; } setTimeout("load()",1000); function load(){ document.getElementById("demo").innerHTML=hgj; document.getElementById("check").innerHTML=c; } </script> <style type="text/css"> #demo{ font-family:"Cambria"; } </style> </head> <body> <p id="demo">hi</p> <p id="check">hi</p> </body> </html>
Offline
TorbyFork234 wrote:
mythbusteranimator wrote:
mythbusteranimator wrote:
I meant the former.
And I'll check tommorow, cause you can't do much on a 3DS.I still cant find it. I click Inspect Elemtent.
There's a place where you view all the files of a website, I don't know where it is in chrome though.
Would it be a right click?
On IE, you can see with F12, but you can't edit.
Offline