I'm getting more into jQuery and so have set up a HTML/Javascript/CSS base site which I use for all my tests.
Since these tests will eventually turn into PHP and ASP.NET MVC websites, I want to use this opportunity to get the basics down right again for modern browsers and web standards before building the scripting languages on top of it.
I've selected to use:
XHTML 1.0 Strict
UTF-8 encoding
as few CSS references as possible (put everything in 1 CSS file for loading speed)
as few Javascript references as possible (1 javascript file plus the jquery code base reference - I assume using the Google jQuery code base is best practice for speed)
I check my code as I build it with the http://validator.w3.org
Is there anything else I need to consider?
Here is an example of one of my test websites:
index.htm:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
<title>Text XHTML Page</title>
<link href="css/main.css" rel="stylesheet" type="text/css" media="all"/>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript" src="javascript/main.js"></script>
</head>
<body>
<h1 class="highlightTitle">Text</h1>
<p class="main">First</p>
<p>Second</p>
<p id="selected" class="regular">Third</p>
<p>Fourth</p>
<form action="">
<div>
<input type="button" value="highlight it" onclick="highlightIt();countThem()" />
<input type="button" value="highlight title" onclick="highlightTitle()" />
<p>here is another paragraph</p>
</div>
</form>
</body>
</html>
main.cs:
p.highlighted {
background-color:orange;
}
h1.highlightTitle {
background-color:yellow;
}
h1.deselected {
background-color:#eee;
}
p.regular {
font-weight: bold;
}
main.js:
google.load("jquery", "1.3.2");
function highlightIt() {
$('#selected')
.toggleClass('highlighted');
}
function countThem() {
alert("there are " + $("p.main").size() + " paragraphs");
}
function highlightTitle() {
$("h1").toggleClass("deselected");
}
Personally I would bind to the click event via jQuery to ensure nice separation, like this:
$("#yourId").bind("click", highlightIt);
This way you can bind to multiple event handlers. If you just use onclick AFAIK you can only ever use one handler.
BTW you can also use custom event and event namespaces:
$("#yourId").bind("beforeHighlighting", doSomething);
is triggered by
$("#yourId").trigger("beforeHighlighting");
and
$(".hasAHelptext").bind("helptext.click", showHelptextFct);
$(".hasAHelptext").bind("click", otherFct);
// will only remove the showHelptextFct event handler
$(".hasAHelptext").unbind("helptext.click");
HTH
Alex
Move the <script> blocks to the bottom of the page.
With regard to CSS and JS files in general, I wouldn't combine all JS files to a single file during development. It gets very hard to develop in one big JS file. Rather use a module that combines them on-the-fly or during deployment.
I usually go with (both CSS and JS):
one general file:
project.css
and one per page:
project_welcome.css
and any special components (login controls, ad area views etc) have a seperate one as well.
That way you can apply some organizing techniques and won't go crazy managing that single large file.
HTH
Alex
I would recommend putting the JS calls below the body tag. If your scripts are hanging, then the page can load and let the behavior (JS) load after the fact. I've noticed that speed greatly improves with this method.
Check this out: http://stevesouders.com/hpws/rule-js-bottom.php
Related
I don't want to use styles from style.css, so I decided to remove style.css from DOM. This work just fine in Firefox and IE8, but not in IE6:
$("LINK[href='http://www.example.com/style.css']").remove();
Any other solution, with jQuery?
Here is example:
HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Testing</title>
<script type="text/javascript" src="path/to/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("link[href*='style.css']").remove();
});
</script>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div id="content">...</div>
</body>
</html>
And here is CSS (style.css):
#content {
background-color:#333;
}
Only in IE #content is still dark. :(
Maybe is jQuery bug?
This is not a bug in jQuery, it is a bug (or possibly, a feature) of the IE rendering engine.
It seems this problem is being caused by the fact that Internet Explorer does not correctly re-render the page after removing the LINK element from the DOM.
In this particular case, the LINK tag is no longer present at the DOM, but IE still displays the CSS that has been loaded into memory.
A workaround / solution for this is to disable the stylesheet using the .disabled property like this:
// following code will disable the first stylesheet
// the actual DOM-reference to the element will not be removed;
// this is particularly useful since this allows you to enable it
// again at a later stage if you'd want to.
document.styleSheets[0].disabled = true;
EDIT in reply to your comment:
Or, if you want to remove it by the href use the following code:
var styleSheets = document.styleSheets;
var href = 'http://yoursite.com/foo/bar/baz.css';
for (var i = 0; i < styleSheets.length; i++) {
if (styleSheets[i].href == href) {
styleSheets[i].disabled = true;
break;
}
}
Perhaps it's something strange IE6 does to URL in the href attribute? Try something like:
$("LINK[href*='style.css']").remove();
(i.e. check whether the href value contains "style.css")
It's just a guess, however. If that doesn't work, I recommend checking the JQuery documentation closely on the subject of attribute selectors and the remove method.
Also keep in mind that it's also not impossible that it's in fact a bug. (IE6 in general causes lots of issues involving JavaScript and DOM manipulation, among other things.)
Topic's quite old, but You can only add ID to your link element, and delete it by element:
$("#id").remove();
Maybe using lowercase on the tag name?
I am attempting to code a simple example of a Dojo dialog box. I have copied the example shown in the Dojo reference here => http://dojotoolkit.org/reference-guide/1.7/dijit/Dialog.html
My code is shown below:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Dialog Test</title>
<script language="JavaScript" type="text/javascript">
dojo.require("dojo.parser");
dojo.require("dojox.widget.Dialog");
dojo.require("dijit.form.Button");
dojo.require("dijit.layout.TabContainer")
dojo.require("dijit.layout.ContentPane")
</script>
</head>
<body>
<div id="dialogOne" dojoType="dojox.widget.Dialog" title="My Dialog Title">
<div dojoType="dijit.layout.TabContainer" style="width: 200px; height: 300px;">
<div dojoType="dijit.layout.ContentPane" title="foo">Content of Tab "foo"</div>
<div dojoType="dijit.layout.ContentPane" title="boo">Hi, I'm Tab "boo"</div>
</div>
</div>
<p>When pressing this button the dialog will popup:</p>
<button id="buttonOne" dojoType="dijit.form.Button">Show me!
<script type="dojo/method" event="onClick" args="evt">
// Show the Dialog:
dijit.byId("dialogOne").show();
</script>
</button>
</body>
</html>
When the page loads in a browser, the Dialog doesn't work. I just see the text from the tabbed panes appear in the browser.
I've copied the code from the reference guide exactly so I'm very confused. Any suggestions?
Thanks.
James.
The Dojo samples unfortunately tend not to work fully 'as is', but are bits of skeleton code that need wrapping up in various standard bits of ceremony.
You've at least three things causing this not to work and render correctly. There may be other problems on top, but these will definitely cause it not to render:
You need to link to a version of the core Dojo scripts. Linking to a CDN version is a simple way to go. e.g. <script src="//ajax.googleapis.com/ajax/libs/dojo/1.8.3/dojo/dojo.js"></script>. Details are here: http://dojotoolkit.org/download/. Be sure to put this before your require scripting.
Add a link to a Dijit theme style sheet (CSS file) in your page, otherwise none of the widgets will display correctly. e.g. <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/dojo/1.8.3/dijit/themes/claro/claro.css"/>
Add a class attribute on the body element describing which theme you want to use. e.g. <body class="claro">.
Only when you've done all those three things will it have a chance of working. There may be other problems too, but they're the fundamental three.
I am messing around with JavaScript experimenting to get a feel for it and have already hit a problem. Here is my html code:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" href="styles.css">
<script type="text/javascript" src="testing.js"></script>
</head>
<body onload="writeLine()">
</body>
</html>
Here is the JavaScript testing.js:
function writeLine()
{
document.write("Hello World!")
}
Here is the style sheet styles.css:
html, body {
background-color: red;
}
So a very simple example, but I may have chose an awkward example, using on-load in a body tag. So the code above loads and runs the function, but the style sheet does nothing, unless I remove the script tags in the head. I have tried putting the script tags everywhere else, but nothing works. I have researched on-line how to properly link to JavaScript files, and have no found no clear solution, can anyone point out my error?
I have used JavaScript before, but I want a clear understanding from the beginning before I use it any longer
You cannot use document.write after the document is closed (which it will be when onload fires) without destroying the existing document (including links to stylesheets).
Instead, use DOM manipulation, which is covered by chapters 8 and 9 of the W3C JavaScript Core Skills.
Your problem is with the document.write() called in a wrong moment*. This method prints given text at current place in the page as was intended to work while the page still loads. Because you are calling it when the whole page was loaded, the results are unexpected (undefined?)
Instead you should manipulate the dom tree directly:
function writeLine() {
var text = document.createTextNode("Hello World!");
document.body.appendChild(text);
}
Actually in Opera browser I see red background for few milliseconds and then it goes back to white. Try commenting out document.write() - the background is as expected. Moreover you should include <script> tag at the end of body, but this won't solve your problem.
* to be honest, there is no good moment for calling document.write(), avoid it
In your particular example it doesn't matter where the script tag is added as the document.write command executes after the content is rendered, overwriting the existing content.
If you add an alert before overwriting the content you can see your page is red before it gets overwritten with Hello World.
I'm having some problems with getting one of my site pages with IE8. It works fine in IE9, Safari (both PC & Mac) & Firefox (Mac). I'm using a find(tag1).html(tag1) call sequence to do a title substitution, but I get the following error in IE8 when I debug it in the IE script debugger, and this in the html(tag2) function:
Unexpected call to method or property access
The find(tag1) function seems to return the enclosing object (i.e. #sidebar), rather than the nested object #sidebarheader, and this causes problems when later making the html(tag2) call.
I've created a representative test case as follows:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JQuery .find() test case</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.js"></script>
<script type="text/javascript">
function UpdateHeader() {
$('#sidebar').find('header').html("New Title"); // IE8, nesting div's in the find fct. will not discover the child div
}
document.ready = UpdateHeader;
</script>
</head>
<body>
<div style="height: 400px; width: 390px">
<div id="jqm-home">
<div id="page">
<div id="sidebar">
<div id="sidebarheader">
<header>Old Title</header>
</div>
</div>
</div>
<p onclick="UpdateHeader();">Click to update title</p>
</div>
</div>
</body>
</html>
And here is the jsFiddle test case:
http://jsfiddle.net/bnmcK/21/
Has anybody a suggestion on how to get this to work in IE8?
In order to support the new HTML 5 elements in older versions of IE (8 and below), there's a handy trick, which involves creating a dummy element before running your script.
So, simply calling document.createElement('header'); in your page will solve the problem, see here.
For the full explanation, this post does a nice job of providing an explanation.
Also, html5shiv is a project that solves this problem for other elements too.
<header> is a HTML5 tag, which IE8 doesn't know about (IE9 however, supports this tag). Since you're declaring XHTML 1.0 transitional, I'd suggest using a <h1> tag instead, which will work just fine in IE8.
I'm not sure what I'm doing wrong here:
index.html
<?xml version="1.0" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "XHTML1-s.dtd" >
<html xmlns="http://www.w3.org/TR/1999/REC-html-in-xml" xml:lang="en" lang="en" >
<head>
<script type="text/javascript" src="scripts/eventInit.js"></script>
</head>
<body>
<p id="javascriptWarning">This page will not work with JavaScript disabled.</p>
</body>
</html>
eventInit.js
window.onload = function () {
alert("check"); // works
var jsWarning = document.getElementById("javascriptWarning");
jsWarning.onclick = function () {
alert("hi"); // works
};
jsWarning.onload = function () {
alert("loaded"); // fails
};
}
And yet, nothing happens. What am I doing wrong? I've tried other events, like onmouseover and onload.
I'm doing this in Visual Studio, and intellisense isn't giving me options for setting any event handlers. Is that because I'm doing this wrong?
I have confirmed that JS is working on my setup; just putting alert("hi") in a script and including it does work.
It might be important to note that I'm doing this in JScript, since I'm using Visual Studio 2010, so perhaps event handling is different?
Updated to remove '-' from the ID name, but it still doesn't work.
Updated added the window.onload block. Now onclick works, but onload doesn't.
You are trying to set a load event on a paragraph. Only objects which load external data (window, frame, iframe, img, script, etc) have a load event.
Some JS libraries implement an available event (such as YUI) — but you know the paragraph is available, since you're setting an event on it, and you couldn't do that if it was unavailable.
maybe you forgot to have the code block inside a
window.onload = function() {
// btn click code here
}
You have to wait for the document to be parsed before you can go looking for elements by "id" value. Put your event handling setup into an "onload" function on the window object.
The browser won't fire an "onload" event on your <p> tag. You won't need that anyway if you do your work in the "onload" handler for the window as a whole.
[soapbox] Use a framework.
The script is executed before the desired element exists. Additionally, I don't think, p has an onload-Event. Windows, frames and images, yes, but paragraphs?
You should use <body onload="init();"> or window.onload=function(){ … } or a library function, if you use a library. Example:
index.html
<?xml version="1.0" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "XHTML1-s.dtd" >
<html xmlns="http://www.w3.org/TR/1999/REC-html-in-xml" xml:lang="en" lang="en" >
<head>
<script type="text/javascript" src="scripts/eventInit.js"></script>
</head>
<body>
<p id="javascriptWarning">This page will not work with JavaScript disabled.</p>
</body>
</html>
scripts/eventInit.js
window.onload=function(){
alert('JS is working!');}
Edit: Okay, I am very sure, p makes no use of an onload event handler. And it's no wonder, you don't need it. If you want to execute JS code just after the paragraph is finished, do this:
<p>
<!-- stuff -->
</p>
<script type="text/javascript">
/* stuff */
</script>
Instead of this:
jsWarning.onload = function () {
alert("loaded"); // fails
};
try this
if(jsWarning) alert("loaded");
I think someone above mentioned checking for the existence of the element. At this stage the element should be present but it does no harms to check for it.
I think you have to make sure your JavaScript is binding.
Is your javascript before or after your paragraph element, for some reason my brain is aiming towards that.
I would look into using something like jQuery, it will help.
using jQuery your code would be (with the relevant jQuery files included of course):
$(document).ready(function()
{
$("#javascript-warning").click(function(){
alert("HELLO");
});
});
I don't think hyphens are valid in class names when used in conjunction with JavaScript. Try an underscore instead.
onload is a window event.