homepage Welcome to WebmasterWorld Guest from 54.205.254.108
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Pubcon Platinum Sponsor 2014
Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
Forum Library, Charter, Moderator: open

JavaScript and AJAX Forum

This 32 message thread spans 2 pages: 32 ( [1] 2 > >     
How to Master JavaScript
naark




msg:4216575
 8:12 am on Oct 14, 2010 (gmt 0)

actually this is not really a question... i just want to have some advice of what to do and what to read(offline/ebooks)to learn and at the end master javascript.... or at the end have a knowledge almost like mastery or in depth skills and knowledge about javascript....
any suggestions?

 

ericmorales115




msg:4216697
 2:12 pm on Oct 14, 2010 (gmt 0)

Like most things in life, i would say mastering JavaScript takes a crap load of practice and some base in theory. I used some ebook available on the iPad and the helped some. I also used Google and that helped alot, Then again i just recently started on JS. But i know PHP and C++ and i learned them just how i learned guitar with practice. GL

lexipixel




msg:4218606
 2:30 am on Oct 19, 2010 (gmt 0)

w3schools is a great place for beginners to learn several types of markup and scripting.

[w3schools.com...]

caribguy




msg:4218641
 4:02 am on Oct 19, 2010 (gmt 0)

Or Mozilla's developer reference: https://developer.mozilla.org/en/JavaScript

brotherhood of LAN




msg:4218642
 4:04 am on Oct 19, 2010 (gmt 0)

Knowing another programming language helps, and getting a good idea of the DOM also.

astupidname




msg:4218679
 6:22 am on Oct 19, 2010 (gmt 0)

I would recommend starting with w3schools as previously mentioned. Get the basics down there. Then to help get an even better grasp, Douglas Crockford (senior architect of javascript for Yahoo) has lots of good info about javascript at his site's 'javascript' subdomain: javascript.crockford.com [javascript.crockford.com]
Especially check out the videos section. Hours of essential learning there.

JAB Creations




msg:4219604
 4:03 am on Oct 21, 2010 (gmt 0)

Best advice?

Use XHTML as actual XHTML, which means serving pages as application/xhtml+xml so you can't use document.write as you're not supposed to in the first place; use alert() for debugging.

Don't use innerHTML, it's total junk and is completely unreliable; stick to using the DOM and all the element methods that for some reason refer to elements as nodes (just how amateurs refer to elements as tags).

Don't put scripts in the body element, put them in the head element; people will say that hurts performance, it doesn't but what it does do is NOT allow lazy coding practices.

Don't use frameworks EVER. They don't work when things get mission critical, they're wholly unreliable, and they easily alienate dial-up users who have more market share then IE6 in the US/UK/etc.

Lastly learn about rendering engines and use the big four: Gecko/Firefox, Presto/Opera, Trident/IE, WebKit/Safari. They each have strong points to test with JavaScript and their error consoles including IE. Opera really shines in this area and will catch lots of stuff that Gecko won't. Use and test with them all. I test with Firefox primarily though I use Opera for testing on pretty much a daily basis. Nick those warnings in Firefox too, leave no error unfixed!

You simply can't go wrong with my advice if you spend some time and work on your own personal projects. Set your goals of course though keep them reasonable and so long as you manage your time wisely you should do much better then you thought you ever could.

- John

Fotiman




msg:4219829
 2:35 pm on Oct 21, 2010 (gmt 0)

I'm going to go ahead and disagree with just about everything JAB Creations just said. :)


Use XHTML as actual XHTML, which means serving pages as application/xhtml+xml so you can't use document.write as you're not supposed to in the first place; use alert() for debugging.

1. IE browsers don't support support pages served as application/xhtml+xml without some tricks, so right away you'd be alienating a huge customer base. In addition, *most* websites are not extending the HTML set of tags, which means that an XHTML doctype is not appropriate, and an HTML doctype is. This does not really apply to learning JavaScript, though.

2. There's no rule that says you're "not supposed to use it [document.write] in the first place", though I agree that best practice is to avoid it as it is timing related (if document.write executes after your page has finished loading, it will replace the entire document). There are better alternatives to document.write.

3. alert() is one way to debug an application, but there are also some other alternatives that don't block processing. For example, creating your own logging mechanism to output to the page or using something like the Yahoo UI Library's logging. Another option still is using Firebug to step through your code (there are other JavaScript debuggers available too).


Don't use innerHTML, it's total junk and is completely unreliable; stick to using the DOM and all the element methods that for some reason refer to elements as nodes (just how amateurs refer to elements as tags).


innerHTML is totally reliable and is used by many of the top JavaScript frameworks. Claiming that it's junk and unreliable is, quite frankly, totally wrong. I'm not opposed to using DOM methods, but there is nothing wrong with using innerHTML.


Don't put scripts in the body element, put them in the head element; people will say that hurts performance, it doesn't but what it does do is NOT allow lazy coding practices.


Again, I disagree. The best place for scripts is at the end of the document just before the closing </body> tag. While JavaScript files are being downloaded and processed, the browser blocks all other resources from being downloaded. Placing the scripts at the end of the file allow the browser to download other resources in parallel, thereby giving a more responsive feeling experience to the end user. In addition, placing scripts in the <head> does not prevent lazy coding practices. I think JAB's argument is that it prevents the use of document.write, but it really doesn't. For performance reasons, place scripts just before closing </body> tag.


Don't use frameworks EVER. They don't work when things get mission critical, they're wholly unreliable, and they easily alienate dial-up users who have more market share then IE6 in the US/UK/etc.

I disagree. Frameworks today are small. The production version of jQuery 1.4.3 is 26 KB. The YUI2 Core (which provides excellent DOM and Event utilities) is 13 KB. On a 56K dialup connection, that's about 3.7 seconds and 1.9 seconds respectively (for the initial download... after that the browser can cache them). And saying they don't work for mission critical applications is just plain silly. There are a ton of applications that use frameworks today with no problem. They save time, and often provide the functionality you need with a smaller footprint than if you develop that functionality yourself (because they've gone through several iterations of optimization).

JAB Creations




msg:4219894
 4:28 pm on Oct 21, 2010 (gmt 0)

1.) It only takes a little PHP and basic understanding of headers to get XHTML to work in all browsers and degrade to regular HTML for IE8 and older...

<?php
if (isset($_SERVER['HTTP_ACCEPT']))
{
$p = explode('Validator',$_SERVER['HTTP_USER_AGENT']);

if (count($p)>1) {$mime = 'application/xhtml+xml';}
else {$mime = 'text/html';}
}
header('content-type: '.$header->mime.'; charset=utf-8');
echo '<?xml version="1.0" encoding="UTF-8"?>'."\n";
?>


2.) document.write does not work with XHTML and if you use it then you cut yourself off from using XHTML easily as well as being stuck in the position of having junk code.

