How to use jQuery without making a mess? [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I could expect short answers to be "just use AngularJS/Backbone/...(fill the blank)".
But I believe before I dive into those ultimately, there shall be alternatives and proper ways of getting things done.
So for now, I am using plain html, css, javascript and the only library I use is jQuery and some plugins.
Confession time:
these are the things that I found myself doing all the time and I really think these are "bad" and not "the right thing to do":
Use global js variable to hook things together.
eg.
$(document).ready(function(){
window.someVar = ...;
window.someFun = function(){...};
});
Need to bind all the event again after DOM manipulation, because it stops working after selecting some elements and putting it somewhere else.
eg.
$(".myElementWithSpecialActionHandler").click(function(){});
after the element was relocated, say insert to a different position of the page, the event handler function stops working. So I have to do
// after DOM manipulation
// again >.<
$(".myElementWithSpecialActionHandler").click(function(){});
Js code is dumped into one giant "main.js" file.
css code is dumped into one giant "main.css" file.
I use <tag onClick="someFunction(); ...> here and there because of issue "2." sometimes.
I use inline css here and there.
I am a noob. But I am deeply uneasy writing all these code and yet I am not quite clear how to "make it right". I don't this is an ideal question in SO, but I think this is quite common for new developers. So the answers would benefit a lot of people.
Any enlightenment, web links, pointers to good source, help, and critics are greatly appreciated!
Yours sincerely,
A noob with good taste=> therefore he is disgusted with his own code :(

I don't think there are correct answers to any of these question, but preferences/opinions
1) I don't like adding variables to global scope, so window.someVar is a wrong practice because there can be accidental manipulation of a value by another non relevant scope. If you are using jQuery the need for global variables are very less. If you find yourself using it many times then you may have to rethink about the solution
2) You need to look at event delegation instead of binding event handler after creating new elements. Assuming you are adding new input elements to a div with id x then you can do the below in dom ready handler instead of binding it again and again
$('#x').on('change', 'input', function(){})
3) I normally uses a single js file for my script, so that it can be properly cached
4) same as the script file
5) In string literals I use ' as the enclosing tag so that I can use " inside for html attributes like var x = '<div class="someclass"></div>'.
6) I normally wouldn't use inline css, As much as possible try to separate style info from the html markup

Just to get it out of the way, you can definitely profit from using some sort of frontend framework. I like jQuery for small things that need to directly manipulate the DOM.
1) some of this is unavoidable. JavaScript is built on global variables. Even Douglas Crockford acknowledges this in "JavaScript: The Good Parts". Just try to keep it to a minimum. Look at patterns to contain things, such as immediately invoked function expressions.
3) Try to find ways to split things up then use something to concatenate and minify it. That said, I'm guilty of bunching things up too much too.
4) There are good reasons to split things out. Your CSS reset can be in its own file. Site-wide layout in another file. Page specific stuff can go into their own files. Templating languages can help you subdivide a page into functional pieces that can have their own CSS files.
5) I didn't know that this was a problem honestly. I've seen plenty of people use single quotes around JS strings.
6) Good for hacking, bad for long term. Just add another class (or id if appropriate). You could put it in a shame.css: http://csswizardry.com/2013/04/shame-css/

Related

Is this method of creating html elements in JavaScript considered outdated? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
In the newer versions of JavaScript, I know that you have to createElement() then you have to appendChild() if you wanted to create and html element in JavaScript. However, I stumbled across this method of creating html elements using Jquery and I was wondering if it was outdated?
$("#options").html("<option value='Millimetre'>Millimetre</option>")
Thanks for any answers!
It's not that it's outdated, it's that this syntax depends on the jQuery library, and jQuery is still concerned with imperative DOM manipulation. These days, most UI frameworks use declarative patterns because they are easier for developers to author and reason about. Declarative patterns move the complexity closer to the level we can handle, rather than requiring us to move our brains closer to the complexity of the mutation logic.
But we can strip out the jQuery and do basically the same thing:
create a string that contains HTML markup
inject that string into the document using .innerHTML
There are reasons folks don't like working with strings of HTML, which is sometimes called "tag soup":
there's nothing to protect against basic typos or markup mistakes like nesting errors
tag soup is hard to read, because even in an editor with intelligent syntax highlighting, the tag soup is just a string, so it will all be one color
some characters which are valid in HTML need to be escaped inside tag soup, which makes it even harder to read
long strings of tag soup typically make for very long lines of code; very long lines of code are hard for humans to read, and do not diff well; there are patterns for mitigating this, but that's an extra hassle you have to deal with
That said, there is one really big benefit that tag soup has: better runtime performance. DOM manipulation is typically one of the slowest things javascript does within the browser. I haven't run tests recently, but back in the day a single DOM operation usually took about 100ms. That maybe seems fast, but if you're adding hundreds or thousands of nodes to the document it can add up to several seconds. Setting innerHTML is also a DOM operation, but that one operation can create, modify, or remove hundreds or thousands of elements at once. Yes, an innerHTML op that adds thousands of elements will probably be slower than an innerHTML operation that only adds 5 elements, but it'll probably still be at least one order of magnitude faster than adding each of those elements using individual operations.
Worry less about whether the thing you're doing is "cool" or "cutting-edge." Focus on whether you're using the right tool for the job, whether the tool makes your job easier or harder, whether the tool is reliable across all the platforms and timespans you care about.
It's not your job to please the cool kids. It's your job to write software that does the right thing, for the right reasons, in the most obvious way possible.
Pretty much everything regarding Jquery is consider outdated, that's why sites such as Github and frameworks as Bootstrap are droping Jquery use.
The non outdated will be in fact handling the DOM yourself whit createElement() (which Jquery does under the hood), but as you can tell it gets pretty complicated doing all that yourself
So alternatives are:
using a web front end framework such as Angular, React or Vue
using a modern library to handle DOM updates
Not saying Jquery is useless it still gets the job done but there are many reasons not tu use anymore, most of them comming from the fact that JS got many new feature that are now native and not having any need to re implementing with more code from Jquery

