Best html questions in December 2011

Unable to set marginTop style with script using IE8, but works in grown-up people browsers

16 votes

I'm attempting to animate the slide-out of a menu with script. To do this, I need to animate the marginTop property of an element and increment it from -30px to 0px.

However, in IE8, the animation simply does nothing. I've traced this down to the fact that setting marginTop in script seems to have no effect. In Chrome and Firefox, this works fine.

Here's an example that will work with Chrome/Firefox, but not IE:

http://jsfiddle.net/rm58T/2/

Is this an IE bug, and if so, are there any workarounds for this behavior? Thanks!

Update:

Here's some screen shots of the bug.

In Chrome, my Fiddle looks like this (You can see the "Name of new menu" text, since we changed the margin with script)

enter image description here

In IE8/Vista, it looks like this. I can confirm in Developer Tools that topMargin is actually 0px as expected, however the elements were not re-drawn:

enter image description here

Another Update:

This bug repros (at least for me) on IE8 running on Windows 7, and also IE8 running on Windows 2008 Server. It does NOT repro for me on IE7 running on WinXP. I do not have any IE9 machines to test it.

Yet Another Update:

I found one potential work-around. If I set p.newmenu to position: absolute; instead of position: relative; then it works. However, in my case I'm hosting this entire thing in a popup menu and need this control to push out the bottom of the modal dialog, so absolutely positioning it is not an option. However, perhaps this knowledge can help in finding a workable solution. An example of this work around can be found here.

Would You Believe Another Update?:

I did find a workaround for now. If I use top: -30px; instead of a negative top margin, then everything works. top behaves a bit differently than a margin, though, and makes the UI not look quite as nice. In particular, when you use top: -30px, then you'll have 30px of whitespace under your element since relative positioning doesn't affect other page flow.

I'd greatly like to figure out why I can't use a negative top margin on IE like I can with other browsers, so I'm still hoping someone can provide an answer that will provide all the benefits of a negative top margin but also work with IE8.

The trigger for this behaviour is how IE8 handles the fieldset element.

You can work around it by setting the display for fieldset to inline (or inline-block).

div.modal.addmenu fieldset {
   display: inline;   
}

How do tell a browser not to offer to save an incorrect password?

14 votes

Often on a website, if I enter the wrong password by mistake, I get a page back that indicates the wrong credentials, but Chrome (Or whatever) prompts me with "Would you like to remember this password?"

Is there any way to hint to the browser that now is not the time to ask, so that it only prompts if the user enters a correct password?

You could use JQuery & Ajax to post the login form to the server and recieve a response back without ever reloading the page, thus avoiding this problem altogether.

EDIT

Something along the lines of this (untested):

<div id="error"></div>
<form id="loginForm" method="post">
  <input type="username" name="username" id="username">
  <input type="password" name="password" id="password">
  <input type="submit" value="Login">
</form>

<script>
  $(function(){
   $('#loginForm').submit(function(){
     // Ajax to check username/pass
    $.ajax({
      type: "POST"
    , url: "/login"
    , data: {
        username: $('#username').val()
      , password: $('#password').val()
      }
    , success: function(response) {
        if(response == 'OK'){
          $('#loginForm').submit()
        } else {
          $('#error').html('Invalid username or password')
        }
      }
   })
  })
</script>

Are repeated backgrounds in html more efficient if they are larger than 1px?

12 votes

If there is a one-dimensional background that is repeated on a certain dimension, is there any mentionable difference in performance if the image is e.g. 1px wide versus 10 or 20 pixels wide?

I assume you mean a two-dimensional background.

I can't imagine that there is any noticeable difference, on modern computers. However, because bandwidth is still at a premium, especially on mobile devices, I think you would be better off conserving bandwidth by repeating a 1px wide image instead of say 2 or 3 px wide.

UPDATE: We just ran a test, unscientifically, but certainly perceptually relevant, in which one page rendered a 10px green square over a 10,000,000px square div, and another page rendered a 1px green square over the same size div. All styles are set with CSS, both pages had no other content. The graphics were loaded locally. There was absolutely no perceptual difference in the rendering in either Safari 5 for Mac, or FireFox 8 for Mac. Still, it's possible that there could be performance issues on certain models of older (crappier) smart phones.

CSS "overflow" culls "background-color"

12 votes

I'm trying to style blocks of code for a website. The container div is set to overflow both vertically and horizontally. The problem is when it overflows horizontally, the zebra-striped background-color is culled. I tried it with a background image as well but it culls that too. Why is it doing that and how do I fix it?

Thanks.

Image: http://zero.robotrenegade.com/q3w/background-overflow.png

Webpage (scale your browser width down to see the problem): http://zero.robotrenegade.com/q3w/code.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="created" content="">
    <meta name="description" content="">
    <meta name="keywords" content="">
    <link rel="stylesheet" href="" type="text/css" media="all" title="Default styles" />
    <title></title>
    <!--[if IE]><script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            jQuery("pre code").html(function(index, html) {
                    return html.replace(/^(.*)$/mg, "<span class=\"line\">$1</span>")
            });
        });
    </script>
