HTML / CSS autonumber headings? - javascript

Is there a way (ideally easy) to make headings and sections autonumber in HTML/CSS? Perhaps a JS library?
Or is this something that is hard to do in HTML?
I'm looking at an application for a corporate wiki but we want to be able to use heading numbers like we always have in word processors.

Definitely possible using css counters - just make sure you watch out for browser compatibility...:
This will make h2 get 1., 2., h3 gets 1.1, 2.1, 2.2 etc...
<style>
body{counter-reset: section}
h2{counter-reset: sub-section}
h3{counter-reset: composite}
h4{counter-reset: detail}
h2:before{
counter-increment: section;
content: counter(section) " ";
}
h3:before{
counter-increment: sub-section;
content: counter(section) "." counter(sub-section) " ";
}
h4:before{
counter-increment: composite;
content: counter(section) "." counter(sub-section) "." counter(composite) " ";
}
h5:before{
counter-increment: detail;
content: counter(section) "." counter(sub-section) "." counter(composite) "." counter(detail) " ";
}
</style>
As lpfavreau says, it's the same as another question I believe.
Also note that using css will not change the heading (e.g. selected text will give you the heading without the numbers). This may or may not be desirable. lpfavreau's (accepted) answer will give you the jquery code to modify the heading text.
See MDN: Using CSS counters for details.
3rd Party Edit
I created an example with the css above

2016 update. Please see Stephen's answer below for a proper method in CSS. My answer made sense in 2009 when the browsers and libraries were different. We are now living in a whole new world and the method presented here is outdated. I'm leaving it for the poor souls that are still living in corporate microcosms made of IE7 and tears.
See this other question if you're wondering how to do it in CSS, the answer might be what you are looking for. But titel has a good proposition too, depending how your HTML document is made.
It should be noted that, as Triptych said in another comment, this is of interest only if it's for an internal tool where you have control over which browsers are used and using CSS is worth it because modifying the HTML would be hard for example. Support of this CSS feature is limited.
It would of course be easy to use something like jQuery to do the increment also. Something like this untested snippet:
$(document).ready(function() {
$('h1').each(function(index) {
$(this).html((index + 1) + '. ' + $(this).html());
});
});
Don't forget to include the jquery.js file in your document of course.

The simplest method would be Numbered Lists
<ol>
<li> Section
<ol>
<li>Nested one</li>
<li>Nested two</li>
</ol>
</li>
<li>Section</li>
<li>Section</li>
<li>Section</li>
<ol>
will be something like:
Section
I. Nested one
II. Nested two
Section
Section
Section

Could possibly be done either serverside or with JavaScript. Don't know about any premade scripts that does it though.
Impossible to do with HTML/CSS, at least - unless you manually add all numbers into your headings.

Lists do it, why not other elements? http://www.w3.org/TR/CSS2/generate.html#scope

<ol>
<li>Heading 1</li>
<li>Heading 2</li>
<li>Heading 3</li>
</ol>

It is possible to implement auto numbering using HTML itself using ordered lists, and nesting them if necessary. Below there is a link to a live example of this, example I found after a fast search on Google.
http://archive.corewebprogramming.com/Chapter2/Nested-Ordered-Lists.html
There is also an possibility to use Unordered Lists and CSS as shown in this example:
http://print.wordpress.com/2006/02/22/css-beautifully-numbered-lists/

Related

Using JQuery selectors and "this" for dynamic elements

