I would like to understand how HTML, JS and CSS work together and reference one another.
I have found that HTML can reference CSS via an id reference.
Example: <div id="left-show"></div>
However, it would be much appreciated if someone could clarify the following:
How would you tell your HTML code to reference a specific JS function.
Within a JS function, is it a good practice to reference a CSS id?
If a JS function and CSS id share the same name, would that create a conflict?
How would you tell your HTML code to reference a specific JS function.
Generally, you don't.
You include a script (with a <script> element) that accesses whatever parts of the DOM you want it to interact with (via the document object that the browser will make available to the script).
You can use the addEventListener method to bind a function so that it will run in response to an event (such as a button being clicked).
Within a JS function, is it a good practice to reference a CSS id?
There is no such thing as a CSS id. HTML has IDs which have a multitude of purposes including being matched by CSS ID selectors, being linked to with a fragment identifier on the end of a URL and allowing a <label> to reference its associated form control with the for attribute.
If you want to access a specific element, then an HTML ID is a good way to identify it (via the getElementById method).
If a JS function and CSS id share the same name, would that create a conflict?
There can be some issues if JavaScript variables of any kind (including functions) match the ID of an HTML element. This is best avoided by staying away from the global scope as much as possible (as per this answer).
Your questions are a bit far-reaching for a full explanation on a concise Q&A site like SA. You would really need to read a lot of material for a full understanding.
However, some brief simplified answers to get you started
1) HTML links to JavaScript via events that trigger JavaScript functions. This is an example of a very simple event on an HTML element that will look for a function in your JavaScript declared as function aJavaScriptFunction(){ } when you click on the button. There are different ways to do this and different types of event, but this is a good place to start.
<input id="thebutton" type="button" value="A Button" onclick="aJavaScriptFunction();" />
2) It very much depends what you are trying to do, but in general selecting HTML DOM elements via their ID is an efficient method of selecting them to do something with them. So this might be the JavaScript function that we're using in the previous example.
function aJavaScriptFunction()
{
var aButtonElement = document.getElementById("thebutton"); // <-- It's not a "CSS id" as such, CSS can use the HTML id
// .... some more javascript that uses aButtonElement like
aButtonElement.style.borderColor = "red";
}
3) No. JavaScript and CSS don't really directly overlap as such in the way you might be thinking, when you're beginning, think of them both as altering the HTML. It is possible to do some of the same things with JavaScript as CSS, but in general they happen at different times. This CSS doesn't conflict with the previous JavaScript, though they both do similar things.
#thebutton { border-color: blue; }
Here are all my examples put together into a jsFiddle where you can play with them.
You'd be best off visiting somewhere like W3 Schools or Code Academy.
Related
I have a big working project with massive frontend javascript code. If I add elements with class "icon" to one of templates, this elements get display:none at once. Obviously it comes from javascript, but I can't find it by file searching with ".icon" and related.
Is there a program way to find where this setting comes from? "Where" means anything helpful - function name, file name or something.
Your problem is one of the reasons I somewhat disagreed with the Unobtrusive JavaScript mantra from a few years back, which decreed that you should always target elements via selector hierarchy instead of attributes like "onload" on the element themselves. It becomes a nightmare to track down why a given element is affected. It could be because of a class, or because the element has ANY class at all, or if its class starts with "ic", etc etc etc.
Since you mention that it only happens when you apply the "icon" class, its definitely still most likely steaming up from that. Keep searching through all the JS methods that fire at pageload and look for "display: none" or "hide()" methods. Some of jquery's animation methods might be the culprit too, if they are running fast enough.
I want to implement a timer in DOM but I don't want to use any Javascript. Is this actually possible?
I already have the code in Javascript but I would like to change it to DOM so that I don't have to activate JS.
Thanks for any help :D
The only way to reliably modify the Document Object Model is with JavaScript. DOM is just a structure for accessing parts of a webpage, nothing more.
So unless you have a vendetta against JavaScript and would rather using something like client side VBscript (IE only) you have to use JavaScript.
If you just want to get a similar effect you could try playing with CSS pseudo-elements which I doubt will cover your needs. Also CSS pseudo-elements aren't really part of the page so there are quirks; pseudo-element text cannot be selected for example.
In short, you must use JavaScript to "use" DOM, its a structure, not a language.
I have been struggling with choosing unobtrusive javascript over defining it within the html syntax. I want to convince my self to go the unobtrusive route, but I am having trouble getting past the issues listed below. Can you please help convince me :)
1) When you bind events unobtrusively, there is extra overhead on the client's machine to find that html element, where as when you do stuff, you don't have to iterate the DOM.
2) There is a lag between when events are bound using document.ready() (jquery) and when the page loads. This is more apparent on very large sites.
3) If you bind events (onclick etc) unobtrusively, there is no way of looking at the html code and knowing that there is an event bound to a particular class or id. This can become problematic when updating the markup and not realizing that you may be effecting javascript code. Is there a naming convention when defining css elements which are used to bind javascript events (i have seen ppl use js_className)
4) For a site, there are different pieces of javascript for different pages. For example Header.html contains a nav which triggers javascript events on all pages, where as homepage.html and searchPage.html contains elements that trigger javascript on their respective pages
sudo code example:
header.html
<script src="../myJS.js"></script>
<div>Header</div>
<ul>
<li>nav1</li><li>nav2</li>
</ul>
homepage.html
<#include header.html>
<div class="homepageDiv">some stuff</div>
searchpage.html
<#include header.html>
<div class="searchpageDiv">some other stuff</div>
myJS.js
$(document).ready(function(){
$("ul.li").bind("click",doSomething());
$(".homePageDiv").bind("click",doSomethingElse());
$(".searchPageDiv").bind("click",doSomethingSearchy());
});
In this case when you are on the searchPage it will still try to look for the "homepageDiv" which does not exist and fail. This will not effect the functionality but thats an additional unnecessary traversal. I could break this up into seperate javascript files, but then the browser has to download multiple files, and I can't just serve one file and have it cached for all pages.
What is the best way to use unobtrusive javascript so that I could easily maintain a ( pretty script heavy) website, so another developer is aware of scripts being bound to html elements when they are modifying my code. And serve the code so that the client's browser is not looking for elements which do not exist on a particular page (but may exist on others).
Thanks!
You are confused. Unobtrusive JavaScript is not just about defining event handlers in a program. It's a set of rules for writing JavaScript such that the script doesn't affect the functionality of other JavaScript on the same page. JavaScript is a dynamic language. Anyone can make changes to anything. Thus if two separate scripts on the same page both define a global variable add as follows, the last one to define it will win and affect the functionality of the first script.
// script 1
var add = function (a, b) {
return a + b;
};
// script 2
add = 5;
//script 1 again
add(2, 3); // error - add is a number, not a function
Now, to answer your question directly:
The extra overhead to find an element in JavaScript and attach an event listener to it is not a lot. You can use the new DOM method document.querySelector to find an element quickly and attach an event listener to it (it takes less than 1 ms to find the element).
If you want to attach your event listeners quickly, don't do it when your document content loads. Attach your event listeners at the end of the body section or directly after the part of your HTML code to which you wish to attach the event listener.
I don't see how altering the markup could affect the JavaScript in any manner. If you try to attach an event listener to an element that doesn't exist in JavaScript, it will silently fail or throw an exception. Either way, it really won't affect the functionality of the rest of the page. In addition, a HTML designer really doesn't need to know about the events attached any element. HTML is only supposed to be used for semantic markup; CSS is used for styling; and JavaScript is used for behavior. Don't mix up the three.
God has given us free will. Use it. JavaScript supports conditional execution. There are if statements. See if homePageDiv exists and only then attach an event listener to it.
Try:
$(document).ready(function () {
$("ul.li").bind("click",doSomething());
if (document.querySelector(".homePageDiv")) {
$(".homePageDiv").bind("click",doSomethingElse());
} else {
$(".searchPageDiv").bind("click",doSomethingSearchy());
}
});
Your question had very little to do with unobtrusive JavaScript. It showed a lack of research and understanding. Thus, I'm down voting it. Sorry.
Just because jQuery.ready() executes does not mean that the page is visible to the end user. This is a behaviour defined by browsers and these days there are really 2 events to take into consideration here as mootools puts it DomReady vs Load. When jQuery executes the ready method it's talking about the dom loading loaded however this doesn't mean the page is ready to be viewed by the user, external elements which as pictures and even style sheets etc may still be loading.
Any binding you do, even extremely inefficient ones will bind a lot faster than all the external resources being loaded by the browser so IMHO user should experience no difference between the page being displayed and functionality being made available.
As for finding binding on elements in your DOM. You are really just fearing that things will get lost. This has not really been my actual experience, more often than not in your JS you can check what page you are on and only add javascript for that page (as Aadit mentioned above). After that a quick find operation in your editor should help you find anything if stuff gets lost.
Keep in mind that under true MVC the functionality has to be separate from the presentation layer. This is exactly what OO javascript or unobtrusive javascript is about. You should be able to change your DOM without breaking the functionality of the page. Yes, if you change the css class and or element id on which you bind your JS will break, however the user will have no idea of this and the page will at least appear to work. However if this is a big concern you can use OO-Javascript and put div's or span's as placeholders in your dom and use these as markers to insert functionality or tell you that it exists, you can even use html comments. However, in my experience you know the behavior of your site and hence will always know that there is some JS there.
While I understand most of your concerns about useless traversals, I do think you are nickle and dime'ing it at this point if you are worried about 1 additional traversal. Previous to IE8 it used to be the case that traversing with the tag name and id was a lot faster than my selector but this is no longer true infact browsers have evolved to be much faster when using just the selectors:
$("a#myLink") - slowest.
$("a.myLink") - faster.
$("#Link") - fastest.
$(".myLink") - fastest.
In the link below you can see that as many as 34 thousand operations per second are being performed so I doubt speed is an issue.
You can use firebug to test the speed of each in the case of a very large dom.
In Summary:
a) Don't worry about losing js code there is always ctrl+f
b) There is no lag because dom ready does not mean the page is visible to start with.
Update
Fixed order of speed in operations based on the tests results from here
However keep in mind that performances of IE < 8 are really had if you don't specify the container (this used to be the rule, now it seems to be the exception to the rule).
As I've gotten deeper into using jQuery with various sites I've worked on, I've found that I can get lost on whether a class attribute value is appended to an element in the DOM in order to attach an actual CSS style, or to bind an event to it. As such, I've started leaning towards using the rel attribute on anchor tags to denote if something is going to be bound to an event, keeping the class attribute specifically for stylization. (I've not delved into this deep enough to determine if there are any drawbacks or fundamental flaws with this approach, however, and am open to comments & criticisms on it.)
It got me to thinking that others must have similar things they do to help keep their code organized, and I'm interested in learning about some new ideas that might be floating around out there.
Usually this is not much of an issue for me, even in medium sized projects.
I usually assign classes for styling, and I often end up using same selectors in JS code.
Semantically speaking, the rel attribute is not an appropriate way to store data. As it should point out the relation of a link to the target.
HTML5 makes things more flexible with data- custom attributes.
You use the class attribute when you have multiple HTML elements that have shared presentation or shared behavior.
So if you have several buttons for which you want to use the same event handler, then you give those buttons a class and then use JavaScript to select those elements (by class) in order to set the handler on them (you use a JavaScript library which has a selector engine). For example, in jQuery:
$(".addButton").click(function() {
// the event handler
});
Classes are used both for CSS styling and JavaScript manipulation.
Is there a way to create your own HTML element? I want to make a specially designed check box.
I imagine such a thing would be done in JavaScript. Something akin to document.createHTMLElement but the ability to design your own element (and tag).
No, there isn't.
The HTML elements are limited to what the browser will handle. That is to say, if you created a custom firefox plugin, and then had it handle your special tag, then you "could" do it, for varying interpretations of "doing it". A list of all elements for a particular version of HTML may be found here: http://www.w3.org/TR/html4/index/elements.html
Probably, however, you don't actually want to. If you want to "combine" several existing elements in such a way as they operate together, then you can do that very JavaScript. For example, if you'd like a checkbox to, when clicked, show a dropdown list somewhere, populated with various things, you may do that.
Perhaps you may like to elaborate on what you actually want to achieve, and we can help further.
Yes, you can create your own tags. You have to create a Schema and import it on your page, and write a JavaScript layer to convert your new tags into existing HTML tags.
An example is fbml (Facebook Markup Language), which includes a schema and a JavaScript layer that Facebook wrote. See this: Open Graph protocol.
Using it you can make a like button really easily:
<fb:like href="http://developers.facebook.com/" width="450" height="80"/>
The easiest way would be probably to write a plugin say in Jquery (or Dojo, MooTools, pick one).
In case of jQuery you can find some plugins here http://plugins.jquery.com/ and use them as a sample.
You need to write own doctype or/and use own namespace to do this.
http://msdn.microsoft.com/en-us/magazine/cc301515.aspx
No, there is not. Moreover it is not allowed in HTML5.
Take a look at Ample SDK JavaScript GUI library that enables any custom elements or event namespaces client-side (this way XUL for example was implemented there) without interferring with the rules of HTML5.
Take a look into for example how XUL scale element implemented: http://github.com/clientside/amplesdk/blob/master/ample/languages/xul/elements/scale.js and its default stylesheet: http://github.com/clientside/amplesdk/blob/master/ample/languages/xul/themes/default/input.css
It's a valid question, but I think the name of the game from the UI side is progressive markup. Build out valid w3 compliant tags and then style them appropriately with javascript (in my case Jquery or Dojo) and CSS. A well-written block of CSS can be reused over and over (my favorite case is Jquery UI with themeroller) and style nearly any element on the page with just a one or two-word addition to the class declaration.
Here's some good Jquery/Javascript/CSS solutions that are relatively simple:
http://www.filamentgroup.com/examples/customInput/
http://aaronweyenberg.com/90/pretty-checkboxes-with-jquery
http://www.protofunc.com/scripts/jquery/checkbox-radiobutton/
Here's the spec for the upcoming (and promising) JqueryUI update for form elements:http://wiki.jqueryui.com/Checkbox
If you needed to validate input, this is an easy way to get inline validation with a single class or id tag: http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/
Ok, so my solution isn't a 10 character, one line solution. However, Jquery Code aside, each individual tag wouldn't be much more than:
<input type="checkbox" id="theid">
So, while there would be a medium chunk of Jquery code, the individual elements would be very small, which is important if you're repeating it 250 times (programmatically) as my last project required. It's easy to code, degrades well, validates well, and because progressive markup would be on the user's end, have virtually no cost on the server end.
My current project is in Symfony--not my choice--which uses complex, bulky server-side tags to render form elements, validate, do javascript onclick, style, etc. This seems like what you were asking for at first....and let me tell you, it's CLUNKY. One tag to call a link can be 10 lines of code long! After being forced to do it, I'm not a fan.
Hm. The first thought is that you could create your own element and do a transformation with XSLT to the valid HTML then.
With the emergence of the emerging W3 Web Components standard, specifically the Custom Elements spec, you can now create your own custom HTML elements and register them with the parser with the document.register() DOM method.
X-Tag is a helpful sugar library, developed by Mozilla, that makes it even easier to work with Web Components, have a look: X-Tags.org