<style>
.codeblock {
    max-height: 25em;
    overflow: auto;
    margin: 1em;
    border: 1px solid #ccc;
    font-size: 1em;
    line-height: normal;
    border-radius: 8px;
    box-shadow: 0px 0px 4px rgba(0,0,0,0.25);
}
.codeblock h1, .codeblock p {
    font-size: 1em;
    margin: 0;
    padding: 0em 1em 0.5em 3.5em;
    line-height: 2em;
    background-color: #eee;
}
.codeblock pre {
    margin: 0;
    padding: 0;
    font-face: 'lucida console',monaco,courier,'courier new',monospace;
}
.codeblock pre code {
    counter-reset: line-numbering;
    margin: 0;
    padding: 0;
}
.codeblock pre code .line::before {
    content: counter(line-numbering);
    counter-increment: line-numbering;
    padding-right: 0.5em;
    width: 4.5em;
    text-align: right;
    color: #888;
    border-right: 1px dotted #888;
    display: inline-block;
    background-color: #eee;
}
.codeblock pre code .line {
    display: block;
    margin: 0 0 -1.2em 0;
    line-height: 1.5em;
}
.codeblock pre code .line:nth-child(odd) {
    background: #f2f5f9;
}
/*.codeblock pre code .line:hover {
    background: #4b95e5;
    color: #fff;
}*/
</style>

</head>
<body>

<div class="codeblock"><!--<h1>Hello, this is an optional header.</h1>-->
<pre><code>void idAF::Restore( idRestoreGame *savefile ) {
    savefile->ReadObject( reinterpret_cast<idClass *&>( self ) );
    savefile->ReadString( name );
    savefile->ReadBool( hasBindConstraints );
    savefile->ReadVec3( baseOrigin );
    savefile->ReadMat3( baseAxis );
    savefile->ReadInt( poseTime );
    savefile->ReadInt( restStartTime );
    savefile->ReadBool( isLoaded );
    savefile->ReadBool( isActive );

    animator = NULL;
    modifiedAnim = 0;

    if ( self ) {
        SetAnimator( self->GetAnimator() );
        Load( self, name );
        if ( hasBindConstraints ) {
            AddBindConstraints();
        }
    }

    savefile->ReadStaticObject( physicsObj );

    if ( self ) {
        if ( isActive ) {
            // clear all animations
            animator->ClearAllAnims( gameLocal.time, 0 );
            animator->ClearAllJoints();

            // switch to articulated figure physics
            self->RestorePhysics( &physicsObj );
            physicsObj.EnableClip();
        }
        UpdateAnimation();
    }
}</code></pre>
<!-- <p>This is an optional footer, goodbye!</p> -->
</div>

</body>
</html>

Try float:left on the .codeblock pre. Works in Firefox.

<pre> fits itself inside the .codeblock container like there was no more room. float makes your <pre> element wide just enough to fit its content.

UPDATE

.codeblock pre {
    float: left;
    min-width: 100%;}