3.) No, innerHTML is horribly unreliable and does not correctly process things in to the DOM which makes scripting with AJAX loaded content a 50/50 and I only prefer 100% chance of things working in normal circumstances. Stick to using importNode and other node related methods. I don't see why anyone who values standards would promote the use of an unreliable proprietary Microsoft method? That or maybe you've been lucky to have it work well enough in your given situations though I really stress the browsers out so it probably comes down to the context of what we're working on.

26KB is not small, that's over six seconds on dial-up. Additionally last night I was browsing this forum and saw numerous jQuery related threads. When you get in to real JavaScript you'll get sick of seeing jQuery as the quick and easy solution. Easy is never the correct solution when you're doing mission critical.

Actually yes, WordPress is a perfect example of where jQuery fails pretty hard. I dealt with a client who had a plug-in and a theme and wanted them both. jQuery was rooted deeply in to both and I ended up refusing the work because the code was a total utter nightmare. I would like to stress that I can and do reject work as I have to prioritize my time, I refuse to work with junk code as I work with clients and am building my own business; I don't have time to deal with code that can't be used reliably once much less not used over and over again. Plus it refused to work cross-browser because of two instances and the code to override one instance didn't resolve jQuery's bugs. Yes, DHTML animations worked in IE and Opera though not Firefox and Safari which leads me to think jQuery isn't intelligent enough to test for standards compliant methods first as Opera does support some proprietary Microsoft code which in an of itself means that jQuery will perform worse on IE9 then it does on IE8 in example. I could go on and on and on, please don't tempt me. ;)

I'm okay with disagreeing with Fotiman and most other people on friendly terms. If you're used to coding one way then that's fine however I have found my approach to things to save enormous amounts of time. In example I've seen people (plural) spend hours tracking down missing quotes that only broke one browser; if I'm missing a quote when I reload the page it breaks and I get an error message telling me exactly where and what the problem is so it ends up being fixed in seconds. Most people don't code as cleanly as I do so imagine what you could do with dozens or even hundreds of hours of your life given back to you? :)

The approach with JavaScript I have taken has also made Version 2.9 of my site a total speed demon. I have a lot of features and functionality while at the same time the initial page load is under 10 seconds on a 36K modem (4,500 bytes a second) and every page load (except for my gallery) only takes 2-3 seconds on dial-up tops. It's sort of like you have to be at the top of a mountain to understand what standing at the top of a mountain is like. Not to say that Fotiman doesn't know what he's talking about because he's helped me numerous times on here, it's just our personal preferences when it comes to code differ and that's okay if at the end of the day what your clients or boss needs if finished. :)

- John

Fotiman




msg:4219925
 6:01 pm on Oct 21, 2010 (gmt 0)

1.) It only takes a little PHP and basic understanding of headers to get XHTML to work in all browsers and degrade to regular HTML for IE8 and older...

But why bother? If you're going to serve it as HTML, then it *IS* HTML and therefore should use an HTML DOCTYPE. Also, you've now added a server side dependency that future developers might not be aware exists. And not everyone is running PHP. You've made the simple task of delivering HTML content overly complicated.

2.) document.write does not work with XHTML and if you use it then you cut yourself off from using XHTML easily as well as being stuck in the position of having junk code.

That's a fair point. And again, I don't condone the use of document.write. But again, there are very few sites that serve up actual XHTML content. I think we both agree that document.write should be avoided and I would just leave it at "You should avoid document.write because it's timing sensitive, and also it won't work at all for XHTML documents (if for some reason your application requires XHTML)"


3.) No, innerHTML is horribly unreliable and does not correctly process things in to the DOM which makes scripting with AJAX loaded content a 50/50 and I only prefer 100% chance of things working in normal circumstances.

Can you provide an example? I'm not exactly sure what you're describing. What do you mean by "does not correctly process things in the DOM"?

Stick to using importNode and other node related methods. I don't see why anyone who values standards would promote the use of an unreliable proprietary Microsoft method?

Note, it is not a proprietary Microsoft method. It is supported by all current browsers. Also, innerHTML was added to HTML5, and therefore is now part of the standards.

That or maybe you've been lucky to have it work well enough in your given situations though I really stress the browsers out so it probably comes down to the context of what we're working on.

I think for a large majority of what developers are doing, innerHTML is going to work for them. I know you've done some unique work, and your mileage may vary. :)


26KB is not small, that's over six seconds on dial-up.