Why there are two different Javascripts? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I am learning JavaScript, but the tutorial are kind of different depending on the resources. It looks like the JavaScipts are different, there is like 2 types of it.
So, let's say if we take one source, they have a code like this:
<html>
<body>
<p>Before the script...</p>
<script>
alert( 'Hello, world!' );
</script>
<p>...After the script.</p>
</body>
</html>
But when I do tutorial, on Codecademy , for example, they do not have any html code, no body, p, script... the code does not go into html. Functions like alert, onclick are very popular and, in fact, the w3schools begins with these functions, where on Codecademy there are no such things. And this code line
document.getElementById('demo').innerHTML = Date();
it says it is important in javascript, but codecademy does not mention it at all! Like what are those document dot getElementById('demo').What is it doing? Why it is everywhere on w3schools, but not on Codecademy, if it is so important? I finished whole JavaScript course on Codecademy, but I am still confused how come it is so different?
I learned Python before and it is similar to proper JavaScript (I call proper JavaScript the one, that is on Codecademy, because the structure is just like Python)
So the weird JavaScript (the one that is on w3schools, etc. and not on Codecademy) often has dollar sign, lines like this
function $(x) {
return document.getElementById(x);
}
The proper JavaScript use dollar signs only with string interpolations and that's it and the whole Codecademy tutorial does not have this all weird code that I provided above, which seems really important on other web sources.
All the YouTube tutorials I found are also using proper JavaScript, just declaring variables, writing functions, like, normal programming language, like Python, but what's with all the HTML tags, alerts, onclicks, dollar signs, etc., that are in tutorials like w3schools? Can please someone explain me?
Yes, I'm embarrassed a lot. To think of that I know Python and JavaScript on higher than beginner level, but I cannot figure out what's with the different code and what is happening...
P.S. Thank you everyone for answers. I probably wasn't clear, but I didn't wanted you to explain what actually those code lines, that I posted, meant (like most of you did), but mainly I wanted to know how come it's so different, why is that difference, why two different types of JavaScript? Hence, I accepted the appropriate answer.
document.getElementById is part of the DOM API, it's not part of JavaScript. If you want to interact with webpages you need html that is parsed and "converted" into DOM tree like structure. For example document don't exist in Node.js (server side JavaScript) but there is library that allow to use if you want to test your front-end code.
<script> tag is a way to add JavaScript files to html page. But you don't need html page to use JavaScript (you can use Node.js that I've mentioned).
and about this:
function $(x) {return document.getElementById(x);}
$ is normal variable and function name, it's legacy for Prototype and jQuery libraries that used this for their API main entry point and it's very short and clean.
The one on Codecademy mostly deals with server-sided Javascript, read up on NodeJS if you want to know more about it.
The other one with document.getElementById() and such is client-side Javascript and it gets executed by you or anyone who visits the webpage (so the client) inside of the browser.
NodeJS on the other hand doesn't run in a browser and doesn't have a global document or window because of that. You can use it to make a webserver (check out Express) or use it for other stuff in the same way you would use other languages like for example Python.
Both of them are still the same Javascript but they run in a different context.
The dollar sign is pretty typical jQuery syntax, it's just a framework for Javascript where they decided to use $ as variable name (which is allowed) so you could easily see it's a function from jQuery. There's nothing preventing you from using $ yourself in variable names, not in NodeJS and not in the browser.
There are arguably more than 2 even!
Javascript was developed to work inside the browser, in the context of the DOM, but it is also a programming language independent of any browser, of any HTML, of any DOM.
In HTML, <script> tags are for javascript, but you can also link to javascript files.
the <script> tag is just a html element which declares the content of this block to be javascript.
the content will be executed by the browser inside of the scope of the DOM.
in a javascript application you do not code javascript directly into the DOM, instead the JS files will be included/injected into the page.
When you see getElement usually its trying to find an element from DOM tree, in your case it's trying to find and element with the id demo.
Would find something like this
<div class="container">
<p id="demo"> </p>
</div>
For the code document.getElementById('demo').innerHTML = new Date() this would get the date and set it to your HTML #demo node.
As for function $(x) {return document.getElementById(x);} this function is trying to copy jQuery funtion of selecting DOM. Its does the same thing as the above code but you type alot less once its declared.
function $(x) {
return document.getElementById(x);
}
$('demo') // finds all nodes that have #demo in your DOM tree
In your HTML snippet using <script> before and after a tag means that you have or not to wait for the document to load. DOM tree loads from one node to the next and when you load a JS file or script, it gets instant loaded and fired, unless its told no to using events and conditions.
<html>
<body>
<p>Before the script...</p>
<!-- This element exists in your DOM tree already so you
don't really need the document to load. -->
<script>
alert( 'Hello, world!' );
</script>
<p>...After the script.</p>
<!-- This element is added after the script so if you run
the code above trying to find this "p" tag you would need
to add a proper window.onload event -->
</body>
</html>