Works in Firefox, Opera, IE9 and WebKit

As far as I understand, it elements inside a container with overflow:auto fit themselves inside the area that's visible by default. Those elements' width:100% is only as wide as the outer container. In this example inside of the inner container you have a code tag that doesn't break lines so the text goes outside the inner container and makes the outer container show scrolls. To avoid that, you need the inner container to fit its content hence float:left.

But, as you cleverly noticed (and I didn't), this way it won't expand if the outer container is wider than the code so to avoid that you need to put min-width:100% to make the inner container use at least all the visible space inside the outer container.

How can I start out with web development using Perl?

11 votes

I want to be able to create web front-ends to my Perl programs. I have a lot of experience with Perl, and I have converted most of my code to Modern Perl paradigms championed by Chromatic. I have ZERO experience writing web pages though. (The occasional Word save-as-web-page notwithstanding).

I believe that I know which tools to start with, I am simply having difficulty with their beginning documentation and in which order to learn the tools.

  • Perl: I am all set here.

  • Dancer: I have created a site but I am very lost and the cpan docs simply confuse me further. I have no idea how to integrate these sites with Apache instead of using the mini server that comes with Dancer.

  • Template Toolkit: This one seems the most straight forward and I have the O'Reilly book. Seems like an awfully big book for something that seems easy, so I know I am missing something.

  • HTML: How much should I learn? What is the best learning path?

Ultimately, what would be nice is a complete 'Building Modern Websites with Perl from the Ground Up' tutorial, book, video series, or web site.

Please, where do I start?

You need to first decide what you are trying to do. Are you trying to write a dynamic site, generating web pages whose content vary depending on requests or are you trying to make building a static web site easier?

Either way, you should learn HTML on its own, and write some static web pages by hand. Then, realize that you can use Template::Toolkit's ttree to factor out common parts (header, footer, sidebar etc) and build a static site with uniform appearance.

The second step would be to use Perl to generate some dynamic pages. Learn CGI first to understand the basics, see also RFC 3875.

Also, look into HTTP and understand how web servers work.

Dancer is my favorite web application framework of the moment. By the time you have worked on the earlier steps, it will be somewhat obvious what Dancer does for you.

You need to first be able to separate actually separate concepts in your mind.

How to target a braille / screen-reader via CSS

11 votes

I use a webfont to display some icons on a website. This is fantastic because they scale, and i can print them if i want to... But the problem is that blind people see them as normal letters or characters. The following example returns me a nice Icon + text.

<span>i</span> Info
<span>t</span> Contact
etc...

A blind person will just read: iInfo, tContact etc...

Is it possible somehow to target only braille- & screen-readers with CSS?

I found this on the w3 website, but I'm not sure if the work in real live: http://www.w3.org/TR/CSS2/media.html#media-types

Does anyone have any experience with this?

------update-----

:before & :after -> Some screen-readers such as VoiceOver for MacOS do read the "content" part out loud. I have tested this by my self.

@media braille, speech -> Seams not to have a influence on VoiceOver. It reads whats visible on the screen (tested with safari & chrome)

speak: none; -> has no influence at all on VoiceOver or NVDA ( https://twitter.com/#!/jcsteh/status/143848614979055616 )

I think there is no "ultimate solution" to this. But you can use the abbr-tag to describe the use of your font-char, therefore most screen-readers will read-out the title-param of abbr and the user gets the meaning of the 'icon-character'.

I'm not 100% sure, but as it seams NVDA, JAWS and VoiceOver for iOS this works — on Mac OS X (unfortunately) not

Example:

<abbr title="Attachment Icon">A</abbr>

Best way to do curved shadows

10 votes

For something like this:

box

What would be the most effective way to do this? Best to do an image, or is there a way to achieve this with CSS without a bunch of hacks/extra markup that I dont know about?

Also the shadow only has to work in IE9, FF, and Chrome

You would do so using pseudo-elements and the box-shadow property. I have done up an example for you here: http://jsfiddle.net/sl1dr/NWnXw/

This works in IE9 and up.

/* Shadow */

.shadow {
    box-shadow: 0 1px 5px hsla(0,0%,0%,.25),
                inset 0 0 50px hsla(0,0%,0%,.05);
    position: relative;
}
.shadow:after,
.shadow:before {
    bottom: 7px;
    box-shadow: 0 10px 15px hsla(0,0%,0%,.25);
    content: '';
    height: 50%;
    left: 7px;
    max-width: 300px;
    position: absolute;
    right: 7px;
    z-index: -1;
    -webkit-transform: skew(-15deg) rotate(-8deg);
       -moz-transform: skew(-15deg) rotate(-6deg);
        -ms-transform: skew(-15deg) rotate(-6deg);
         -o-transform: skew(-15deg) rotate(-6deg);
            transform: skew(-15deg) rotate(-6deg);
}
.shadow:after {
    -webkit-transform: skew(15deg) rotate(8deg);
       -moz-transform: skew(15deg) rotate(6deg);
        -ms-transform: skew(15deg) rotate(6deg);
         -o-transform: skew(15deg) rotate(6deg);
            transform: skew(15deg) rotate(6deg);
}

Reasons for not using CSS to visually rearrange order of HTML elements

10 votes

We're having a bit of a discussion in the office at the moment about using CSS to visually re-order elements on the page.

On a very basic level, a member of our team wants to structure the HTML like this (this request is based solely on a design perspective)

<div class="secondary-content">
    <h2>Secondary content heading</h2>
    <p>This is the secondary content</p>
</div>
<div class="main-content">
    <h1>Main heading</h1>
    <p>This is the main content</p>
</div>

and then use CSS to visually place the main-content div before the secondary-content one.

Now, I'm not asking for help on how we would technically achieve this, but more I'm looking for evidence to back up the argument that we shouldn't do it at all.

As a front-end dev, my intial concerns are around accessibility

  1. Screen readers/assistive technologies will hit the secondary-content first. To me, that's akin to opening a book, starting at chapter 4 and then going back and reading chapters 1, 2, 3, 5, 6 etc
  2. The heading structure of the page will be disjointed (H2 before H1 etc)
  3. If there is any content in secondary-content which requires info from main-content in order to be understood, it will be confusing for users with CSS off/assistive technologies etc

However, the real hot button for people in the business is Google/SEO. Therefore, does anyone know any good arguments/articles as to why writing the HTML in an ill-structured way would negatively impact our SEO?

[Would] writing the HTML in an ill-structured way would negatively impact our SEO?

Almost definitely. While the precise nature of search ranking algorithms is a jealously guarded industry secret, and each company is different, everyone looks unfavorably on differences between content presented to search engines versus that presented to users.

Here's what Google's Webmaster Guidelines say:

  • Create a useful, information-rich site, and write pages that clearly and accurately describe your content. [Pages whose content obfuscates the actual visual ordering are not clearly and accurately describing their content.]

  • Make a site with a clear hierarchy and text links. [Putting a <h2> before a <h1> violates a hierarchy.]

  • Use a text browser such as Lynx to examine your site, because most search engine spiders see your site much as Lynx would. [Someone using a text browser would certainly be confused by bizarre content reordering schemes.]

So, in short, you're meddling with the "clear hierarchy" that search engines are trying to index. That's clearly not desirable.

To answer your more general question:

I'm looking for evidence to back up the argument that we shouldn't do it at all.

Fundamentally, HTML documents are just that: documents, meant for conveying semantic information through their structure.

Attempting to subvert this natural ordering isn't strictly verboten, but it often suggests that you didn't write the markup correctly, and it always leads to unexpected flows. For example,

  • In a book, do you expect chapter 7 to come before chapter 6?
  • In a newspaper article, do you expect the body to come before the headline?
  • In a movie, do you expect the closing credits to come before the title card?

You can see why, structurally, it would be ill-advised to reorder elements in this way. A document has a natural shape; distorting it makes it harder to understand.

There may be compelling aesthetic or artistic reasons to change the form of semantic vehicles like documents (e.g., a movie like Memento which exploits this for deliberate effect), but these are usually well thought-out, and not done trivially.

And you'd be hard-pressed to make an equivalence between a movie, which is designed to entertain, and an HTML document, which is designed to inform.

Style text inside textarea like Facebook does

10 votes

I try to achieve something like the Facebook does when you type @<NAME_OF_A_FRIEND> in a reply. After you choose a friend, the name of that friend is highlighted with a blueish background, so you know it's a separate entity in that text.

I've "inspect element"-ed that textarea and there is no div placed on top of the textarea.

Can anyone give me a clue about how that is done ?

enter image description here

See this example here. I used only CSS and HTML... The JS is very more complex for now. I don't know exactly what you expect.

HTML:

<div id="textback">
    <div id="backmodel"></div>
</div>
<textarea id="textarea">Hey Nicolae, it is just a test!</textarea>

CSS:

#textarea {
    background: transparent;
    border: 1px #ddd solid;
    position: absolute;
    top: 5px;
    left: 5px;
    width: 400px;
    height: 120px;
    font: 9pt Consolas;
}

#backmodel {
    position: absolute;
    top: 7px;
    left: 32px;
    background-color: #D8DFEA;
    width: 53px;
    height: 9pt;
}

