Delineating a section of HTML without altering document flow - javascript

I'm working on a web application that requires me to transparently delineate a section of the DOM for usage with JavaScript. The issue is that I don't necessarily know what the rest of the page markup will look like.
I do know that the markup within the section will be 'self-contained' in that tags started within the section will also end within the section and vice versa.
I could play it safe and use comments at the start and end of the section, but this makes it somewhat inconvenient to play with in JavaScript. I'd rather be able to use DOM manipulation functions to find and modify this section.
So I guess my question is, do 'inline' elements modify the document flow at all? (Without special CSS rules) I'd like the document to look exactly the same if the tags delineating the section weren't present.
If an inline element does alter the document flow, is there a way to make an element that can be recognised by JavaScript but does not alter the document flow?
Thanks,
YM
P.S. Cross-browser support and standards compliance are important to me on this one.
EDIT: Quick note that I'm not just being lazy here. I have conducted tests and research about this and so far I believe inline elements don't alter the flow at all. (Unless they are told to with CSS) The purpose for this question is the ensure that these observations are correct and to discover any possible scenarios under which this doesn't hold true.
EDIT2: As the comments pointed out, I don't quite seem to have the vocabulary to accurately describe what I'm asking for. I also believe this question may be subjective, so I think I'll just close it and use the data tags method provided below.

Yes, inline elements are part of the document flow. Inline elements don't start with a new line but they can flow to additional lines if their contents are too large.
It sounds like you're writing some sort of visual JS code inspector. You could target your HTML elements with JS with data-* attributes, which will not impact your CSS or flow.

Related

Javascript replacements for on(event) attributes

If this sounds like I'm asking for opinion, sorry I'm not expressing myself better.
My question is, why is it necessary to replace attributes like onclick by anonymous functions? What is the advantage?
For example, I have a web page that needs to be brought up to date, so I need to replace
<input id="text" onfocus="this.blur()">
by
<input id="text">
.
.
<script>
$('#text').focus(function(){this.blur()});
<script>
But what does this do? What is the specific advantage of this over the original? I searched, but I couldn't find any real reason, only opinions.
There are many reasons not to use dom0 events.
You can find some of these under the topic "unobtrusive javascript".
http://en.wikipedia.org/wiki/Unobtrusive_JavaScript
Decoupling the markup and the behaviour is the most obvious one
The main advantages are clarity and flexibility:
Limiting ad-hoc javascript code is considered as a good practice since all your javascript logic will be found in one place.
It allow you to write decoupled code and "non-obstrusive" javascript, which basically means that you will be able to easily change the behavior of your webpage without touching the HTML.
You can say than using "onenvent" attributes over event handlers is quite the same as using the style attribute over an attached CSS file.
using the on() function allows to add as many event listeners as you see fit.
One good advantage is that this keeps your HTML simpler & lighter and could be loaded and rendered faster while your javascript on the bottom is still being loaded. If you consider performance its better to load HTML (& css) at the very beginning and scripts at the last.
Also, it separates code from the markup, making everything less
messed up, more systematic and easier to debug.
And you can't simply write bulky java script code in attributes it becomes inconvenient, you'd have to write in functions anyway for complex logic.
No one has mentioned that inline handlers are a vector for XSS attacks.
Keeping JavaScript out of HTML allows you to harden your site and set a Content-Security-Policy: script-src 'self'
that disable JavaScript in HTML.

How does one figure out what piece of JavaScript changes a given HTML tag?