organising HTML class names and IDs used for different purposes (appearance, jQuery and Selenium) [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
There are countless articles on writing clean HTML/CSS.
What I haven't found though is advice on organising class names and IDs that are used for different purposes (design vs jQuery vs Selenium testing).
For any given class name and ID, it's difficult to tell what it's being used for. In 2+ person teams, there also seems to be a tendency to keep adding more and more IDs and classes, and avoiding cleaning up those that are already there, in fear of breaking things.
Are there patterns, conventions, tools, or pearls of wisdom that would help?
I have not come across any tools to help with this situation. But I have used the conventions below with moderate success. None of them are an exact science though.
Regarding IDs:
Because IDs are the faster lookup, I tend to use them whenever I'm wanting to address a specific part of my HTML, regardless of how I'm using it (styling/jQuery/testing/etc).
However, because each element can only have a single ID, there's not really an opportunity to use a naming convention or style for different uses. And I have found that if I've wanted to address an element for one reason, there's a good chance I'll want it again for a different reason.
For example: if I have a button on a page and find it using jQuery (by ID) to attach an event handler, then chances are I'll also want to find that button to test its behaviour.
So because an ID can be used for multiple reasons, it should be named in a general way, ideally describing what the element is or represents, rather than how it will be used. It should then make sense however it is used.
But as you say, for a given ID
it's difficult to tell what it's being used for
I agree, and generally don't try to find out unless I have to. Other team members can't add additional IDs to an element that already has one, and should be encouraged to re-use an existing ID if it fits their purpose.
Using this approach, existing IDs should not be updated or removed, and become a permanent feature of the HTML. (But like any rule, it can be broken if need be and the risk is worth it)
This way everyone should be comfortable to reuse existing IDs without having their code being broken by someone else changing them, and the ID names should make sense for all uses. This should lead to not having too many "extra" IDs.
Regarding Classes:
In 2+ person teams, there also seems to be a tendency to keep adding more and more ... and avoiding cleaning up those that are already there, in fear of breaking things.
My experiences match yours; people tend to add a new class rather than reuse an existing one. This can also sometimes lead to developers being more comfortable to remove a class if they think they've deleted the only code that used it. This in turn bites anyone who did reuse the class, and they think "next time I'll just add my own new class to be safe". A good example of a vicious cycle.
I try to treat classes in the same way as IDs (described above) and:
Use non-use-specific names
Reuse an existing class if there's one already there that "makes sense" by its name
Discourage changing or removing existing classes (to increase confidence with reuse)
With additional thought, an exception could be made for classes added for only "external" reasons, such as testing, by having classes with a common prefix such as "tst". I would consider this approach if the use:
Will create a large number of classes (noise)
Is expected to be changed a lot (as the usage is bedded down)
Expected to possibly be replaced in future with a difference approach
Is controlled by an external group to the development team
But using any kind of naming convention is only as good as the people who follow it (or don't). Testing is really the only way to know if something has been broken when there isn't a compiler to tell you that there's a bad reference hanging around.
tldr;
So, in general I don't try to organise my IDs and Classes by how they are used, and I try to maximise their reuse and minimise their changes. But I have an open mind if more compelling answers are given to this question!
I would say: classes (and targeting HTML elements directly or in combination) for styling, id's for behaviour (and Selenium), "do not repeat yourself/others" thinking - cascading styles, and that is about it.
If everyone follows this concept - common goal to keep clean code is achieved but at the same time it can also mean more problems - for example multiple event delegations (not using "proper" object oriented concepts) and CSS class chains on same element can cause even less readability and more time to handle.
So - actually it is very hard to have a general rule - especially if people have different views and code-styles. But I still think - classes for styling and id's for behaviour applies...

Mobile website too slow on the phone [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I am building a prototype for a mobile section of a website. It uses no dynamic staff, just jQuery and Foundation 4. When I test the site in the iphone's browser, it's very very slow to load and to respond to touches. Can some experienced folks please tell me all things to make sure the site loads and operates faster on the mobile device?
All my images are saved "for web", so they shouldn't be a problem. Could it be slow because my CSS style sheet is very lengthy? I am not an expert at combining and applying one classes to a lot of things yet, so may be I have too many id-s and separate classes? Would that be a big deal in this case though? Also, could it be slow because I am using Foundation, jQuery and a Flexlider plug in and each of them has their own multiple style sheets and .js files? Should I throw away any files I am not using from their folders? Am I on the right track and what else can I do? Thank you in advance.
There are some things which helped me to make my mobile app more faster. I had the same issue as you, the screen response was very low.
Get rid of every unused code
I had a lot of commented code and files that i actually didn't use. This includes css styles that aren't used.
Do you even need classes or Ids?
Looking at my app, i had almost on any element a class or Id. Were i instead could use a element selector. here some more info about the selectors. Follow the DOM structure. I mostly used a class for groups and Ids for one specific element(which i almost never needed).
Check if you have css styles that doesn't add something
Sometimes you have multiple styles that doesn't actually add anything to it. A great example is using a float: *; and display: inline-block;. When using both of these on one element has no extra function as float makes the element inline-block by default.
optimize you script
With this i mean, see if you can shorter you codes with the same functionality. Using two almost identical functions? short them to one function. Also using premade function of your script language will really help you to make your code faster. So don't create your own sort function, but use the premade function.
For help on optimizing you code, i suggest you to take a look here.
jQuery selectors
Make your jQuery selectors more specific. For example:
You may have a div with class content.
<div class="content"></div>
Instead of selecting it with
$('.content')
You could use
$('div.content' )
jQuery can now restrict the search to DIV elements only.
More info fore more efficient jQuery selectors here
Store determenation code
When you get information, for example screenWidth minus the width of a other div, and you using this more then once, store it! This way your webpage hasn't to do the calculate over and over and can just get the variable.
Don't use 'big' plugins when using half of it
When you only use a small part of a plugin you're using, it's better to find or a other plugin or code it yourself. Loading the plugin files might harm your performence, would be a shame if it actually wasn't even necessary.
This is just a global view were I had a big advantage on and I hope you can find a fine use for this.
Feel free to correct me when I'm wrong.

How to organize JS loading?

I have a serious project with big JS file with many functions, and now I have some questions about it.
Of course, I will stick together all my js files and gzip it, but I have a question about functions initialisations. Now I have many, many simple functions, without any classes. I heard that it is better to separate my code into many classes, and I want to do it, and on page generation step mark in my script, which classes I need on specific page. For example, I don't need a WYSIWYG editor at the main page, and so forth, so I will create special var with array of js classes which I need. Is this the best practice? Will clients get performance and memory savings?
Suppose that I have many links with onclick actions. What is better: leave them as <a href="#" onclick="return smth();"> or rewrite as <a href="javascript:void(0);"> and create jquery .bind in document.ready section? But what if the client wants to click something before the document is ready?
After a click on something I must create a div with specific static html. Where is it better to store this content? In some var in my class? Or maybe in some template?
I usually organize my JavaScript using namespacing to prevent function name clashing and further add each object into it's own .js file for organization purposes
var MyObject = function() {
return {
method_1 : function() {
// do stuff here
},
method_2 : function() {
// do stuff here
}
};
}();
MyObject.method_1();
MyObject.method_2();
I then import whatever is needed on my pages. Having a few extra global functions that aren't used on a page won't make a noticeable change in performance.
Some people turn the whole onclick in HTML into a grand philosophical debate... for me, it's dirty, yet easy to read and quick to implement. Binding events works great and completely separates JavaScript from HTML but sometimes can be difficult to maintain if your HTML being maintained by many developers gets very sloppy
Keeping the HTML bits in JavaScript has worked fine for me
You might also be interested in looking at the Google Closure JavaScript compiler.
Also: If your JS is large enough to affect performance, you may actually end up getting better performance out of separate files and load depending on what your page initially needs or load-on-demand (via jQuery getScript).
You might also want to look into what kinds of actions you expect users to be using before the DOM is ready.
As for HTML in JS (or vice-versa). It depends. How much HTML are you building? I usually don't put more than one line of HTML in a .html() statement. If it's really more than that, I look at a different solution (like pulling it from another source on-demand or putting it somewhere, hidden, in the page and yanking it over).

Categories