hide line beginning and end text separators

9 votes

two solutions below: one with pure css, the second with jQuery, allowing any kind of symbol/image to be a separator

pre: Fairly hard to formulate and find such questions/solutions so I am sorry if duplicating.

I have a multi-line, justified block with random(not entirely) text hyperlink elements (tags/categories/etc) without fixed width separated by "|" symbol and spaces around. Looks pretty much like a tag cloud but with a fixed font-weight, size and other formatting, can contain more than one word in a hyperlink element. The problem rises when a separator is placed just before the end of the line or at the beginning of the line, actually, it happens always one way or another as I set nowrap to link elements, so this looks really ugly. Seeking for a solution to remove separators in the beginning and end of the lines.

For better understanding I will try to draw an example here.

C++ | PHP | CSS | ASP |
JavaScript | jQuery
| HTML 5 | StackOverflow

Something like that, of course, with justification and much more lines in a row. And another drawing of what I want to achieve.

C++ | PHP | CSS | ASP
JavaScript | jQuery
HTML 5 | StackOverflow

So fixed number of elements in a line is not an option, fixed width is also not an option.

The only solution I came up with is to set font to monospace and to count symbols and print pragmatically line-by-line with server-side scripting, the downside, of course, is the monospace fonts. Seeking for a better solution like pure html/css (would be perfect), JavaScript/jQuery formatting after output.