I often want to change some releatively minor detail about how JS changes the DOM, but I can never figure out which function in what script changes a given tag. How does one do this?
For example, on this page, I want whatever JS is adding the "selected" class to various a tags to also add it to the enclosing li tags. However, I have no idea how to figure out where this is taking place.
Clarification: As much as I'd like an answer to my current, specific conundrum, I'd much rather be taught how to figure it out myself.
CLARIFICATION:Is there a way to point at a certain object in the DOM and find out what script(s) are/were accessing/modifying that object? In other words "watch" that object for JS access/modification.
What you need is DOM breakpoints in WebKit's Developer Tools.
They're designed for tracking DOM mutation events - such as change of an attribute of an element (which is your case), element removal, or addition of subelement. You can refer to tutorial in DevTools documentation.
In basic cases you might want to use grep for searching the strings such as "selected" in your code.
I’m not aware of any debugging tools that’ll tell you when a DOM element is being acted upon by a script.
(If anyone knows of any, dear lord please tell me about them — I’m a freelancer, so I spend most of my working days trying to figure out old, knotty DOM-manipulating JavaScript that someone else wrote.)
You basically have to search through every bit of JavaScript file included in the page, and identify lines that might be taking the action you’re seeing.
In the case of a class name being added to an element, an obvious search is for the class name itself, although that’s not guaranteed to work. E.g.
el.className = el.className + 'sel' + 'elected'
If jQuery is in use, I’d definitely search for addClass.
Once you think you’ve found the right line, then if you have access to the JavaScript code, you can change it and see if your change takes effect.
(And, because view source is still a part of the web, you can get access to the code by saving it all to your computer.)

Why not use inline CSS if all the HTML+CSS is generated at runtime by javascript and no developer will need to work with css and html?