I have a page with a ton of documents for a client who would like users to be able to click on each article/project listed on the page, and for a small details pane to open beneath it reveling the content.
I know this is fairly easy to do, particularly with JQuery, but I am not well-versed in the language and trying to take a stab at this kind of dynamic functionality. There are well over 50 documents, hence the reason for using "this" and trying to keep things dynamic rather than explicitly calling EACH of the 50 elements (and also bogging down load times).
Here is my HTML (I've only included ONE of the elements in the list)...
<ul class="paging" id="paging">
<li><a href="">Economics of Ethanol and Bio-butanol as Gasoline Blendstocks<br />
<strong>Categories:</strong> Oxygenated Fuels Issues, Bio-fuel Economics, Blendstock Valuation, Refining Economics, Refinery Modeling</a>
<ul style="background:#f8f8f8; width:500px; height:200px;"><li>Here is the text that should appear beneath woot</li></ul>
</li>
And here is my JQuery bit...
<script type="text/javascript">
$(document).ready(function() {
$('ul.paging > li > ul').hide();
$('ul.paging > li').click(function() {
$(this > ul).slideToggle();
});
});
</script>
My elements is being hidden correctly, so I'm assuming my selectors are ok? Anyhow, there's no working functionality with the roll-out. Any thoughts?
Thank you, all help is very appreciated! Like I said, very new to this. :) Thanks again!
The value of this is a DOM element. You need to use it as the base for jQuery's DOM traversal methods, like .children().
$(this).children("ul").slideToggle();
$(this > ul) should look like $('ul', this)
Or
$(this).find('ul').slideToggle();
The selector here is likely your problem:
$(this > ul).slideToggle();
You might best use this:
$(this).find('ul').slideToggle();
I would also suggest making CSS style for the ul's hidden by default, that way they wouldn't potentially flash on the screen before the document ready event.

jQuery to add a class to menu items?

I have the following menu items:
<ul>
<li class="static">
<a class="static menu-item" href="/mySites/AboutUs">About Us</a>
</li>
<li class="static">
<a class="static-menu-item" href="/mySite/Practices">Practices</a>
</li>
<li class="static">
<a class="static-meunu-item" href="/mySite/Sectors">Sectors</a>
</li>
</ul>
I cannot add specific background images to the menu items as they all have the same class. In order to achieve this it will be ideal if specific classes could be added for example:
<ul>
<li class="static">
<a class="static menu-item about-us" href="/mySites/AboutUs">About Us</a>
</li>
<li class="static">
<a class="static-menu-item practices" href="/mySite/Practices">Practices</a>
</li>
<li class="static">
<a class="static-meunu-item sectors" href="/mySite/Sectors">Sectors</a>
</li>
</ul>
In the above example highlighted in red are the classes that have been added. This will then allow me to add the specific background images to each menu item.
How can I achieve this using the .addClass() method in jQuery?
In this case, adding specific classes is overkill. I would simply use an href selector since that seems to be what you're basing your classes off of:
// *= indicates contains
$('a[href*="AboutUs"]').addClass("about-us");
$('a[href*="Practices"]').addClass("practices");
$('a[href*="Sectors"]').addClass("sectors");
If there are other anchors on the page with the same href's that you don't want to include, simply use the parent > child selector:
// *= indicates contains
$('.static > a[href*="AboutUs"]').addClass("about-us");
$('.static > a[href*="Practices"]').addClass("practices");
$('.static > a[href*="Sectors"]').addClass("sectors");
Here is a working jsFiddle to illustrate the solution.
You should be able to add a class by passing a callback function to the addClass function -
$("a").addClass(function() {
var newclassname = $(this).text().toLowerCase();
return newclassname.replace(/ /g,'-');
})
Demo - http://jsfiddle.net/aZEZN/
I personally find it overkill to do such things with Javascript.
Makes more sense doing it server side as it's been mentioned above.
Or...
CSS! You could use CSS3 pseudo classes to do this.
I have created an example here
To make this work in older browsers such as IE7, make sure you add Selectivizr to your head section
define your class like this;
.highlight { background:yellow; }
.highlight2 { background:yellow; }
.highlight3 { background:yellow; }
then add your class like this;
$(".about-us").addClass("highlight");
$(".practices").addClass("highlight2");
$(".sector").addClass("highlight3");
It's not necessarily overkill specifying individual classes for each list item. A class should be used (as opposed to an ID) when there is even a possibility to group multiple elements together (for scripting, styling). In your case, as this is a navigation menu, you might have multiple menus (such as a left-side pane side bar, a footer menu aswell). From my experience, I would specify each menu button as its own class in order to handle the group of links together (ie all links that directs the user to the About us page).
The most obvious benefit of this is that you will be able to handle the active links as a group vs. individually; just as you would have a hover color on these links, you might as well want the link to be bold when the user is on that specific page. Grouping the links together and handling this as a class would allow you to bold all the links if you have multiple menus.
To add to this, erimerturk had a good idea of specifying highlights or 'themes' within your styles. This is a good practice (although not for your case) when you want to specify a certain color scheme for your site. Specify your color, background color and highlights as classes and tag these classes to the required elements within your html directly. This is a huge boost for maintainability and scalability, so although I wouldn't say as far as saying it's good practice, it's certainly not bad practice as far as I'm concerned.
Overkill or not, sometimes we may just want to test out ideas quickly on the browser, or you might be working on nodejs. I have edited the link classes to static-menu-item.
var links = $("body").find("a.static-menu-item");
$.each(links, function(value) {
var items = $(this).attr('href').split("/");
$(this).addClass(items[items.length-1].toLowerCase() );
});
Working example