Thank you in advance!

EDIT: answering to a comment below, markup can be anything you wish, basically something like:

<div><a href="#">tag 1</a> | <a href="#">tag 2</a> | <a href="#">tag 3</a></div>

Here's an idea: http://jsfiddle.net/WyeSz/
(note that the jsfiddle demo uses a CSS reset, you may need a little more CSS than this to reset list styles, etc.)

Basically, you set border-left on the list items, then position the entire list -1px to the left within a container that has overflow:hidden, which cuts off the left borders.

<div>
    <ul>
        <li>C++</li>
        <li>PHP</li>
        <li>CSS</li>
        <li>ASP</li>
        <li>JavaScript</li>
        <li>jQuery</li>
        <li>HTML 5</li>
        <li>StackOverflow</li>
    </ul>
</div>
ul {
    width:200px;  
    margin-left:-1px;/* hide the left borders */
}
li {
    float:left;   
    padding:2px 10px;
    border-left:1px solid #000;
}
div {
   overflow:hidden;/* hide the left borders */  
}

difficult HTML, JavaScript, CSS grid page

8 votes

FYI, This is a simplified/generic example of what I'm working on. I'm just looking for the HTML, JavaScript, and/or CSS that can make this work. I'd prefer that this can be done without any javascript library. Also, the page will be built based on data loaded from a database. This only needs to work in newer IE/Firefox browsers.

I need to create a web page that has a grid of fixed size "cells" on it, each cell will be 150 pixels by 150 pixels. Here is sample 6x3 grid, but my grids will vary in size (4x10 or 3x5, etc. as per the database data):