Ok, lets do some math here just to clarify. I was referring to a 56k dial up connection. A 56k dial up connection means 56 kilobits per second.
1 KB/s = 8.192 kb/s
So 56kbps / 8.192b = 6.836 KiloBytes per second. 26KB / 6.836KB = 3.8 seconds.
If we assume a slower 33.6kbps connection, then 4.1 KiloBytes per second, 26/4.1 = 6.34 seconds.

Neither of which I consider to be too long for a dial up connection. Admittedly, that is my opinion, and you are entitled to to have a differing one. :)

Given that the average web page takes up 320 KB on the wire [code.google.com], a 26KB file is only 8.125% of the AVERAGE web page. In other words, this is a very minor percentage of what users will experience on average, and IS relatively small.

In addition, a recent survey showed that as of Oct. 2009, 68.7% of Americans had internet access, with 63.5% having broadband internet. That means 5.2% of internet users were using dial up. The only point I'm making here is that the number of dial up users is relatively small (at least in the US... I don't know about numbers in other countries).


don't have time to deal with code that can't be used reliably once much less not used over and over again

It sounds like this is simply a case of you not wanting to take the time to learn the framework and give it a fair chance. jQuery is well documented, and extremely reliable (when you know what you're doing). I admit, it took me a long time to come around to jQuery, but it really is a very elegant and powerful framework. Saying that it's unreliable because someone developed a plug-in that used it, and someone else developed a theme that used it, and the code was messy is not a good argument. The code may have been a mess, but it doesn't need to be, and that has nothing to do with whether the developer used a framework or not. There are plenty of scripts out there using plain old vanilla JavaScript that are just a mess. Whether the code is written using jQuery or not is irrelevant... the blame there sits on the developer.

I think we will simply have to agree to disagree. :)

JAB Creations




msg:4219957
 7:08 pm on Oct 21, 2010 (gmt 0)

1.) It's not my fault or anyone else's if they have poor coding practices and can't keep their header and template files well organized. There is a set pattern of what goes before what. Every template system I've seen mixes what should not be mixed and the file naming scheme is just not intuitive.

Also I'll reiterate that XHTML saves an enormous amount of time by helping you catch errors much quicker, the only thing it won't catch are duplicate ID's and you can usually figure that out when you're scripting and the wrong part of the page executes with your script.

Additionally XHTML is extensible, HTML is not. I can add XHTML5 features using XHTML 1.1 and HTML8 features one day without having to do major reworking of my code. The only applicable form of difficult with XHTML is if you argue against it. A few lines of code will strengthen your coding habits and save you an enormous amount of time in the long term.

3.) In regards to innerHTML not being reliable try scripting with content loaded via AJAX and "added" to the DOM via innerHTML. It proves to be a 50/50 chance hit-or-miss in my experience. I can't think of anything really specific since working with the DOM alleviated the issues and that was about a year and a half ago for me. I may have an older build of Version 2.9 that still uses innerHTML somewhere so if you'd like me to look in to that I'll see if I can find an example.

Actually it is a proprietary Microsoft method that so happens to be supported by all the browsers. It is in a spec however it's in it's infancy and from what I've read does not have much momentum. In regards to it being added to HTML5, that's JScript, what is JScript doing in an HTML specification? Don't get me started on all the things being done wrong with HTML5! :-/

4?.) I've read that you can't actually get a 56K connection over the phone lines because of certain laws hence why a 56K modem is limited to 36K speeds. With my 56K modem I never got more then 4.7KB a sec which is 37,600 kilobits because I remember comparing the speed to when I got my first cable modem and was like whoa. :) Still that's nearly four seconds of code that itself does nothing directly so that easily implies that more code will have to be loaded and you're now at the mercy of the framework working in the browsers that you need to support. Additionally every instance of jQuery I have encountered is over 70KB minimized, not the 26KB you're talking about. Of course I'm speaking about what I have personally seen so my perspective is only my own.

Plus coding for a framework is not JavaScript, it's framework dependent code. That might be okay for a small quick and easy project though I wouldn't use it for something mission critical...plus I usually reuse my own code anyway over and over and over again so I have absolutely no need to use a framework since my code (for what I do at least) has evolved to such a dynamic point. I think for naark it comes down to how far he ultimately wants to go with his code. My perspective is simply this: the less you depend on others the greater your strengths become and the more in-demand you become to others.

In regards to dial-up market share it's still larger in countries like the UK then IE6's market share. The numbers are bound to have changed in the year since I've read the statistics. Still if you're willing to get things to work on IE6 why not get things to work for dial-up users and benefit from writing your own code directly? Value comes from having or producing what others don't have or can't produce.

Actually I've worked with jQuery in Version 2.8 of my site and while it was useful I found ultimately while working on Version 2.9 that writing my own code reduces the amount of code, increases the speed that pages load, increases my ability to code actual JavaScript, does not limit my browser support to only what jQuery will support (my extended browser support is a selling point for my business once I get it running in about a year), my code is far more reusable, there is less of it, etc etc. I simply do not see the benefits to using jQuery period. On top of that with clients who do have it I always end up saying 'no', just no. I can code something to work in less then 1KB that most people decide they need jQuery for and have seen people ask if they need jQuery just to change a className on an id, really? Granted I know there are lots of people who really make good use of jQuery to be fair though again I don't approve of it looking for IE methods and then the standards compliant methods, it's use of innerHTML, it's general bulk, it's bugs, etc.

The reason it's inelegant is because developers are ultimately usually lazy and not coordinated. To be successful you have to be strict about what you do, how you code, and not get lazy and take the easy route.

"The five essential entrepreneurial skills for success are concentration, discrimination, organization, innovation and communication." - Michael Faraday