Changing the text of multiple links with JavaScript (onMouseOver)

I have multiple links, each embedded in its own list-item, like so:
<ul id="topLinks">
<li>Link 1</li>
...
<li>Link 4</li>
</ul>
What I would like done is, when the user is hovering over the link, dashes are added to the link text. For example, when the mouse rolls over "Link 1", it turns to "-Link 1-", and goes back to normal when the cursor is not over that link anymore - leaving the other links alone (until user rolls its cursor over each respective link).
I've tried writing a few scripts of my own for it, but Im still pretty new to JavaScript, so Im kind of lost. Oh, by the way, I apologize for not having a live example, Im working on my LocalHost at the moment...
In fact, you can use :after and :before CSS selectors, in combination with :hover: http://jsfiddle.net/pimvdb/p9Qfu/. It is more straightforward and faster than doing it in JavaScript.
li:hover:before {
content: "-";
}
li:hover:after {
content: "-";
}
If you're willing to do jQuery then this would work: http://jsfiddle.net/MrrZs/ If not, I can try something else for you.

How to create interactive tags in html file?

I don't know anything about programming, so I'm trying to find out where to start learning + how difficult my problem is. Since I don't have any programming knowledge, I'll try to describe my problem in natural language, hope that is OK.
I have the html file of the penal code (a type of law). It contains many different rules, that are in numbered paragraphs (§ 1, § 4, etc).
Now I want to look at the source code and manually “tag” the paragraphs according to specific criteria. For example all the paragraphs that concern the use of a weapon get the “weapon” tag, or that have a minimum sentencing of 1 year and higher get a “crime” tag, etc.
At the end I want to view an interactive html file in Firefox/Chrome, where I could for example click on a “crime” button, and all §§§ that were tagged with “crime” would appear in bold red, keeping the rest of the document intact. Ideally I would also be able to click on “weapon” and would only see the §§§ tagged with “weapon”, making the rest of the document disappear.
The function it's just for me, so it would only need to work on a Xubuntu 11.04 desktop with Firefox or Chrome. The original source file would be http://bundesrecht.juris.de/stgb/BJNR001270871.html. The code looks strange to me, is there a way to convert it into something more easily manually editable?
Any help would be greatly appreciated. Primarily I don't know where to start learning. Do I need to know HTML, jQuery, or a programming language like Python? Do I need to set up an Apache server on my PC? Perhaps because of my ignorance of programming, this seems like a not too complex function. Am I mistaken in the belief that an amateur could build something like thins maybe one month?
I think this is not very difficult to make, although the tagging process can be quite labour-intensive.
You don't need much programming skills, especially when you want to tag stuff manually. You probably only need basic HTML and CSS and some Javascript to pull this off.
What I would do is the following
Create a local copy of the HTML file (use Save As in your browser)
Manually tag each § by giving it the appropriate tag as a classname
Create a list of all available tags and let javascript filter out the § you'd like to see
Now Step 1 is pretty easy I guess, so I'll go right to Step 2. The paragraphs in the HTML file are formatted according to a certain pattern, e.g.:
<div class="jnnorm" id="BJNR001270871BJNE009802307" title="Einzelnorm">
<div class="jnheader">
<a name="BJNR001270871BJNE009802307"/>Nichtamtliches Inhaltsverzeichnis
<h3><span class="jnenbez">§ 31</span> <span class="jnentitel">Rücktritt vom Versuch der Beteiligung</span></h3>
</div>
<div class="jnhtml">
<div>
<div class="jurAbsatz">
(1) Nach § 30 wird nicht bestraft, wer freiwillig etc.
</div>
</div>
</div>
</div>
What you want to do now is add your tag to the <div> element with the class jnnorm. So the above example would become (if the tag weapon would be appropriate):
<div class="jnnorm weapon" id="BJNR001270871BJNE009802307" title="Einzelnorm">
You do that for each paragraph in the HTML. This will be pretty boring, but okay.
Now Step 3. First create a list of links of all the tags you've just created. How you create lists in html is explained here. Put this at the top of the HTML document. What you want to do with javascript is when you click on one of the links in your list that only the paragraphs with the given class are shown. This is most easily done with jQuery's click event and the show and hide methods.
Updated with jQuery example
Make a menu like this
<ul id="menu">
<li id="weapon">Weapons</li>
<li id="crime">Crime</li>
</ul>
And then use the following jQuery
<script>
$(document).ready(function(){
// When a <li> element inside an <ul> with the id "menu" is clicked, do the following
$('ul#menu li').click(function(){
// Get the id of the <li> element and append a '.' so we get the right name for the tag (class) we want to show
var tag = '.' + $(this).attr('id');
// Hide all elements of class 'jnnorm'
$('.jnnorm').hide();
// Show all elements with the class name of tag we want
$(tag).show();
});
});
</script>
Note: HTML classes are denoted as .classname in jQuery whereas HTML id's are denoted as #idname.
Good luck!
This could be done using purely HTML/CSS and Javascript, so not server would be needed. JQuery would make the javascript side easier.
Basic idea of how to do it:
Use CSS style classes for your "tags"
Have a button for each tag with an onclick handler that uses JQuery to highlight everything with that tag (or make everything else invisible)
The HTML source code actually looks nicely structured, though it could use a few more linebreaks for sub-paragraphs. Any good HTML/XML editor has an autoformat feature that handles this, though you could get any specific format you want using a programming language with convenient text-manipulation facilities, such as Perl, awk or Python.