-------------------------------------
|     |     |     |     |     |     |
|     |     |     |     |     |     |
|     |     |     |     |     |     |
-------------------------------------
|     |     |     |     |     |     |
|     |     |     |     |     |     |       6x3 grid of "cells"
|     |     |     |     |     |     |
-------------------------------------
|     |     |     |     |     |     |
|     |     |     |     |     |     |
|     |     |     |     |     |     |
-------------------------------------

each of these cells will need the following:

1) contain a "main" image that is 150 pixels by 150 pixels. This image will need to be changed in the browser, hopefully using CSS sprites if possible. I'd like to stick all of these images into a single file and crop down to what is needed in each cell.

2) When the mouse is over a "Cell", an overlay of click-able images will display. In the sample below I use letters, but the images will not be letters, more like icons. These clicks need to be able to run a different per image javascript function (so a click on the "A" image will run function A, while a click on "F" will run function F, etc). Images will be dependent on database info, so for different cells, some will be included and other not. Their position within the cell will always be fixed and controlled. Here is what a single cell might look with the images (letters) over top:

---------
|A  B  C|
|D  E  F|     a single cell where all overlay images appear
|G  H  I|
---------

---------
|A     C|
|   E   |     a single cell where only some overlay images appear
|G      |
---------

3) free text wrapping and centered within the cell. It would be best if this free text was above the main image #1 and below the click-able images #2, but if it was on top of everything than that would be OK too. There will be a reasonable length limit on this text, so scrolling beyond the 150px x 150px should not be an issue, but it will need to wrap.

For the record, this is not homework! and HTML/javascript/CSS is certainly not my strength. I have been working at this for a while and have seen/worked with many examples of how to do various components of this. I've yet to find anything that can work when everything id put together.

Personally I think tables are the devil, so here is something more like what I would do that uses floated divs:

http://jsfiddle.net/gbcd6/11/

You could easily swap out the text content for images, or add background images through CSS, as well as call separate JS functions based on the one-nine class each "control" div has.

EDIT:

Here is the most current version of the solution, which does include an actual table rather than using display: table-cell, as well as additional example markup for images and wrapping, and a basic Javascript example. This was done to fix an issue with older browser support, and to meet KM's requirements. Though the overall structure is still pretty much the same as the original fiddle.

how to break the long word in html?

8 votes

I'm creating list dynamically in javascript. I want to break the long word in as dot dot dot(.....). For example, if the word is "Software life cycle development" I want to change it as "Software life cycl....".

And I used "WORD-BREAK:BREAK-ALL;white-space:normal;" My current output is:

Software life cycle development.

Can anyone tell, how to fix this? thanks in advance.

  var parent = document.getElementById('searchlistview');
var listItem = document.createElement('li');
listItem.setAttribute('id', 'listitem_' + listId);
listItem.setAttribute('data-icon', 'false');
listItem.innerHTML = "<img src=" + imagesrc + " class='ui-li-icon ui-li-has-icon'></img>
<a target='_black' data-role='button' href='#' id=" + listId + " name= " + url + " data-theme ='c' rel='external' 
data-inline='true' style='margin-left:0em; WORD-BREAK:BREAK-ALL;white-space:normal; ' >" + searchName + "<p style='margin-top:1px;margin-left:1px;'>
File size: " + fileSize + "</p></a>";
parent.appendChild(listItem);

You can try this css

text-overflow:ellipsis;

It would put ... when the text overflow. see this page for your reference.

Dynamically adjusting two outside columns to the variable width of the center column

7 votes

I would consider myself to be an intermediate/advanced CSS/HTML coder but I'm stumped on how to do the following scenario.. I'm starting to think it is impossible but I really want to believe it is..

Let's say the wrapper width is 1000px.

Within it is three columns. The two outside columns are the same width, this width is decided by the center column. The center column is the only one with content, just one line of text with 30px of padding on either side. So if the line of content is 100px with padding, than the other two columns would be (1000-100)/2 each..