Yes, there are plenty of regular (the use of the word vanilla is an alien context) JavaScript can be done messy as well, that comes down to if the programmer doesn't care or doesn't have enough time. What I am saying is if you master JavaScript itself instead of relying on frameworks and avoid certain things then instead of writing code every time you need to do something what naark will notice is that they will start to reuse their own code as they start to really improve. I often talk about code in contrast to grass. I use to have to code like I would always have to cut grass...now I code once and the need doesn't "grow" back. Imagine mowing your lawn in such a way that in a year it will only grow at half the rate and in three years it will always be the perfect length.

Okay, I agree to disagree too. :) Each person's path is different, the important thing is that naark can try all of the advice and figure out what works best for them. That's how I think we all learned the code in the first place.

- John

Fotiman




msg:4219998
 8:57 pm on Oct 21, 2010 (gmt 0)


3.) In regards to innerHTML not being reliable try scripting with content loaded via AJAX and "added" to the DOM via innerHTML.

I whipped up a quick example to test this. I used jQuery to simplify the example. When the page loads, it will attach an event listener to the button. When the button is clicked, it will load in some content from another file, and set that to the innerHTML value. It will then find the newly added element (using getElementById) and attach an onclick event handler which will simply throw up an alert to let us know it worked. This worked 100% of the time I tried it.
File 1:

<DOCTYPE html>
<html>
<head>
<title>innerHTML Testing</title>
</head>
<body>
<p>In regards to innerHTML not being reliable try scripting with content loaded
via AJAX and "added" to the DOM via innerHTML. It proves to be a 50/50 chance
hit-or-miss in my experience. I can't think of anything really specific since
working with the DOM alleviated the issues and that was about a year and a half
ago for me. I may have an older build of Version 2.9 that still uses innerHTML
somewhere so if you'd like me to look in to that I'll see if I can find an example.
</p>
<input type="button" id="loadContent" value="Load Content" >
<div id="dynamicContent"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
// Attach event listener to button
$('#loadContent').click(function () {
$.get('snippet.htm', function (data) {
var dynamicContent = document.getElementById('dynamicContent'),
foo;
// Load some dynamic content and use innerHTML to add it to this document
dynamicContent.innerHTML = data; // <a id='foo' href='#'>Foo</a>
// Now find the newly added content and attach an onclick handler
foo = document.getElementById('foo');
foo.onclick = function () {
alert('It worked');
return false;
};
});
});
});
</script>
</body>
</html>


snippet.htm

<a id='foo' href='#'>Foo</a>



Actually it is a proprietary Microsoft method that so happens to be supported by all the browsers.

Proprietary, by definition, would mean that it was Microsoft specific. If no other browsers implemented innerHTML, then it would be a proprietary Microsoft method. Originally, yes, it was a proprietary method, but other browsers quickly saw the value of it and added support for it.


In regards to it being added to HTML5, that's JScript, what is JScript doing in an HTML specification?

No, it's not JScript, it's part of the HTML5 DOM. This is a new attribute of HTMLDocument and HTMLElement. It is a serialization of the node's children, and when set will replace the child nodes of the document/element with the parsed value passed in.


4?.) I've read that you can't actually get a 56K connection over the phone lines because of certain laws hence why a 56K modem is limited to 36K speeds. With my 56K modem I never got more then 4.7KB a sec which is 37,600 kilobits because I remember comparing the speed to when I got my first cable modem and was like whoa.

With V.90 technology, the effective download rate is limited to 56 kbps. U.S. government regulations limit the max to 53.3 kbps. Back in the day, I used to get 48 kbps pretty consistently. I think it also depends on the condition of the lines between you and the Central Office (CO). Newer technology (V.42 / V.44) adds compression capabilities for (potentially) faster downloads.


Additionally every instance of jQuery I have encountered is over 70KB minimized, not the 26KB you're talking about.

If you don't GZIP it, then yes, it will be about 75.9 KB.


Still if you're willing to get things to work on IE6 why not get things to work for dial-up users and benefit from writing your own code directly?

To be honest, I would not put in extra effort at this point to ensure things work properly on IE6. It now has about 7% market share worldwide (closer to 3.5% in the U.S.). :)
Things will still work for dial up users, they will just have a longer loading time, as expected. With the average page being 320 KB, if my total page weight is less than that, then I've provided an above average experience for those modem users.
:)

JAB Creations




msg:4220046
 11:10 pm on Oct 21, 2010 (gmt 0)

I did not actually want to do too deeply in to the debate on innerHTML since the code on my site is so in-depth and the issues I encountered were well over a year ago. I would love to debate it to a deconstructionist extent however I simply don't have the time to go bug hunting and figure out what I encountered then. All I can say is when you notice things not working in conjunction with content loaded via AJAX there is a reasonable chance that it's an issue with innerHTML. I also can't remember what versions of what browsers. We'll just have to leave that point at a draw. :)

Though I will stick by my statement that it's proprietary. Even if it's being adopted in to a specification of a different language (which makes ABSOLUTELY NO SENSE) it has and will continue to be a property Microsoft method even if it's been implemented in all the other browsers. So it's not part of any finished spec and HTML5 is not a JavaScript/DOM spec because it's an (X)HTML spec. On top of that I have numerous disagreements with the (X)HTML5 spec.

I think 320KB is excessive, most pages only need about one or two images if that. I'm not saying some pages can't make heavy use of multimedia however most pages simply don't need to. Entertainment should be part of my day, not my entire day. ;) Also my decision to support IE6 is a business oriented one as it will be yet another check on my list of things I can and already do support once I get my business running however trust me when I say I can't wait for it to be a thoroughly mute point. ;)