The only reasons I see on the internet to not to use inline-css is because of the separation of html and css & management, but if this is not a problem in my case I don't care I will use.
Another pro I can say is this: imagine you want to load a widget made by another user, you will only need to load 1 file, the javascript and not the css.
But it might have other problems?
thanks
If you read your question again, you have answered it yourself. There is a reason for the "separation" of html and CSS. Because at some point in time, you will eventually want to change the look of what you have coded up. These are the times when having a separate CSS file would be very helpful so you are only ever making changes in one place and not throughout your application.
EDIT
Another usefulness of having the CSS separate is the caching. Most of the modern browsers cache the CSS files. This means there are less round-trips to the server and quicker response times. I'm not sure if same is the case for JavaScript, because JavaScript files would be cached, but the client browser will have to execute the code every time it loads.
I think this is a good question that is worth exploring. I don't think there is a performance or standards-based argument for not using inline CSS - it works perfectly well - the only (though considerable) argument for separated CSS is for maintainability / readability. And so if you are generating CSS from JavaScript, generating it inline is just as sound as any other way.
In fact, DOM APIs in general expose much simpler methods for assigning styles directly to elements ( https://developer.mozilla.org/en/DOM/element.style ) than for creating new stylesheets. Therefore almost all JavaScript libraries, like jQuery, when they have to manipulate styles they do it by adding inline styles to an element.
Having said that, I have never before seen a situation where the mark-up and styling for a whole page was generated with JavaScript. I would expect this to be rather inefficient. I can see that if you have a web application where all content is pulled in through Ajax (a perfectly good solution) then you might write a fair bit of the mark-up with JavaScript, but still it would be better/more efficient to load most of the surrounding mark-up for your content in the initial page load, and then use JavaScript to swap out content within existing elements.
In any case, I would recommend that you keep most of your CSS in an external stylesheet with relevant classes already defined, so that all your JavaScript does is create elements with the correct class. This would have a performance advantage and would also mean that all your style information was located in one place, and is separate from your JavaScript, which would make your code easier to maintain.
It's OK to use inline css. (in this specifice case)

Why is it bad practice to use links with the javascript: "protocol"?

In the 1990s, there was a fashion to put Javascript code directly into <a> href attributes, like this:
Press me!
And then suddenly I stopped to see it. They were all replaced by things like:
Press me!
For a link whose sole purpose is to trigger Javascript code, and has no real href target, why is it encouraged to use the onclick property instead of the href property?
The execution context is different, to see this, try these links instead:
Press me! <!-- result: undefined -->
Press me! <!-- result: A -->
javascript: is executed in the global context, not as a method of the element, which is usually want you want. In most cases you're doing something with or in relation to the element you acted on, better to execute it in that context.
Also, it's just much cleaner, though I wouldn't use in-line script at all. Check out any framework for handling these things in a much cleaner way. Example in jQuery:
$('a').click(function() { alert(this.tagName); });
Actually, both methods are considered obsolete. Developers are instead encouraged to separate all JavaScript in an external JS file in order to separate logic and code from genuine markup
http://www.alistapart.com/articles/behavioralseparation
http://en.wikipedia.org/wiki/Unobtrusive_JavaScript
The reason for this is that it creates code that is easier to maintain and debug, and it also promotes web standards and accessibility. Think of it like this: Looking at your example, what if you had hundreds of links like that on a page and needed to change out the alert behavior for some other function using external JS references, you'd only need to change a single event binding in one JS file as opposed to copying and pasting a bunch of code over and over again or doing a find-and-replace.
Couple of reasons:
Bad code practice:
The HREF tag is to indicate that there is a hyperlink reference to another location. By using the same tag for a javascript function which is not actually taking the user anywhere is bad programming practice.
SEO problems:
I think web crawlers use the HREF tag to crawl throughout the web site & link all the connected parts. By putting in javascript, we break this functionality.
Breaks accessibility:
I think some screen readers will not be able to execute the javascript & might not know how to deal with the javascript while they expect a hyperlink. User will expect to see a link in the browser status bar on hover of the link while they will see a string like: "javascript:" which might confuse them etc.
You are still in 1990's:
The mainstream advice is to have your javascript in a seperate file & not mingle with the HTML of the page as was done in 1990's.
HTH.
I open lots of links in new tabs - only to see javascript:void(0). So you annoy me, as well as yourself (because Google will see the same thing).
Another reason (also mentioned by others) is that different languages should be separated into different documents. Why? Well,
Mixed languages aren't well supported
by most IDEs and validators.
Embedding CSS and JS into HTML pages
(or anything else for that matter)
pretty much destroys opportunities to
have the embedded language checked for correctness
statically. Sometimes, the embedding language as well.
(A PHP or ASP document isn't valid HTML.)
You don't want syntax
errors or inconsistencies to show up
only at runtime.
Another reason is to have a cleaner separation between
the kinds of things you need to
specify: HTML for content, CSS for
layout, JS usually for more layout
and look-and-feel. These don't map
one to one: you usually want to apply
layout to whole categories of
content elements (hence CSS) and look and feel as well
(hence jQuery). They may be changed at different
times that the content elements are changed (in fact
the content is often generated on the fly) and by
different people. So it makes sense to keep them in
separate documents as well.
Using the javascript: protocol affects accessibility, and also hurts how SEO friendly your page is.
Take note that HTML stands for Hypter Text something something... Hyper Text denotes text with links and references in it, which is what an anchor element <a> is used for.
When you use the javascript: 'protocol' you're misusing the anchor element. Since you're misusing the <a> element, things like the Google Bot and the Jaws Screen reader will have trouble 'understanding' your page, since they don't care much about your JS but care plenty about the Hyper Text ML, taking special note of the anchor hrefs.
It also affects the usability of your page when a user who does not have JavaScript enabled visits your page; you're breaking the expected functionality and behavior of links for those users. It will look like a link, but it won't act like a link because it uses the javascript protocol.
You might think "but how many people have JavaScript disabled nowadays?" but I like to phrase that idea more along the lines of "How many potential customers am I willing to turn away just because of a checkbox in their browser settings?"
It boils down to how href is an HTML attribute, and as such it belongs to your site's information, not its behavior. The JavaScript defines the behavior, but your never want it to interfere with the data/information. The epitome of this idea would be the external JavaScript file; not using onclick as an attribute, but instead as an event handler in your JavaScript file.
Short Answer: Inline Javascript is bad for the reasons that inline CSS is bad.
The worst problem is probably that it breaks expected functionality.
For example, as others has pointed out, open in new window/tab = dead link = annoyed/confused users.
I always try to use onclick instead, and add something to the URL-hash of the page to indicate the desired function to trigger and add a check at pageload to check the hash and trigger the function.
This way you get the same behavior for clicks, new tab/window and even bookmarked/sent links, and things don't get to wacky if JS is off.
In other words, something like this (very simplified):
For the link:
onclick = "doStuff()"
href = "#dostuff"
For the page:
onLoad = if(hash="dostuff") doStuff();
Also, as long as we're talking about deprecation and semantics, it's probably worth pointing out that '</a>' doesn't mean 'clickable' - it means 'anchor,' and implies a link to another page. So it would make sense to use that tag to switch to a different 'view' in your application, but not to perform a computation. The fact that you don't have a URL in your href attribute should be a sign that you shouldn't be using an anchor tag.
You can, alternately, assign a click event action to nearly any html element - maybe an <h1>, an <img>, or a <p> would be more appropriate? At any rate, as other people have mentioned, add another attribute (an 'id' perhaps) that javascript can use as a 'hook' (document.getElementById) to get to the element and assign an onclick. That way you can keep your content (HTML) presentation (CSS) and interactivity (JavaScript) separated. And the world won't end.
I typically have a landing page called "EnableJavascript.htm" that has a big message on it saying "Javascript must be enabled for this feature to work". And then I setup my anchor tags like this...
<a href="EnableJavascript.htm" onclick="funcName(); return false;">
This way, the anchor has a legitimate destination that will get overwritten by your Javascript functionality whenever possible. This will degrade gracefully. Although, now a days, I generally build web sites with complete functionality before I decide to sprinkle some Javascript into the mix (which all together eliminates the need for anchors like this).
Using onclick attribute directly in the markup is a whole other topic, but I would recommend an unobtrusive approach with a library like jQuery.
I think it has to do with what the user sees in the status bar. Typically applications should be built for failover in case javascript isn't enabled however this isn't always the case.
With all the spamming that is going on people are getting smarter and when an email looks 'phishy' more and more people are looking at the status bar to see where the link will actually take them.
Remember to add 'return false;' to the end of your link so the page doesn't jump to the top on the user (unless that's the behaviour you are looking for).

Why Stackoverflow binds user actions dynamically with javascript?

Checking the HTML source of a question I see for instance:
<a id="comments-link-xxxxx" class="comments-link">add comment</a><noscript> JavaScript is needed to access comments.</noscript>
And then in the javascript source:
// Setup our click events..
$().ready(function() {
$("a[id^='comments-link-']").click(function() { comments.show($(this).attr("id").substr("comments-link-".length)); });
});
It seems that all the user click events are binded this way.
The downsides of this approach are obvious for people browsing the site with no javascript but, what are the advantages of adding events dynamically whith javascript over declaring them directly?
You don't have to type the same string over and over again in the HTML (which if nothing else would increase the number of typos to debug)
You can hand over the HTML/CSS to a designer who need not have any javascript skills
You have programmatic control over what callbacks are called and when
It's more elegant because it fits the conceptual separation between layout and behaviour
It's easier to modify and refactor
On the last point, imagine if you wanted to add a "show comments" icon somewhere else in the template. It'd be very easy to bind the same callback to the icon.
Attaching events via the events API instead of in the mark-up is the core of unobtrusive javascript. You are welcome to read this wikipedia article for a complete overview of why unobtrusive javascripting is important.
The same way that you separate styles from mark-up you want to separate scripts from mark-up, including events.
I see this as one of the fundamental principals of good software development:
The separation of presentation and logic.
HTML/CSS is a presentation language essentially. Javascript is for creating logic. It is a good practice to separate any logic from your presentation if possible.
This way you can have a light-weight page where you can handle all your actions via javascript. Instead of having to use loads of different urls and actions embedded into the page, just write one javascript function that finds the link, and hooks it up, no matter where on the page you dump that 'comment' link.
This saves loads of repeating html :)
The only advantage I see is a reduction of the page size, and thus a lower bandwith need.
Edit: As I'm being downvoted, let met explain a more my answer.
My point is that, using a link as an empty anchor is just a bad practice, nothing else! Of course separation of JavaScript logic from HTML is great. Of course it's easier to refactor and debug. But here, it's against the main principle of unobtrusive JavaScript: Gracefull degradation!
A good solution would be to have to possible call of the comments: one through a REAL link that will point to a simple page showing the comment and another which returns only the comments (in a JSON notation or similar format) with the purpose of being called through AJAX to be injected directly in the main page.
Doing so, the method using the AJAX method should also take care of cancelling the other call, to avoid that the user is redirected to the simple page. That would be Unobtrusive JavaScript. Here it's just JavaScript put on a misused anchor tag.

Categories

Resources