Is there a dynamic way to have the two outside columns adjust to the varying width of the center column that is defined by its varying contents, one line of text?

Graphic of what I am trying to accomplish:

http://i.stack.imgur.com/cMuBP.png

Good 'ole tables to the rescue:

http://jsfiddle.net/hgwdT/

Actually I think tables are the devil, but this works as you described. And so here it is using display: table-cell on the child divs, so it is functionally the same using nicer markup:

http://jsfiddle.net/XXXdB/

The center element can indeed have a dynamic width; to prevent the content from being squished, I simply added a white-space: nowrap to the p containing the text.

I also confirmed that this solution works in IE8 and FF, in addition to Chrome.

jQuery simple autocomplete implementation

4 votes

I've made a simple implementation of an autocomplete which would call ajax and load a list of matches. Here's the JSfiddle

http://jsfiddle.net/83hJw/

This of course only shows an alert saying "OK" when the timer times out

You'll notice that it resets the timeout to give you a chance to finish entering what you want, ie if you pause for 0.3 seconds when typing, it will then run the search, so as not to request too many times to the server

I've also got it to only run if the number of characters are above 4 characters too

Put simply, I'm wanting to know if there is a better way of doing this in jQuery?

Not sure about a better method, although I have noticed a flaw in your code. If I enter 4 characters then hit backspace before the time out, you'll still get the timeout running. You need to move the clearTimeout outside of the if statement in the keyup. From what everyone else above has said, it would appear the jQuery UI autocomplete has what you need with the delay feature, but you seem to have dismissed it?

EDIT

It also has the minLength option so you can specify 4 for that, and it will work exactly as you want

Website Join Form - Location Geo Co-Ordinates

4 votes

I have a website with a join form that asks you for your country and then city. When you type your city it sends AJAX calls back to a MySQL DB I have and this returns 10 possible results in a div under the input that you can select from or type further for a more refined return.

enter image description here

This works fine for one country (I purchased this DB) but I need to expand it for the entire world. I can purchase a DB for the world (country, city, suburb, postcode, geo co-ordinates) but its not cheap so I wanted to ask.

  1. Is there a way to do the same thing using Google Maps, Yahoo or Bing? Can I have users enter a country city location and have the GEO CO-Ords returned? Is it possible to do this with the AJAX keyup event returning possibilities?

  2. How to other people/sites go about this.

Note: I should also explain why I need this. The site is for online dating and I need to do radius searches. Eg: search for other members within 10KM or 20KM from where I am so I need GEO CO-Ords for each member.

Any advice would be greatly appreciated.

I have used Geonames in my previous geo-based project, what I did was:

  1. Downloaded the free database from the site.
  2. Imported the country, city, admin area database.
  3. Created my own Ajax service and various functions based on the imported database.

To make a query quick enough for your auto-complete input form, you might want to reduce the data size of the cities table by eliminating less populated cities by using "cities1000.zip" (which stands for "all cities with a population > 1000). I used this solution and the search speed was at least 1000x times faster.

And a quick answer for your "radius searches", you can use these Reverse Geocoding Webservices from Geonames as well.

dynamic database driven website with html pages

3 votes

I have a small project about a dynamic database driven website which is users can post, comment, like,... on it.
and I was thinking about creating html pages instead of php pages.
for example after someone posts sth a php code will create a html page for that post and people can comment on it. while submitting a comment, an ajax call to a php page will save comment data to database and write that comment to the html file.
I thought it could be a good way to reduce server load. and have advantages for SEO.
Does this technique have a name? and Does it have any more advantages or disadvantages?
Thanks in advance

There's a flat-file blogging engine called Kure. It's an open-source project so feel free to check it out. "Flat file system" would be the closest thing to a name for this technique.

I have to agree with my SO colleagues here. Servers and even personal computers are, for the most part, more than capable to handling what you'r describing using a real database. Blogging engines such as Wordpress, are incredibly powerful and flexible and will save you a lot of hassle down the line.

That said, if you insist in creating your own flat-file system... more power to you. Good luck.