- John

Fotiman




msg:4220058
 11:38 pm on Oct 21, 2010 (gmt 0)

I know what you mean (about not having enough time). :)

JAB Creations




msg:4220061
 11:49 pm on Oct 21, 2010 (gmt 0)

Yes! I think not having enough time is one sign of becoming successful! Also having to charge more is another good sign. :)

- John

astupidname




msg:4220254
 10:57 am on Oct 22, 2010 (gmt 0)

Frameworks are extremely useful IF you TRULY understand what you're doing with them and how they work. This does come down to personal preference, willingness to learn the in's and out's of the framework, and when trying to do more advanced things the degree to which you grasp the core language (javascript) and OOP or programming in general. My personal preference is to code my own.

innerHTML is totally reliable and is used by many of the top JavaScript frameworks. Claiming that it's junk and unreliable is, quite frankly, totally wrong.


Can you provide an example?


I disagree that it's totally reliable, and agree that it's not "junk" -when used properly (as in, if it works during testing, great! if not, go directly to DOM methods). I ran in to it with something someone on another forum had trouble with and I struggled to understand why at first also (well, I still don't totally understand why), but helped resolve by using DOM methods. I'll give you a cleaned up example of it here, this will work in Internet Exploder, but not in other browsers such as Firefox, Chrome or Safari (windows), the alerts will not contain the 'foo' properties value from any of the elements added except the last one:


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
<title>Some Title</title>
<script type="text/javascript">

function findObjectProperty(objectId, propertyName){
var el = document.getElementById(objectId);
alert(objectId +'.'+ propertyName +' = '+ el[propertyName]);
}

function add_element(parentId, newElementId){
//naughty stuff here, adding an element via innerHTML,
//then later setting a custom user-defined property on the element.
document.getElementById(parentId).innerHTML += '<div id="'+ newElementId +'" class="newElement"></div>';
var div = document.getElementById(newElementId);
div.foo = "bar";
div.innerHTML = 'This is '+ div.id +', this.foo = '+ div.foo; //accessing div.foo here works fine
}

window.onload = function(){
add_element("container", 'element_1');
add_element("container", 'element_2');
add_element("container", 'element_3');
add_element("container", 'element_4');

findObjectProperty('element_1', 'foo'); //"undefined"
findObjectProperty('element_2', 'foo'); //"undefined"
findObjectProperty('element_3', 'foo'); //"undefined"
//odd thing is, no matter how many elements you add, only the last ones 'foo' property will be found
//correctly in the alerts from findObjectProperty.
//Problem does not exist with default properties such as id or className or even innerHTML for example.
findObjectProperty('element_4', 'foo'); //"bar"
}

</script>
</head>
<body>
<div id="container"></div>
</body>
</html>


If anybody's wondering, how to post formatted code on webmasterworld [webmasterworld.com]
Do not copy formatted code on webmasterworld from IE, use other browser such as Firefox.


In addition to the fact the problem only occurs when adding the element via innerHTML, the above is yet another reason for not extending html elements with custom properties I guess, which incidentally many frameworks do. Strange that only the last added element's foo is found in the alerts. Behaves almost as if a "closure" issue, but you can see by the coding pattern there is nothing that should introduce such closure issue. I'm just taking a wild guess here but could be some sort of stack trace error.
The cure is to change the add_element function to use createElement instead:

function add_element(parentId, newElementId){
var newEl = document.createElement('div');
document.getElementById(parentId).appendChild(newEl);
newEl.className = 'newElement';
newEl.id = newElementId;
newEl.foo = 'bar';
newEl.appendChild(document.createTextNode('This is '+ newElementId +', this.foo = '+ newEl.foo));
}


Well, just thought I'd share that oddity. If anyone can explain it I'd love to hear it.

Fotiman




msg:4220393
 3:11 pm on Oct 22, 2010 (gmt 0)

I think I can explain. :)

Lets step through it.

First, lets look at the add_element function:

function add_element(parentId, newElementId){
document.getElementById(parentId).innerHTML += '<div id="'+ newElementId +'" class="newElement"></div>';


Lets break that down into smaller chunks for debugging. Here's essentially what you're doing:

var parentEl = document.getElementById(parentId);
var currentInnerHTML = parentEl.innerHTML;
var innerHTMLtoAppend = '<div id="'+ newElementId +'" class="newElement"></div>';
parentEl.innerHTML = currentInnerHTML + innerHTMLtoAppend;


The first time through the loop the values will be:

currentInnerHTML = ''
innerHTMLtoAppend = '<div id="element_1" class="newElement"></div>'

Now lets continue on...


var div = document.getElementById(newElementId);
div.foo = "bar";
div.innerHTML = 'This is '+ div.id +', this.foo = '+ div.foo; //accessing div.foo here works fine
}


So you're getting the element, and then you're adding a DOM property foo (using the syntax div.foo = "..."). This is not the same thing as modifying the HTML of the element. So now the next time through the loop, you end up with this:

currentInnerHTML = '<div id="element_1" class="newElement"></div>'
innerHTMLtoAppend = '<div id="element_2" class="newElement"></div>'

Note, there is no 'foo' attribute in that HTML, therefore when you do this:

parentEl.innerHTML = currentInnerHTML + innerHTMLtoAppend;

You are replacing the current HTML (which DOES contain an HTML element that has a 'foo' property in the DOM), with the innerHTML form of that same element but which does NOT contain a 'foo' property.

So here is another solution (using innerHTML) that works:

function add_element(parentId, newElementId){
var currentHtml = document.getElementById(parentId).innerHTML;
document.getElementById(parentId).innerHTML += '<div id="'+ newElementId +'" class="newElement" foo="bar"></div>';
var div = document.getElementById(newElementId);
//div.innerHTML = 'This is '+ div.id +', this.foo = '+ div.foo; //accessing div.foo here works fine
div.innerHTML = 'This is '+ div.id +', this.foo = '+ div.getAttribute("foo"); //accessing div.foo here works fine
}


Notice that I've changed how we get the value? Instead of getting it via a DOM property (div.foo), I'm getting it via it's HTML attribute (div.getAttribute("foo")). Because this is extending the attributes to include a "foo" attribute, the DOM does not contain a "foo" property, as opposed to the id attribute for example, which has a DOM property on an HTMLElement. This also means that we'll need to change how we access it in the findObjectProperty method:


function findObjectProperty(objectId, propertyName){
var el = document.getElementById(objectId);
alert(objectId +'.'+ propertyName +' = '+ el.getAttribute(propertyName));
}


The reason div.foo worked for the last item was because you added the property after the last innerHTML replacement.

Here is the working version in its entirety :)

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
<title>Some Title</title>
<script type="text/javascript">
function findObjectProperty(objectId, propertyName){
var el = document.getElementById(objectId);
alert(objectId +'.'+ propertyName +' = '+ el.getAttribute(propertyName));
}
function add_element(parentId, newElementId){
var currentHtml = document.getElementById(parentId).innerHTML;
document.getElementById(parentId).innerHTML += '<div id="'+ newElementId +'" class="newElement" foo="bar"></div>';
var div = document.getElementById(newElementId);
div.innerHTML = 'This is '+ div.id +', this.foo = '+ div.getAttribute("foo"); //accessing div.foo here works fine
}
window.onload = function(){
add_element("container", 'element_1');
add_element("container", 'element_2');
add_element("container", 'element_3');
add_element("container", 'element_4');
findObjectProperty('element_1', 'foo'); //"undefined"
findObjectProperty('element_2', 'foo'); //"undefined"
findObjectProperty('element_3', 'foo'); //"undefined"
findObjectProperty('element_4', 'foo'); //"bar"
}
</script>
</head>
<body>
<div id="container"></div>
</body>
</html>

Fotiman




msg:4220402
 3:19 pm on Oct 22, 2010 (gmt 0)

With all that said, I would suggest that innerHTML is not a good solution in this particular case, and that using DOM methods to append the element (as you posted as the cure in your example) is a better approach. If you need to modify the DOM properties of an element (that are not mapped to specific HTML attributes), then you will need to do more than just modify innerHTML. And if you're going to do that, then you might as well just use the DOM methods for appending the element as well. And any time you will be REPLACING existing elements by setting innerHTML, special care needs to be taken to ensure that the elements you're replacing don't have DOM properties that need to be preserved.

astupidname




msg:4221051
 8:48 pm on Oct 23, 2010 (gmt 0)

I think I can explain. :)


Ahhh, I see, had not thought of it that way. Very well put Fotiman, it took me a bit to rethink it along the lines you are saying and now I'm sure I understand.
The root core of what you are saying is that Internet Explorer (inventors of innerHTML) are the only ones who know well enough that when you ADD to innerHTML you want the other elements in the existing innerHTML to be preserved in their current state IN THE DOM, whereas other browsers must completely re-evaluate the parents innerHMTL as a string and do not preserve state of pre-existing child elements, so any custom DOM properties get lost that way. Got it, that is absolutely the core of the problem -darned Internet Explorer is the only one that gets it right (they should, right? It's theirs!), how dare these other browsers wreck the existing elements. I guess I think of it as when I say += I mean just please lightly, gently tack on to the end of and please don't touch or even look at the beginning, darnit, and that is what IE does, but others re-evaluate the whole innerHTML string, getting their sticky fingers into the beginning and everywhere and thereby messing things up.

JAB Creations




msg:4221065
 9:24 pm on Oct 23, 2010 (gmt 0)

See, stick with the DOM. ;) Thanks for clarifying that, I really haven't had the time to figure out what was wrong with innerHTML.

- John

blend27




msg:4221176
 4:14 am on Oct 24, 2010 (gmt 0)

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>

I would not use it(ref it) that way, it is none of Google's Biz to know that the user visited my site or that a local project is in a making.

Just my 2 cents.

explorador




msg:4221429
 3:33 am on Oct 25, 2010 (gmt 0)

i just want to have some advice of what to do and what to read(offline/ebooks)to learn and at the end master javascript

I'm no master at all or expert :) yes, go with w3 first and then on "what to do", try to work on a project of yours... then plan, code with future in mind. If you create a code to detect a character, try to build one who can detect "ANY" character, I mean a function, that's something you can resue in the future, then you will be building a set of useful tools and functions on your own that will help you.

I don't like frameworks but I understand they are useful. Use them, or try not to!, but what I really think is, it is better to LEARN javascript than to "learn" how to use a framework... JS has rules and is more like a language than what frameworks use. Sometimes things might not work as you want and then, if that happens, frameworks will do nothing for you... but if you trully learn JS you can find ways to do what on a moment wasn't working.

Read, learn, try, test. Like... there is a great difference on loops "while X<Z.length" than using "x<5", or using loops going reverse, to ZERO. And try to avoid memory consumming techniques, it matters when you are working on something big.

Many things can be understood by "going critical" but one thing I know for sure is you create a habit and then when a lot of things are important you might pay the price for having bad coding habits. Experiment and choose a project for you, something you like, that will take the most out of you in fun ways. Good luck.

aspdaddy




msg:4221503
 8:49 am on Oct 25, 2010 (gmt 0)

