Jump to content

Hadien

Members
  • Posts

    247
  • Joined

  • Last visited

Everything posted by Hadien

  1. Hadien

    Cookie explain

    A cookie typically has a string which is a semi-colon delimited list of key/value pairs. in an example cookie, say that the string value is: "Cheese=somevalue;expire=date;hello=new world"document.cookie.split(';') will basically "split" this string by the semi-colons, expanding the the pairs into an array like so:var ca = ['Cheese=somevalue', 'expire=date', 'hello=new world'];The for loop then iterates through each and every element in the array and tries to find the name which you've passed into the function. With "Cheese" passed in, it looks for the first element that has "Cheese=" in it and parses out that portion of the string via substring, which will return "somevalue".Here is another way you can parse the multiple values. var Cookie_Object = ({ values: {}, load:function () { var arr = document.cookie.split(';'); for(var i=0,key,value,split; i<arr.length;i++){ split= arr[i].indexOf("="); if(split==-1){ // if the "=" was missing, assume the key IS the value key = value = arr[i].trim(); }else{ key = arr[i].substring(0,split)).trim(); value = arr[i].substring(split+1).trim(); } this.values[key] = value; } return this; }}).load(); You see, this code automatically parses the current cookie into an object where all the values are immediately accessible and you don't need to rerun the function. so going by the previous cookie values we've used, you can go:Cookie_Object.values["Cheese"]and the code will return to you "somevalue".However, I should say that you should move away with using cookies. The new HTML specifications have basically migrated the use of cookies to the localstorage and sessionstorage variables. Using Web Storage is much faster, more secure, can hold far, FAR more information, and you don't have to worry about parsing things to the right datatypes and so forth, so you can preserve entire complex data structures while a cookie can only store a string.
  2. No you got it right, that is one way to read external javascript files. That particular file that you pulled up is valid javascript. It is just not easily readable, as the script has been minimized. People minimize their scripts when they want to improve their website's performance (specifically in bandwidth). This, however sacrifices the readability for us programmers which is why it seems cryptic to you. Again its completely valid code and its one of those scripts that is using a number of those little nuances in the language that a programmer picks up through the years. For example the entire outer function there is wrapped in parenthesis then instantly called after definition. This is a method people use when they want to write an anonymous function that no one can re-invoke and will only run once. (window,document,'script','//www.google-analytics.com/analytics.js','ga') These are the parameters that are passed into that function. filling up the arguments: (i,s,o,g,r) with the (a,m) only being defined and used inside this anonymous function, reason with them being in the parameter list is so that it takes less bytes to define the local variables (no need for the 'var' keyword). You can copy a minimized script, paste it into a new file, and then expand the code over multiple lines to help make it more readable. However a lot of the code can still be cryptic if you lack the context of the variables its using. . And most minimized scripts are very, very large... I mean trying to make sense of the jQuery library by reading it's minimized script would be a nightmare. By the way I highly advise against trying to do that because:1) You can easily grab a readable version2) Even when reading the readable version, libraries those sizes often utilize a concert of design patterns. So trying to understand "why" they coded something one way wouldn't make much sense if you didn't understand the underlying patterns they are following. anyway, when that script finishes running, the following variables are created (I had inner function logic expanded to what is implied): window.GoogleAnalyticsObject = 'ga';window.ga = function (){ if (window.ga.q === null){ window.ga.q = new Array(); } window.ga.q.push(arguments); return null; };window.ga.q = ['create', 'UA-46876714-1', 'gtrace.mobi', 'send', 'pageview'];window.ga.l = 1400060753032; //the specific number depends EXACTLY on when the script runs The script also creates an extra script tag with the listed url and inserts the tag right before the very first script tag already on the page.
  3. Also, you should use var answer (not $answer, I mean yes its valid but people will confuse it as PHP), and use prompt(), not alert() as alert won't return anything to the var answer. The reason askfirst was getting that warning is exactly due to what it said. the things it could return weren't the same datatype. when the answer wasn't true you'd return false... but if it was true, you'd continue on with the function normally and finish without returning anything, by which the function will infer to mean it should implictly return null. To remove that warning you need to make sure the function will return the same datatype in ever scenario in the function. You did this by commenting out the first return, but it should also be possible to remove the warning by adding a return true at the very end of the function.
  4. thedate() was likely an overlooked typo. var dateFormat = { now: new Date(), day: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], month: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], date: ["", "1st", "2nd", "3rd", "4th", "5th", "6th", "7th", "8th", "9th", "10th","11th","12th","13th","14th","15th","16th","17th","18th","19th", "20th","21st","22nd","23rd","24th","25th","26th","27th","28th","29th", "30th","31st"]}document.write( dateFormat.day[dateFormat.now.getDay()] + " the " + dateFormat.date[dateFormat.now.getDate()] + ", of " + dateFormat.month[dateFormat.now.getMonth()] + ", " + dateFormat.now.getFullYear() ); I don't know why you made a today and stamp variable, you don't seem to use them. Also I placed everything here inside a custom "dateFormat" object. This is a personal preference of mine, if a bunch of variables which are exclusively related to each other are placed in the global scope, I group them together under one name. It reduces global space pollution and possible name collision. I also avoid using document.write every chance I get, I prefer to be more specific where I insert html, though that is pretty irrelevant here.
  5. Hadien

    jquery

    There are a number of things wrong in this code. let us start with the jquery onclick handler you wrote. $("#statusBtn").click(function(){ function heidi(hilsen="heidi"){ return hilsen; }document.write(heidi()); }); 1) you don't need to define another function "heidi" inside your onclick handler, unless the handler your writing is very complex and would have to do a section of code numerous times. in this case you're not. 2) in Javascript, (Hilsen="heidi") is not how you define a default value. Javascript is type-insensitive and you can't overload a function by simply enforcing the number of specific datatypes a function will have, like you can in other languages. You generally have to resort to prototypes and use "shadowing" to mimic this effect. Don't worry about prototypes, you don't need to learn it here. if you want to set a default variable in a function you should run a typeof check to see if it's undefined, from within the function function heidi(hilsen ){ //checks if hilsen was a passed varible, if so it uses that variable // otherwise hilsen will default to "heidi" return (typeof hilsen !== 'undefined') ? hilsen : "heidi";)$(document).ready(function(){ $("#statusBtn").click(function(){ var text = $(this).data("text"); document.write(heidi(text)); });}); I moved the function heidi outside the onclick handler (and even outside the onready handler, though I didn't need to as it has no real impact on the code). this way everyone can access it. In fact I don't even need the heidi function at all, but one step at a time. Notice I wrote $(this).data("text"). This is an answer to the HTML part of your problems, so read on...Now lets look at that HTML: <button id="statusBtn" onclick="heidi("lars")">klikk</button> here you have a couple more problems. 1) you can't use double quotes to define lars. Your browser will see the double quotes and think, "oh, this is the end of the onclick handler" and not, "oh, you're telling me about a string". you would want to use single quotes in this case like: <button id="statusBtn" onclick="heidi('lars')">klikk</button> HOWEVER, I should say that you shouldn't do this anyway for your particular case as explained in... 2) you've already defined a click handler in jQuery. and since that handler is defined inside an onready handler... then jquery will simply overwrite and ultimately ignore the onlick you wrote in the html. Even if it didn't it would have had no idea what heidi() was anyway. only way the HTML's handler would run is if somehow the Jquery script wasn't loaded. Now... Jquery is already taking care of the click handler for you but you still want to be able to pass parameters into it on a per-element basis, right? Enter the data-xxx attribute. when you want to store special data for jquery or some other library to parse you would add an attribute with "data-" prepended to the name of the variable. in this case I use "data-text", but I could have easily gone "data-heidi" or "data-blahblah". Jquery already has a function that properly parses these custom attributes via .data(""). data-xxx attribute validate under the HTML5 specification and won't break earlier specs so you can use it with out fear. Combined with the Jquery code I posted earlier, your button should look like this: <button id="statusBtn" data-text="lars">klikk</button> That's all you need and the code should work. edit: oh wow, I've been typing this post for so long you already got a number of replys and you've updated your post a bit
  6. The simple answer to all your questions is that you need more experience, not knowledge. As you've said you've read a number of manuals numerous times but the knowledge doesn't seem to sink in because you lack the experience in Javascript. Computers have all the intelligence, all the knowledge in the world but they have no understanding of what it means. You, the Programmer, is charged with possessing the wisdom help create marvelous things, harnessing their knowledge. No manual is ever gonna teach you how to do that, it is something you need to obtain through experience. A strong foundation in programming is experience, not knowledge. In this day and age, knowledge is easily accessible, its knowing what you should do with it that is important. When you come across a major problem and things hit the fan its experience that will pull you through. You should just practice on simple scripts for now. Practice will trump just raw studying. As the saying goes: "An Amateur practices until he can get it right. A Professional practices until he can't get it wrong." Start a simple project and work on it. You don't need to know everything in the world right now. Look up the manuals when you get stuck, because when you need to understand it the most, then you'll most likely remember and understand it. Not only will this improve your understanding and skill in JavaScript, but a number of these fundamentals will also apply to other languages as well. I don't know everything in JavaScript, but then again I don't need to in order to make awesome scripts.
  7. As Davej says. Span is a "flow" type element (in that it uses Display:inline). It sets its dimensions to be only as large as it needs to be and will ignore all width and height styles you try to set it to. Only a few inline flow elements are an exception to this and will listen to css dimensions, like img elements. Block level elements, like div, you can have direct control of with said dimensions.
  8. Well, Specifically for Radio, the only thing that immediately comes to mind is using a <input type="reset"> button to empty the Radios. There may be more you can do for Radio that currently eludes me. It likely has a stronger impact on things you can't replicate (at least easily) via JavaScript like assistive technologies, as this link below seems to imply, though I don't know this first hand. MDN How to Structure an HTML Form paulm, you should take a look at that link, it presents a number of use case examples that your users can take advantage of. Like using fieldsets to have browser read assistants properly read out information to the user.
  9. You can still use forms. Forms already come with in-built usabilities which you can take advantage of, like the whole thing with Radio button behavior. This way you don't have to write out lines and lines of code logic yourself. Though you should disable any way of submitting that form (a simple html attribute onsubmit="return false;" should suffice). However, you should have also made a disclaimer that you were planning to not use forms for their original intent. It just helps us follow along with what you're trying to do sooner.
  10. Are your input elements in the html still using value="yes1"? or did you also update them to value="yes" like I shown in my example? I'm wondering why you're using multiple forms. When you submit a form, the browser will only submit one of the forms, and will garbage the data in the other forms. That said don't do form submits when selecting a Radio. If you want, you can instead resort to using AJAX calls to submit part of a form information is said information is needed to render the rest of a form. Also, I'm not sure why you're using setInterval in a situation that would seem to only need to fired twice. after you switch to the 'second greeting' the setInterval is still firing in the background when you don't need it to. When using setInterval, the function will return a special ID number that references to the looping construct thats constantly firing. when you're done with setInterval, use clearInterval to stop it from firing. Going back to your previous code snippet: var start = ["First greeting", "Second greeting" ];var counter = 0; var elem2 = document.getElementById("start");//modify this linevar intervalID = setInterval(change2, 1000);function change2() {elem2.innerHTML = start[counter++]; if(counter >= start.length) { //modify this line clearInterval(intervalID)} }
  11. Submitted variables are meant to be processed server-side with languages like PHP and Java. Javascript can play with "GET" data by parsing the data from the url, though is mostly intended to help the server know exactly what info to give the client. Javascript can never directly access "POST" data, only indirectly if you make server-side scripting insert the data into javascript as it loads. That line should only be called inside the selectedRadio() function, after you've set income.current. At first, income.current is null, if it reaches that line before you set a value it will throw an error due to you trying to access a property on a null (at current.value), and null never has any properties. Can you show us the code? It is kind of hard for me to follow with a description like that.
  12. You need to remember the buttons you pressed in order. So you need a variable to remember the 1st button (referenced "buttonA") so that when you select the 2nd button ("buttonB"). You can make the proper comparison. var game ={ buttonA:null, score:0 };$("button").clicked(function(){ if(!$(this).is(":visible")){ //selected button was already "removed", do nothing return; } if(game.buttonA === null){ //You're selecting the 1st button in the sequence // I disable it so that the user can't select the exact same button as buttonB game.buttonA = $(this).prop('disabled', true); }else{ //buttonA is NOT null, so you're selecting the 2nd button in sequence. var buttonB = $(this); if(game.buttonA.data("index") == buttonB.data("index")){ //setting buttons invisible, not display:none, so that they'll still // take up space on the screen. This will preserve the original // locations of all the buttons. game.buttonA.css('visibility', 'hidden'); buttonB.prop('disabled', true) .css('visibility', 'hidden'); //clearing buttonA for the next sequence... game.buttonA = null; game.score++; }else{ //The 2 buttons don't match, undo changes from last invoke // so that you can restart the sequence game.buttonA = $(this).prop('disabled', false); game.buttonA = null; } } }) After reading your initial post some more it looks like you also intend that specific pairs must be matched before others. If this is so you can use the current score to see if the buttonA matches the current score, if it doesn't don't set buttonA and don't disable.
  13. Ok a few things:1. notice that document.getElementsByName("income") is grabbing all nodes that have the name "income". The function mentions its looking for a plural amount of Elements. It will return a Nodelist object which is, more or less, an array of all nodes with that particular name. 2. Iterating through this Nodelist allows you to check each and every radio option. helping you find out which one has been selected. 3. Creating a paragraph tag like that will constantly create new tags every time you select a radio button. this will basically give the appearance of a history log of which radio buttons you selected. If that is what you're looking for, then great, but its pretty rare for someone to need to resort to that. Having a pre-created paragraph tag which you would constantly overwrite is much more common, used to often relay error messages to user about the invalidated form. if you'r only using this for debugging then use the Console.log() and Console.dir() to better track code behavior. 4. Personally, due to the nature of Radio buttons, there is never more than one radio (with the same name) that is ever selected. Iterating through a Nodelist will work but then theres n nodes that you're iterating through when you know there can only be one selected radio. Davej's code example is closer in the direction that I would code this. <form name="myForm" action=""> Yes <input type="radio" name="income" value="yes" onClick="selectedRadio(this)"> No <input type="radio" name="income" value="no" onClick="selectedRadio(this)"></form> //I create my own mini-object which I will use for form validation or whatnotvar myForm = { "income":{ "current":null, "yes": "You've selected Yes", "no": "You've selected No" } } //Written this way, the browser doesn't have to iterate over every single, // now unimportant radio to get the current selected value, however many there are. function selectedRadio(val){//Now you have an easy reference to what the selected radio is myForm.income.current= val;//just an example of what you can do.. alert(myForm.income[myForm.income.current.value]); } When it comes to being submitted I can simply check if myForm.income.current is not null (implying that the user selected a radio), so I don't have to go track down the selected radio again, if there is even one. I don't have to iterate through any Nodelist, nor do I ever need to even touch document.getElementById() or document.getElementsByName() as the "this" keyword removes the need to.
  14. I usually turn off BBCode Mode ("lightswitch" icon in the very top left of the posting dialogue) when I want to mess with multiple code blocks more specifically. I have better control of the formatting and can add a couple extra BBCode tags like [ spoiler ] tags which don't appear the in the hotbar. I know some browsers like to implicitly add in a "tbody" tag and you're adding rows directly to table and not inside that "tbody" tag. Your code might be coming across that 1st tbody and its breaking as there is no "cells" property, thinking it is a TR node. That could be a cause. I don't mess with TableRow Nodes all that much so I'm not too familiar with the "cells" property in the first place. That might be browser specific as well. Where exactly is the code not working? As said before, the Console functions like log() and dir() are ever so helpful in debuggin.
  15. You're running the "choice" code immediately, while the page is still loading, not when the form is being submitted. And when the page is currently loading neither radio button is checked by default so when it runs through the loop it sees nothing is "checked" and thus won't say anything.
  16. In JavaScript it is merely a good practice to get used to. It improves readability of your code when others come back to look at it. JavaScript is mostly type-insensitive and also automatically makes sure that new variables made are truly empty if never initialized. There is no direct type classification when making a variable and JavaScript merely assumes the type by what is currently entered in it, casting (changing) the data to other datatypes when needed. In other languages, like C, the language will assign some random available address to the variable and immediately use whatever is already in that address (usually just garbage data). You're required to determine the datatype at creation so that the language knows how many bits the variable needs to use. If you forget to initialize variables in those languages your code could run away with non-sensible info making it do bad things. So if you plan to write in multiple languages always initializing is simply a good habit to get into, unless you have some special use case in explicitly NOT initializing.
  17. I'm not sure I follow. jqeury is merely a framework, you could use the examples I made above alongside them. unless you mean specific objects created inside jquery well you can extend those objects with $.(origObject, extendingObject). or, for example with jQueryUI, use Widget Factory (view source). Writting accessor methods for them. I've written a UI Widget example before on the site a while back for a specific user. I didn't write any accessor methods per se in that example, but I could have easily done something like: getCurrent:function(){ return this.currentTooltip},
  18. You're confused. Globals aren't bad, never were. Its the act of abusing Globals (and how easy people can do so) that is bad. Globals is a necessary part in nearly all languages. That said, if you can get away with avoiding the Global scope then its often for the best. Using Globals when other options are exhausted is completely fine, you just need to keep track of them better. Anyway, your question can solved either with scoping or via the use of accessor methods. Scoping: You can wrap both functions and the variable into one object, all defined in the same scope your functions and variables are all grouped together and only the "myobject" touches the global scope: var myobject = {myvariable:0,One:function (){this.myvariable+=1;console.log(this.myvariable);},Two:function (){this.myvariable+=2;console.log(this.myvariable);},};//outputs "1" in consolemyobject.One();//outputs "3" in consolemyobject.Two(); accessor: You can have object 'A' with the variable 'count', function 'One', and has a getter method 'getCount' while the other function (which belongs in object 'B') can simply use A.getCount() to get the count. var A = {count:0,One:function(){count++;},getCount:function(){return this.count}setCount:function(x){this.count = x}}var B = {Two: function(){ var c = A.getCount()+2; A.setCount(c);}} There is a more stable way of writing getters and setters, but its a bit more verbose than I need to be for this simple example. you can read up on MDN about defineProperty and defineProperties Which option you should best use (Scoping vs. getters) depends on how the two functions relate to each other.
  19. I would advise against it. there are a number of ways of doing this, none of them pretty. The first option through the use of "contenteditable" html (google it). That however is rather clunky and highly invasive to a webpage another option is the is Window.getSelection(). and that is still experimental and not fully functional in a number of Browsers. It can't grab partial selections of a node (at least yet). last option is to use Javascript to explode all the nodes in the valid area to single character span tags then use getSelection to grab all selected "mini-nodes" and loop through them applying the applicable class associated with the button you pressed. but that is just ugly. . However if you simply just want the "current" selection styling to change (as in only what is currently selected will have the red color) thats very simple. look up the CSS3 ::selection Selector. However, this has no current plans of further development so use should be minimalized
  20. Hadien

    Help!

    As someone that uses a Gauss Series (the 1+2+3+4+5 summation) in a lot of the math I play with, I can say that theres a simple formula to calculate this Sum. However, I'm sure Ingolme knows this, and he's providing a simple example to help you learn how recursion fundamentally works. And it is a very useful example. I just wanted to give a heads up about that. Recursion does wonders when you need to write code that relies on the result of previous repetitions. It can be an elegant, clean function with only a couple of lines of code. though do beware that it can come with some extra overhead. for example if you enter in a very large number into that function you can easily hit the stack limit. Because the compiler (or rather interpreter as javascript is an interpreted language) can only remember so many function calls currently in the stack at any one time. Allow me to Answer previous questions you had in earlier posts as well. This is a massive text post so to help you digest I'll store these in multiple spoiler tags so you don't feel so overwhelmed:1) The Chicken and the Egg problem you present will simply run in an infinite function loop until again you hit the stack limit trace. but to answer the underlying question, yes the interpreter will remember the functions you called and any following functions called in the chain, or as the common metaphor "Stack". Since this also touches on what I said about Recursion limits I'll go a little more in-depth. 2) the reason the 1st curly brace would give the answer 1024 (which is correct 2^10 is 1024) is that the "return" statement is outside the looping control structure. 3) the find sequence trys to find the 1st combinations of +5s and *3 that will equal 24, with priority given the the +5. It's kind of hard to give a fully detailed explanation in text so I'll use a binary tree to help illustrate the functions path. Going left down the tree adds 5, while going right multiplies by 3. I think all the other open questions have been dealt with so I'll let you sit and ponder of this.
  21. a more in-depth explaination on Floating point calculationshttps://www.youtube.com/watch?v=PZRI1IfStY0
  22. it can be anywhere: directly written on the page or included in a separate script file loaded with the page. As Justsomeguy said, this particular piece of code is found in the head section of the page. Script code is usually placed in the head section as thats is often the most efficient place to put blocks of code, but they can be placed almost anywhere in the file. as for the server question... yes and no. the code originated from the server, but once the browser loads the code it doen't look back to what is on the server, until you reload the page you can open up pretty much any development console that basically every major browser has. The hotkeys differ from browser to browser and OS to OS, but they all basically have the same capability. Google Chrome/Mozilla Firefox for instance is opened with [F12], Mac Safari opens up with [command+i], and I think IE 1st needs developmental tools activated then also opens with [F12].in this case the code is in easy, readable format, but some site like to minimize or gzip their code to make is smaller and take up less bandwith (letting pages load faster) the drawback to this is that the code becomes nigh unreadable for us humans Of course! for example I can open up my chrome developers tab and go into the console and type simple javascriptalert("hello world"); press enter and the code runs immediately, rendering a pop-up on screen saying "hello world". You can overwrite entire functions inside the console this way. as to whether you should do this falls into a question of ethics and such. Theres some things many websites don't want you messing with. but its very useful in combinations with jquery to find thousands of elements and update them (then use the developer tab to copy the html and paste the result into a text editor, updating the file)
  23. here is a link to the previous thread on the topic so that others can be brought up to speed. in that thread I posted a fiddle that I thought would solve your problem but I noticed I didn't actually explain my reasoning why I think it would. I'll start by asking a question. Why do you need 9 select boxes? from what I understand every time you select a radio button you want to delete whatever was chosen in a related select box so that you can change another select box. when you submit the form, the server is gonna see 18 different inputs (9 radio inputs and 9 select inputs). however you seem to only want 4 of those inputs, the 2 radios and the 2 selects (well we can actually reduce that to just the 2 selects since the radios are also redundant). In the fiddle I provided in that previous thread, I looked at your problem and saw that your process involved over complicating on both the client and server side. client had to mess with all this convoluted logic just to make sure all these select boxes wouldn't have values that would confuse the user or server. while the server side had to sift through 18 different inputs when all it really needed was just 2 of them. so what I did was state that there is only 2 select boxes, and whenever you clicked on a radio button javascript would completely destroy one of the select boxes and rebuild it on-the-fly, the old values don't matter (your requirements made a point of trying NOT to remember previous selections). Not only did this simplify your hundred or so lines of client-code into about 20, but it also greatly simplified the server's job, as now it doesn't need to sift through 18 inputs to get what you want. it can completely ignore the radio inputs and look at the only 2, not 9, select boxes that were submitted. Fixing that 1st I believe is more important as it makes all your future work easier, as well as solve your current problems. I also made minor updates with autocomplete in the other fiddle with the combo box widgets. but those should be ignored until the actual html is rewritten (as its possible that much of the code is unnecessary).
  24. Though not exactly what you guys are talking about, I was reminded of this video that posed some relevance to this subject that I think you may enjoy seeing. Cross Site Request Forgery - Computerphile
  25. what you can do and write out the function and name it (instead of simply writing "function(e)", write something like "function thumbsCallback(e)"), but have the function defined outside the normal click handler, then you list all the events you want this to apply to. <script type="text/javascript"> $(function() { var thumbsSubmitID = null; function thumbsCallback(e) { e.preventDefault(); $(this).prop('disabled', true) .val("wait"); clearTimeout(thumbsSubmitID); thumbsSubmitID = setTimeout(function(ele) {ele.parent().submit();}, 3000,$(this)); }; $("input[type='submit']").on("click keydown keypress keyup",thumbsCallback); }); </script> what this does is that it defines a single function that prevents the event's default action (submitting form in these cases, changes the input's properties, and then sets up a delayed submission. then we assign this one function to 4 different event handlers per input. another option is to instead attach an 'onfocus' event instead of the keydown, keypress, keyup events and have this separate function prevent focus. this way the forms focus would never rest on these submit buttons and thus pressing enter wouldn't accidentally submit them. Possibly a better idea as the previous suggestion will cause a form submit when pressing any key (after disabling and changing text to wait)
×
×
  • Create New...