Dynamically replacing simple DOM element with a template, processed with web-service's result values

M(model): HTML, V(view): CSS, C(Controller): JavaScript
Hi,
I'm maintaining a personal bookshelf (a list of books) in a simple static HTML document, ie:
<ul>
<li class="book">Kitting tips and tricks</li>
<li class="book">La Bonne Cuisine Of Madame E. Saint-Ange: The Essential Companion For Authentic French Cooking</li>
<li class="book">Don't Make Me Think: A Common Sense Approach to Web Usability, 2nd Edition</li>
</ul>
Ok, this is for the model part: just books titles entries (DB equivalent)
Now for presentational purposes, I would like to present it a bit differently... For example, I prefer showing the book's cover rather its title as simple text, eg:
<li class="book"><img alt="Kitting tips and tricks" src=""></li>
For this, I use a web-service (Google Books API) to fetch book's information, client-side(JSON):
$('.book').each(function(index, book){
$.getJSON("http://books.google.com/books/feeds/volumes?alt=json-in-script&callback=?",
{q: $(book).text()},
function(data, textStatus) {
// DOM manipulations: replacing book's title by its cover image
$(book).empty().html('<img alt="' + data.feed.entry[0].title.$t + '" src="' + (data.feed.entry[0].link[0].href) + '"/>');
}
);
})
The problem is DOM manipulations can rapidly becomes complex, for example, if I also want to add author, editor, reviews...
So my question is: is there a way to define a sort of template for the final rendering of the book, eg something like:
<li class="book"><img src="{cover}" alt="{title}"> by <address class="vcard"><span class="fn">{author}</span></address>...</li>
and processing it(client-side) with the web-service's result values?
It makes me think about XSLT here, but I'm really not sure about its implementation over javascript. Do you have another idea?
Thanks for your suggestions.
Have you looked at this StackOverflow question?
JQuery templating engines
I think a possible answer is in your code, namely the end of the query string: &callback=. Define a callback function to parse the returning JSON data and render your template.
As an aside, your "model" should not have "view" attributes, e.g. class names. Perhaps this is just an example and I'm being picky.

Categories

Resources