I learned most of what I know searching and integrating dhtml scripts from dynamicdrive when I was at college, its one of the best.

Its futile to try and remember all that code or buy books unless you are doing it fulltime as a job.

I use quite a bit of JScript now for Microsoft CRM, & c#, SQL CLR, SOAP etc so cant master even 1 language, so having a good editor like Dreamweaver to espose the DOM, or even Notepad++ for your JavaScript is Key to learning, coding at a professional speed and reducing errors.

Theres also the Microsoft Developer Toolbar that helps navigate the DOM - not sure if its JScript or JavaSCript though. For AJAX , Visual Studio/Interdev saves a lot of time.

lexipixel




msg:4221636
 3:19 pm on Oct 25, 2010 (gmt 0)

This thread really got off track -- NAARK, (a newbie with 4 posts), ask for some references on how/where to learn JS --- the regulars (or "irregulars", as it may be), get into a DOM v. innerHTML discussion. Good thing he didn't ask "What brand of laptop is best" --- everyone would have told him how to build one from scratch, and why casting the case from magnesium is better than some other alloy.

Fotiman




msg:4221663
 4:13 pm on Oct 25, 2010 (gmt 0)

I admit, the discussion did get a bit off topic, though the discussion about innerHTML vs. DOM started off as a best practices discussion (which I considered on topic). I considered pulling the innerHTML debate out into it's own thread, but couldn't spot a clear breaking point that made sense.

But I think it has veered back on course now. :)

naark, another great JavaScript reference is the book "JavaScript: The Definitive Guide." Also, online forums (such as this one) make for a nice way to pose questions and get feedback. Once you start learning, if you get stuck or need to better understand why something behaves the way it does, this is a good place to ask. I've found that the best way to learn is though experience. The more you do something, the easier it becomes.

fauxsoup




msg:4221669
 4:34 pm on Oct 25, 2010 (gmt 0)

For the record, I would recommend AGAINST casting a case from magnesium, given its high reactivity to water. It's already bad enough when you spill a drink on your laptop.

Regarding 56k connections, you have to remember that some bandwidth is reserved for uploading those requests your making. Additionally, someone had mentioned that something like 65% of the US is on the internet and 61% is on broadband, which is all well and good except that they said that meant 56k had 4% of the US. However, is the second number, 61%, a subset of the first (as in, 61% of the 65% with internet) or a measurement of US citizens with broadband? It's pertinent, because one suggests 4% dialup and the other suggests 39% dialup, the latter of which I tend to believe is the more accurate number.

On the subject of frameworks, they're great for getting something done quickly, but for production it's just overhead. jQuery is just a collection of functions which use standard JS to accomplish some goals. Not only is there bandwidth overhead, but also processing overhead, and it doesn't always play well. For instance, jQuery adds several functions to arrays. If you have standard JS on the page which loops through an array, you'll also be looping through those functions (which creates all sorts of fun problems if you ever assume you can operate on the data in your array without validating it, typically causing 3 hours of frustration and ultimately a single line of code, which looks a lot like if(typeof(array[key]) == "function") continue;)

Additionally, the selector function for jQuery is rather inefficient, as it parses the whole DOM tree looking for selected elements. It might be a bit more efficient for IDs and classes with specified tags, but $("#something") is just a shorter version of document.getElementById("something"), and $("div.class") equates to a 6 line function, of which any experienced JSer has twelve versions.

The really inefficient thing about JQuery in this case is that most people who program with it use the $ selector to refer to an element or group of elements they already accessed. This isn't so bad for IDs, but for classes you wind up spending more time scanning for elements than processing them.

If you want to MASTER javascript, then do as JAB creations suggests and get very familiar with things like the DOM tree and anonymous functions (first-class functions are easily the greatest feature of JS). Later on you can play with JQuery and other frameworks, after you realize that you can use variables to store references to nodes and node arrays and can understand things like descendant selectors and scope in javascript (which is a mess when you first think about it, but a very organized mess after further thought).

Fotiman




msg:4221684
 5:05 pm on Oct 25, 2010 (gmt 0)


However, is the second number, 61%, a subset of the first (as in, 61% of the 65% with internet) or a measurement of US citizens with broadband? It's pertinent, because one suggests 4% dialup and the other suggests 39% dialup, the latter of which I tend to believe is the more accurate number.

No, it was 61% of Americans, not 61% of those that had internet (not a subset). I paid careful attention to the numbers before posting it because I wanted to be certain. :)


The really inefficient thing about JQuery in this case is that most people who program with it use the $ selector to refer to an element or group of elements they already accessed. This isn't so bad for IDs, but for classes you wind up spending more time scanning for elements than processing them.

Again, that's not a problem with the framework, but rather a problem with the developer.

I agree, though, that getting familiar with the DOM is an important first step to mastering JavaScript.

JAB Creations




msg:4221723
 6:21 pm on Oct 25, 2010 (gmt 0)

How about a little basic code? :)

Basic example...
var a = '1';
alert(a);

var b = 1;

alert(b);


Evolving that example by adding break lines and typeof...
var a = '1';
alert(a+'\n\n'+typeof a);

var b = 1;

alert(b+'\n\n'+typeof b);


Also where you declare a variable determines it's scope, if it's outside of a function it's global and every function can access that variable whereas if it's inside of a function then it can only be accessed by that function.

var a = '1';//global scope
function my_example()
{
var b = 1;//local scope
}


You'll also want to get in to arrays and how to access information in arrays. There are associative arrays such as the following...

var ids = {'example1':'text','example2':4};

alert(ids['example1']+' = '+typeof ids['example1']);

alert(ids['example2']+' = '+typeof ids['example2']);


This is a visual example of how an understanding of JavaScript can evolve over time.

Another thing to consider like I said earlier is to take advantage of all the JavaScript consoles. While Firefox is awesome all-round it doesn't catch all errors, Opera is better at that where Firefox fails. IE and Safari will also catch some things the others won't. Firefox will warn you about stricter stuff which I encourage to acknowledge.

You can also try debugging your code directly...

try {alert(c);} catch(err) {alert(err);}


You'll also want to get in to events such as the onload event which I use an anonymous function in order to be able to add more function calls later.

Save this as example1.xhtml and open it with Firefox or Opera. Safari does not handle malformed XML correctly and the last time I checked Internet Explorer 9 (currently still in beta 1) while it understands XHTML will also not handle malformed XML correctly. To see what I'm talking about remove the '/' from the </h1> ending tag of the h1 element, save, and reload in each browser. Firefox and Opera will break the page and tell you what is wrong so you can fix it, IE9 and Safari won't and IE8 and older can't handle this (see my earlier post). While that may seem like a lot of details this will drastically save you a ton of time in the long run, it's sort of like driving a super car...you may be doing it correct and safely the first time though you might be a little uneasy because you're inexperienced though once you get used to it you just can't go back to regular HTML. I always learned best by example with something that worked, so here you go...

example1.xhtml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Example</title>
<meta name="description" content="Example description." />
<meta name="keywords" content="word 1, something spiffy, mm donuts" />
<meta name="language" content="en" />
<meta name="robots" content="INDEX, FOLLOW" />
<base href="http://localhost/" />
<!--
Move your scripts to external files at a later point.
Only put global variables and your window.onload event in onload/don't cache.
Cache index.js, don't store global variables there.
<script src="scripts/index.js" type="text/javascript"></script>
<script src="scripts/onload.js" type="text/javascript"></script>
-->
<script type="text/javascript">
//<![CDATA[
//XHTML needs to escape scripting, use the first and last line of JavaScript comments to do this.

my_example_function(parameter1,parameter2)
{
alert('parameter1 = '+parameter1+'\n\nparameter2 = '+parameter2);
}

window.onload = function()
{
alert('Oh hai!');
my_example_function('ABC',123);
// Add more functions to call here later on.
}
//]]>
</script>
</head>

<body>

<h1>JavaScript example</h1>

</body>
</html>


Now combined with the PHP code I would recommend if you want to get this running in the most ideal situation get yourself a copy of XAMPP. XAMPP is an almost instantaneous web-server that can run PHP and MySQL. To get this to work in Internet Explorer 8 and older we just modify the code a little as in my example below which if you use for a basis for all your code will really help you learn a lot faster then you could in any other way provided you test with all four browsers (Firefox, Opera, Safari, and IE with IE being the last browser you test in because it's least standards compliant).

- John

example1.xhtml
<?php
if (isset($_SERVER['HTTP_ACCEPT']))
{
$mime_ua = stristr($_SERVER['HTTP_ACCEPT'],'application/xhtml+xml');

if ($mime_ua) {$mime = 'application/xhtml+xml';}
else {$mime = 'text/html';}
}
else {$mime = 'text/html';}
header('content-type: '.$header->mime.'; charset=utf-8');
echo '<?xml version="1.0" encoding="UTF-8"?>'."\n";
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Example</title>
<meta name="description" content="Example description." />
<meta name="keywords" content="word 1, something spiffy, mm donuts" />
<meta name="language" content="en" />
<meta name="robots" content="INDEX, FOLLOW" />
<base href="http://localhost/" />
<!--
Move your scripts to external files at a later point.
Only put global variables and your window.onload event in onload/don't cache.
Cache index.js, don't store global variables there.
<script src="scripts/index.js" type="text/javascript"></script>
<script src="scripts/onload.js" type="text/javascript"></script>
-->
<script type="text/javascript">
//<![CDATA[
//XHTML needs to escape scripting, use the first and last line of JavaScript comments to do this.

my_example_function(parameter1,parameter2)
{
alert('parameter1 = '+parameter1+'\n\nparameter2 = '+parameter2);
}

window.onload = function()
{
alert('Oh hai!');
my_example_function('ABC',123);
// Add more functions to call here later on.
}
//]]>
</script>
</head>

<body>

<h1>JavaScript example</h1>

</body>
</html>

fauxsoup




msg:4221843
 9:18 pm on Oct 25, 2010 (gmt 0)

Important distinction on scope. When resolving a variable name, the script parser travels up the scope chain from the current point of execution to the window object (effectively global scope).

If you have a function foo inside of another function bar, any variables without explicit declaration will pass through bar before window. So:


var global = 1;
function foo() {
var global = 2;
function bar() {
anothervar = 1;
alert(global);
}
}


bar's reference to global will return 2, since that's the nearest explicitly declared variable in the scope chain matching that name.

Note, as well, that anothervar would be a global variable. Since there is no definition for anothervar, the parser travels up the scope chain until it hits the window object and, having found no corresponding definition, creates the variable there.

I suspect you know this, but it's a fact that's often glossed over. There's also all sorts of fun when passing around function references and trying to refer to "this"

lexipixel




msg:4222123
 9:51 am on Oct 26, 2010 (gmt 0)

No, it was 61% of Americans, not 61% of those that had internet (not a subset). I paid careful attention to the numbers before posting it because I wanted to be certain.


I have the same quandary when reading shampoo bottles --- 'cause "33% FREE" and "33% More FREE" aren't really the same thing, are they?

This 32 message thread spans 2 pages: 32 ( [1] 2 > >
Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved