Best html questions in July 2011

Can search engine spiders see content I add using jQuery?

20 votes

I currently have something like this

<p class="test"></p>

<script type="text/javascript">
    $(document).ready(function() {
          $(".test").html("hey");
    });
</script>

Will search engines be able to spider the "hey" text? and if yes, what method can I use to prevent that.

Despite what is being stated here in other answers and totally contrary to Google's own FAQ, a Google employee named JohnMu answered a question recently in Google Groups about how the GoogleBot came to follow a non-existent URL. (The actual URL was contained within the jQuery code itself and the GoogleBot DID try to follow it.)

jQuery causing 404 errors in Google Webmaster Tools

Google Employee explains how JavaScript and jQuery are indexed

Apparently, Google does attempt to index your JavaScript.

Quote Google's JohnMu:

"I would also recommend not explicitly disallowing crawling of the jQuery file. While we generally wouldn't index it on its own, we may need to access it to generate good Instant Previews for your site."

JohnMu later in the same thread...

"Additionally, we're constantly working on improving processing of JavaScript for web-search in general, so if you use jQuery to pull in content, and the jQuery script is disallowed for Googlebot, then we would not be able to look at that at all."

Commonly used pixel sizes for webpages and their pros/cons

20 votes

What are the most commonly used pixel sizes (primarily widths) and what are there advantages and disadvantages?

How can I best find a happy medium to give a good experience to people with a wide variety of monitor sizes?

An answer with an explanation rather than just the size would be greatly appreciated.

the most grids use a width of 960px. (When the design has a fixed width). When you take a look at global statistics 1024 range resolutions are still the most common: http://gs.statcounter.com/#resolution-ww-monthly-201006-201106

Do not use 1000 width. (You have to count in the border width of the browser and the scrollbar, in certain browsers / OS they are larger then in others)

I don't think there is a ultimate resolution that's why you should check the statistics on the concerned webpage (if the page already exists), to decide what resolution is most appropriate. If you can't do this you can check stats for you target market on http://gs.statcounter.com/

Or even better use responsive webdesign: http://www.alistapart.com/articles/responsive-web-design/

Since max- and min-width attributes in CSS, you can target whatever resolution you want, if you have the time / budget for it of course.

is "<script type='text/javascript'>" incorrect?

15 votes

On aminutewithbrendan, brendan eich makes an off hand comment implying that serving scripts as

<script type='text/javascript'></script>

is not correct because "text/javascript" is not a valid MIME type and he states "application/javascript" is a valid MIME type.

I only care about serving HTML5 as the doctype.

  • Where are the MIME types for <script> defined in the html5 W3C specification ?
  • What is browser support like for "text/javascript" and "application/javascript" ?
  • Which should be used ? Alternatively should we just not set type at all?

Literal Quote from brendan: (1:48)

... or script type equals application/javascript or application/ecmascript, those are the official MIME types or either one of those made-up ones from HTML4 like text/javascript ...

Related:

The union of the related resources doesn't really answer all three questions.

Where are the MIME types for <script> defined in the html5 W3C specification ?

Nowhere, it has a list (which includes some experimental and deprecated ones) but states that you can use any MIME type you like. MIME types are defined by IANA and text/javascript is officially marked as obsolete in favour of application/javascript

What is browser support like for "text/javascript" and "application/javascript" ?

Not good enough. There are still plenty of browsers around that don't recognise the latter. (This is, however, only a problem with the type attribute, you can set the HTTP Content-Type header correctly without worrying).

Which should be used ? Alternatively should we just not set type at all?

Since you only care about HTML 5, just omit the type attribute entirely. It is optional and the default language is JavaScript.

Default CSS properties of HTML elements

14 votes

What is the best site to find the default CSS properties of HTML elements?

Many of the HTML elements come with some default CSS properties which can sometimes result in unknown/unwanted behaviour. For example Input boxes are displayed differently in different browsers. I'm looking for a place that covers the new CSS3 properties and the new HTML5 elements. I've seen in other (much older) questions (such as Browser's Default CSS) answers that suggest a solution of CSS reset. This solution is sometimes not wanted, often I would actually like to keep some of the basic properties (such as the highlighting of input boxes in Chrome). In other words: I don't want to get rid of things just because I don't know what they do.

So, Is there a site that can give me all this information (or perhaps most)?

It's different for each browser, so:

As suggested by @robertc, you can also look at the HTML5 Boilerplate stylesheet, which "normalizes the display of a lot of stuff without being a reset in the traditional sense". It also fixes quite a few bugs/inconsistencies.

Why serve 1x1 pixel GIF (web bugs) data at all?

13 votes

Many analytic and tracking tools are requesting 1x1 GIF image (web bug, invisible for the user) for cross-domain event storing/processing.

Why to serve this GIF image at all? Wouldn't it be more efficient to simply return some error code such as 503 Service Temporary Unavailable or empty file?

Update: To be more clear, I'm asking why to serve GIF image data when all information required has been already sent in request headers. The GIF image itself does not return any useful information.

Doug's answer is pretty comprehensive; I thought I'd add in an additional note (at the OP's request, off of my comment)

Doug's answer explains, in a comprehensive way, why 1x1 pixel beacons are used for the purpose they are used for; I thought I'd outline a potential alternative approach, which is to use HTTP Status Code 204, No Content, for a response, and not send an image body.

204 No Content

The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation. The response MAY include new or updated metainformation in the form of entity-headers, which if present SHOULD be associated with the requested variant.

Basically, the server receives the request, and decides to not send a body (in this case, to not send an image). But it replies with a code to inform the agent that this was a conscious decision; basically, its just a shorter way to respond affirmatively.

From Google's Page Speed documentation:

One popular way of recording page views in an asynchronous fashion is to include a JavaScript snippet at the bottom of the target page (or as an onload event handler), that notifies a logging server when a user loads the page. The most common way of doing this is to construct a request to the server for a "beacon", and encode all the data of interest as parameters in the URL for the beacon resource. To keep the HTTP response very small, a transparent 1x1-pixel image is a good candidate for a beacon request. A slightly more optimal beacon would use an HTTP 204 response ("no content") which is marginally smaller than a 1x1 GIF.

I've never tried it, but in theory it should serve the same purpose without requiring the gif itself to be transmitted, saving you 35 bytes, in the case of Google Analytics. (In the scheme of things, unless you're Google Analytics serving many trillions of hits per day, 35 bytes is really nothing.)

You can test it with this code:

var i = new Image(); 
i.src = "http://sharedcount.com/test/beacon.gif";

What I'm not sure about, since I haven't tested it, is if this results in any browser quirks, but it will definitely serve the same purposes as the 1x1 beacon. (For example, Chrome sends the request, but deems the request "Cancelled" in the Dev Tools, since no body was transferred back. But, the request definitely makes it to the server, since there are response headers.)

How do browsers detect GIF image sizes?

13 votes

I was noticing that a GIF was being displayed with padding in FireFox 5 and IE 8. When I viewed the image size via FireBug, I noticed that it was a few pixels larger than expected.

Expected height: 160px vs. actual height: 171px

When I opened the GIF in an image editor, the editor displayed the correct dimensions, however when I ran ImageMagick identify I received the following information:

newGif.gif GIF 200x160 200x171+0+5 PseudoClass 256c 30kb 

If I modified the geometry to 200x160+0+0 the image displayed as I expected it to in FireFox. FireFox and IE 8 seemed to be referencing the Image's page geometry rather than dimensions! Is my analysis correct and if so is this true for all image types or just GIF's?

Updated, I have included an image for your viewing pleasure! This image displays as 200 x 171 for me in FF, but is actually 200 x 160 when you download and view in a graphics program.

here is the image

Header of this GIF file does not correspond to it's body. enter image description here

Image dimensions are stored in 6th to 9th bytes and from the screen shot you can see that dimensions in the header are 00C8 x 00AB which is 200x171 but it's actual size is 200x160

So this image is not valid. There are no standardized behavior for parsing invalid gifs and that's why there is this inconsistency.

Most probably firefox preallocates place for images before they are fully downloaded, when an image is fully downloaded it is put into the center of preallocated space. and because preallocated space is 200x171 but the actual image is 200x160 you will see a border.

EDIT: After going through GIF format reference it appears that GIF does allow this. So the image is valid. So here's what's actually going on here: GIF format consists from several blocks. There is a header block and one or more(if the image is animated) image blocks (there could be other blocks as well, but they are not connected with the issue). Header block holds some information about the image, including it's width and height. However each image block has it's own width and height as well. So what happens with the image in question that it has the main image size as 200x171 but the single frame with the size 200x160. So most editing programs and libraries which doesn't support animated gifs will extract the first frame and display it with the size 200x160 the browsers and editors which do support animation should display it with the full size of 200x171.

PS Every image block has image top and image left position. It seems that by allowing frames to be smaller than canvas, and allowing to move frame's position on the canvas, GIF's developers tried to shave couple of bytes of the animated gif files. I wonder if any of the modern graphic editors take advantage of that... probably not... :)

  1. GIF format byte order

Why does this document.write iframe ads code completely break Internet Explorer?

12 votes

So, I'm trying to find an answer to why this problem is happening; I've fixed the problem, but I want to know why it happened.

TL;DR

Google-provided conversion tracking code that injected an iframe using document.write suddenly caused the page to cease to execute in all versions of Internet Explorer, but was remedied by injecting the same iframe using a non-document.write method.

The Story:

Doubleclick is an advertising network that provides a JavaScript snippet to track conversions from ads.

The snippet they give looks like this:

<SCRIPT language="JavaScript">
var axel = Math.random()+"";
var a = axel * 10000000000000;
document.write('<IFRAME SRC="https://fls.doubleclick.net/activityi;src=143;type=donat01;cat=indir4;ord=1;num='+ a + '?" WIDTH=10 HEIGHT=10 FRAMEBORDER=0></IFRAME>');
</SCRIPT>
<NOSCRIPT>
<IFRAME SRC="https://fls.doubleclick.net/activityi;src=143;type=donat01;cat=indir4;ord=1;num=1?"
WIDTH=1 HEIGHT=1 FRAMEBORDER=0></IFRAME>
</NOSCRIPT>

Now, I know that, for all sorts of reasons, document.write is hazardous and should be avoided. But, Google is giving me this code, so, I figured I could trust it.

It suddenly started breaking all of our pages for all users using Internet Explorer. As in, the page would stop rendering entirely once it hit the document.write. This was crazy: One of the largest third party advertisers on the internet had given me JavaScript that had LITERALLY broken my purchase pages for 25% of my traffic!

As triage, I quickly substituted in the same code using the injection technique found in Google Analytics:

var iframe = document.createElement('iframe');
iframe.src = //the URL;
iframe.width = 0;
iframe.height = 0;
iframe.frameborder = 0;
var ref = document.getElementsByTagName('script')[0];
ref.parentNode.insertBefore(iframe, ref);

This resolved the problem, without actually explaining:

Why does a nearly empty iframe, injected using document.write, break Internet Explorer, but this method above doesn't?

I've solved the problem; it turns out that it had nothing to do with the contents of the <iframe>.

It turns out the page is served by a framework that began using a backend DOM parser that, for reasons likely related to the presence of </ within a <script> tag within the document.write, completely removes the </iframe> tag from the generated page, even though it preserves it in the backend. (It's probably trying to enforce ETAGO rules).

The reason I was able to reproduce it was because I was copying the generated document.write code, not the original code, and never noticed the missing </iframe>. (And my "functioning" document.write code didn't have the stripped out </iframe> tag, leading me to believe that the problem was the contents of the iframe.)

As a result, browsers parsed an unclosed <iframe> tag on the page, which Internet Explorer didn't know how to handle, and died part way through the parsing of the iframe (I'm still not totally sure why).

What is the difference between the hidden attribute (HTML5) and the display:none rule (CSS)?

12 votes

HTML5 has a new global attribute, hidden, which can be used to hide content.

<article hidden>
   <h2>Article #1</h2>
   <p>Lorem ipsum ...</p>
</article>

CSS has the display:none rule, which can also be used to hide content.

article { display:none; }

Visually, they are identical. What is the difference semantically? Computationally?

What guidelines should I consider on when to use one or the other?

TIA.

EDIT: Based on @newtron's responses (below), I did more searching. The hidden attribute was hotly contested last year and (apparently) barely made it into the HTML5 spec. Some argued it was redundant and had no purpose. From what I can tell, the final evaluation is this: If I'm targeting only web browsers, there is no difference. (One page even asserted that web browsers used display:none to implement the hidden attribute.) But if I'm considering accessibility (e.g., perhaps I expect my content to be read by screen-readers), then there is a difference. The CSS rule display:none might hide my content from web browsers, but a corresponding aria rule (e.g., aria-hidden="false") might try to read it. Thus, I now agree that @newtron's answer is correct, though perhaps (arguably) not as clear as I might like. Thanks @newtron for your help.

The key difference seems to be that hidden elements are always hidden regardless of the presentation:

The hidden attribute must not be used to hide content that could legitimately be shown in another presentation. For example, it is incorrect to use hidden to hide panels in a tabbed dialog, because the tabbed interface is merely a kind of overflow presentation — one could equally well just show all the form controls in one big page with a scrollbar. It is similarly incorrect to use this attribute to hide content just from one presentation — if something is marked hidden, it is hidden from all presentations, including, for instance, screen readers.

http://dev.w3.org/html5/spec/Overview.html#the-hidden-attribute

Since CSS can target different media/presentation types, display: none will be dependent on a given presentation. E.g. some elements might have display: none when viewed in a desktop browser, but not a mobile browser. Or, be hidden visually but still available to a screen-reader.

Google's +1 Button: How do they do it?

12 votes

Exploring Google's +1 Button, I found two things odd about the code they supply:

<script type="text/javascript" src="https://apis.google.com/js/plusone.js">
  {lang: 'en-GB'}
</script>

<g:plusone size="tall" href="http://www.google.com"></g:plusone>

So I have two questions:
First:       How is Google able to use the text between the script tags?
Second:  Is the syntax <g:plusone ... HTML valid? What's this called?

How is Google able to use the text between the script tags?

<script> elements are perfectly visible in the DOM:

<script type="text/javascript">//FIRST SCRIPT BLOCK</script>

<script type="text/javascript">
    var s= document.getElementsByTagName('script')[0];
    alert(s.textContent); // "//FIRST SCRIPT BLOCK"
</script>

Google's sneaky trick is to put content in a <script> that has an external src. In this case the src overrides the content inside the block and executes the external script instead, but the contents of the <script> element are still readable through the DOM even though they do nothing.

Is the syntax <g:plusone ... HTML valid? What's this called?

No. If they made their own doctype for HTML+plusone it could be valid that, but it doesn't satisfy validity for HTML, and it isn't even namespace-well-formed in an XHTML document, unless you add an extra xmlns:g for it too.

How to hide html source?

11 votes

The following website has both right click and view source disabled.

http://www.immihelp.com/visitor-visa/sponsor-documents.html

Can anyone shine some light on how this is possible?

The following website has both right click and view source disabled.

They fooled you. Just scroll down in view-source.

Furthermore, employing such tactics marks you as unprofessional. Don’t do it.

Inverse htmlentities / html_entity_decode

11 votes

Basically I want to turn a string like this:

<code> &lt;div&gt; blabla &lt;/div&gt; </code>

into this:

&lt;code&gt; <div> blabla </div> &lt;/code&gt;

How can I do it?


The use case (bc some people were curious):

A page like this with a list of allowed HTML tags and examples. For example, <code> is a allowed tag, and this would be the sample:

<code>&lt;?php echo "Hello World!"; ?&gt;</code>

I wanted a reverse function because there are many such tags with samples that I store them all into a array which I iterate in one loop, instead of handling each one individually...

My version using regular expressions:

$string = '<code> &lt;div&gt; blabla &lt;/div&gt; </code>';
$new_string = preg_replace(
    '/(.*?)(<.*?>|$)/se', 
    'html_entity_decode("$1").htmlentities("$2")', 
    $string
);

It tries to match every tag and textnode and then apply htmlentities and html_entity_decode respectively.

Purpose of HTML button?

9 votes

What was the intended purpose of the HTML <input type="button"> element, taking into account that Javascript appeared after HTML (hence making me doubt that JS was the intended purpose)?

Not sure but, if I remember correctly, <input type="button"> has been added with HTML4.0. Its first draft was from 1997, so 2 years later ECMAScript. So probably is has been introduced exactly for JS purposes.

Take a look to these links provided in comments by Felix Kling:

Javascript window object

8 votes

In Javascript, let's say we have a main page (main.html) which contains an <iframe> (iframe.html)

Now inside this iframe.html, if we need to refer to something on the main page (main.html) , can we not just specify window instead of parent.window

If the answer is we need to write parent.window, I wanted to understand is there not a single window object reference for all the iframes within a main page..

While I do understand document is specific to individual iframes, but window should be common to all..Isn't it...Please help me in understanding the concept...

Also is there something window.parent as well ? If yes, how does it differ from parent.window ?

The concept of window is tied to the document: There's one window per document, and one document per window.

That means <iframe> elements, which have their own document, also have their own window, just like a pop-up window or the main navigator window.

So, you'll indeed have to use window.parent to access the container of an <iframe> element, just like you have to use window.opener to access the owner of a pop-up window.

EDIT: Both window.parent and parent.window are valid expressions that return the same object. That's because the window object is the default context in scripting (unqualified names are parsed as members of window), and window objects have a window property that refers to themselves.

So, parent.window is evaluated as window.parent.window, which is the same object as window.parent.

That said, I do prefer using window.parent, to avoid the (minimal) overhead associated with the extra property access.

Is it possible for an AJAX request to be read before the response is complete?

8 votes

I have an ajax request that takes a while to complete, but the server does output some content along the way. If I load the request simply in the browser, I can see the page slowly loading and it can be stopped at any time. Is it possible to access an incomplete ajax request before the server closes the response?

The way to accomplish this is by listening on the readyState in the the xhr object. When readyState == 3 it means new content has arrived and you can access it. The technique is referred to as Comet.

Note however that different browsers behave differently here, IE will not allow you to access it See Here and webkit browsers (Chrome/Safari) buffer 2KB of data before making it available. After accounting for that though, you can then listen for the change then act on it.

Unfortunately, jQuery does not currently support this out of the box. You can get around this as noted in Bug #8327, where they basically fall back to polling on the readyState to see if it changes. They have plans to maybe do something about it in the future, Bug #9883, but don't hold your breath.

So finally, yes it is possible, no it is not easy.

CSS Venn Diagram mouse hover

7 votes

I'm trying to create a pure css Venn diagram like this Example of a Venn Diagram

Where the circle gets highlighted on mouse hover. But the problem is: using the border-radius property if I mouse over the corner of the circle (outside the circle) , it triggers hover as well.

for a demo see this jsfiddle link and hover over the red area

is there any CSS solution to avoid this or am I ganna have to calculate it using javascript?

EDIT: Thanks to all for the responses. I should have posted the browser information as well. I'm using Chrome 12 So far it seems this bug exists in chrome. I will update this page with any further findings.

I know it's possible to draw circles with border-radius:50%, but it really is a bit of a hack. And it doesn't work in IE8 or lower, without using even more hacks, like CSS3Pie.

So while I accept that you've produced a good-looking Venn diagram in your fiddle example, I don't think it's the best way to do this.

A much better solution would be to use a proper graphics library to draw the diagram using either Canvas or SVG.

For Canvas, you could try this library: http://www.canvasxpress.org/venn.html

For SVG, I would recommend Raphael, which will produce hover-able Venn diagrams in about four lines of code.

I know that neither Canvas nor SVG are supported by IE8, but then neither is border-radius, so I assume that isn't a criteria for you.

In any case, Raphael does actually work in all versions of IE, as it detects the browser and renders VML instead of SVG if it's running in IE. Canvas support can also be hacked into older IEs if you really need it.

JavaScript RegExp.test() returns false, even though it should return true

7 votes

The Prob: I get an AJAX response (JSON or plaintext with line breaks). Each item of the response should be checked via RegEx to find out whether it matches to user-definded patter or not.

Example:

Ajax Response (plain-text)

"Aldor
Aleph
Algae
Algo
Algol
Alma-0
Alphard
Altran"

User-pattern:

/^Alg/ig.test(responseItem)

RegExp Results should look like:

Aldor   // false
Aleph   // false
Algae   // true
Algo    // true
Algol   // true
Alma-0  // false
Alphard // false
Altran  // false

But each time i get different (and kinda weired) results... e.g. (/^alg/ig.test("Algo") => false)

My code:

HTML

...
<form>
  <input id="in" />
</form>
<div id="x">
  Aldor
  Aleph
  Algae
  Algo
  Algol
  Alma-0
  Alphard
  Altran
</div><button id="checker">check!</button>
...

JavaScript (jQuery 1.6.2)

$(function(){
    var $checker = $('#checker');

    $checker.click(function(ev){
        var inputFieldVal = $.trim($('#in').val());
        console.log(inputFieldVal); // Alg
        var regExpPattern = '^'+inputFieldVal,
            re = new RegExp(regExpPattern, 'igm');
        onsole.log(re); // /^Al/gim
        // Get text out of div#x
        var text = $('#x').text();
        // Trim and 'convert' to an array...
            text = $.trim(text).split('\n');
        console.log(text); // ["Aldor", "Aleph", "Algae", "Algo", "Algol", "Alma-0", "Alphard", "Altran"]

        for (var index=0, upper=text.length;index<upper;++index) {
            console.log(
               re.test(text[index]),
               text[index]
             );
        }
    });
})

Console OUTPUT:

/^Alg/ig => should match each item which starts with Alg

false "Aldor"
false "Aleph"
true "Algae"
false "Algo" //Why ? O.o
true "Algol"
false "Alma-0"
false "Alphard"
false "Altran"

/^Al/ig => should match each item because every item start with Al

true "Aldor"
false "Aleph" //Why ? O.o
true "Algae"
false "Algo" //Why ? O.o
true "Algol"
false "Alma-0" //Why ? O.o
true "Alphard"
false "Altran" //Why ? O.o

Any suggestions?

This is a common behavior that the the exec or test methods show when you deal with patterns that have the global g flag.

The RegExp object will keep track of the lastIndex where a match was found, and then on subsequent matches it will start from that lastIndex instead of starting from 0.

For example:

var re = /^a/g;
console.log(re.test("ab")); // true, lastIndex was 0
console.log(re.test("ab")); // false, lastIndex was 1

Remove the g flag from your pattern, since you are looking just for a single match (you are testing each line separately).

XML,XSLT transformation

5 votes

I have 2 strings, an XML string I constructed using Java's DOM interface, and an external XSL file I want to bind to that XML file. I tried using Java's transform methods, but without luck (Meaning I can't seem to find any solution for this on the web).

How do I take an XML file and an XSL file and make an html string out of them both?

What I'm trying to do is to inject an XML page into my JSP page.

Just to clarify: This is done in a servlet, not in javascript.

A little more information:

I create the xml during runtime as a string, the xsl file I've got is stored on the server, what I want to do is to display the xml altered by the xsl file to the user when he clicks on a certain link on the site, and I want to embed that inside an existing jsp page, (in order to maintain the standard look of the site.

This is what I've got so far:

String convertedXML = new String();
TransformerFactory factory1 = 
    TransformerFactory.newInstance();
Source xsl = new StreamSource("my.xsl");
Result result11 = null;
try {
    Templates template = factory1.newTemplates(xsl);
    Transformer transformer1 = template.newTransformer();
    Source xml = new StreamSource(xmlString);
    result11 = new StreamResult(convertedXML);
    transformer1.transform(xml, result11);
} catch(Exception e) {
   System.out.println("Not Good");
}

the last line before the catch throws the next error:

javax.xml.transform.TransformerException:
java.io.FileNotFoundException: at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.getOutputHandler(Unknown Source) at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transform(Unknown Source) at controllers.UserController.schedulePage(UserController.java:394)

Could you put your file into WEB-INF and try to use following:

String path = "/WEB-INF/my.xsl";
ServletContext context = getServletContext();
InputStream xslIs = context.getResourceAsStream(filename);
Source xsl = new StreamSource(xslIs);

jQuery.post() inside a jQuery.post()

5 votes

Imagine a website where the content is loaded via a menu with using jQuery .post() (or .get()).

Imagine that inside this dynamic loaded content should be another jQuery post to show some more things under the content

(all without navigating to a new file in the address bar)

Here is what i mean (but only the base frame...):

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<input type="text" name="n" id="n" placeholder="Search..." />
<button id="click1">Go</button>
<!-- the result of the search will be rendered inside this div -->
<br />
<div id="result" name="result"></div>

<script>
window.onload = (function(){
    /* attach a submit handler to the button */

    $("#click1").click(function(event) {
        $.ajax({
            url: 'test.php',
            type: 'POST',
            data: 'n: term',
              success: function(msg) {
                $( "#result" ).empty().append( msg );
              }
         });
    });
});
</script>

</body>
</html>

So, stop laughing, I know that the page only loads itself in the div and this is not working because of the same IDs... it´s not Inception here ;-)

But even if I link a completely new page to it with new IDs it is not working...

Is it possible to add a new jQuery AJAX inside an existing, already with jQuery AJAX loaded content?

I think yes, but I can´t find my mistake...

/EDIT

I think I need to give a bit more input:

test.php

<input type="text" name="n" id="n" placeholder="Search..." />
<button id="click1">Go</button>
<div id="result" name="result"></div>

<script>
window.onload = (function(){        
    $("#click1").click(function(event) {
        $.ajax({
            url: 'test2.php',
            type: 'POST',
            data: 'n: term',
              success: function(msg) {
                $( "#result" ).empty().append( msg );
              }
         });
    }); 
    $("#click2").click(function(event) {
        $.ajax({
            url: 'test3.php',
            type: 'POST',
            data: 'n2: term',
              success: function(msg) {
                $( "#result2" ).empty().append( msg );
              }
         });
    });
});
</script>

test2.php

<input type="text" name="n2" id="n2" placeholder="Search..." />
<button id="click2">Go</button>
<div id="result2" name="result2"></div>

test3.php

<?php
echo 'It´s working!';
?>

My final question: Why is it not working? Why does it not output "It´s working!" at the end?

You can put another post inside the success handler of the first post:

$("#click1").click(function(event) {
    $.ajax({
        url: 'test.php',
        type: 'POST',
        data: 'n: term',
          success: function(msg) {
            $( "#result" ).empty().append( msg );

            $.ajax({/* params here */});
          }
     });
});

How to show text outside input ONFOCUS?

4 votes

I have a form like this:

<form action="search.php" class='search' method='GET'>
<input 
    type="text/submit"
    class="home_search_area"
    value="Search"
    name="search" 
    onblur="if(value=='') value = 'Search'" 
    onfocus="if(value=='Search') value = ''"
 /></form>

Now my form hides word "Search" on focus. I want to show text "Press enter to start searching" outside textarea onfocus. Any ideas?

Thanks.

add an element under the input field:

<div id="tips"></div>

add to the onfocus event:

onfocus="if(value=='Search') value = ''; document.getElementById('tips').innerHTML = 'Press enter...'"

Dynamically change the height of an element to another

4 votes

Column A and B
Well here we have two columns A and B. The thing is column A generally contains more content so its height is more (in this case 126px) and column B has less content so it remains shorter (here 94px). Now I want to make the height of B = A, considering that height of column A might change dynamically by AJAX but to keep pace with column A, height of column B must also change.
<div id="A">filer text</div> | <div id="B">filler text2</div> Now may be by using jQuery or some js we can get the height of element with id #A and set it to #B but the problem lies when the content changes dynamically.

$("#a").css("height", $("#b").css("height") );

Which then could be put in the callback function of, say:

$.ajax({
  ...
  success:function(msg){
    // could be optimized by storing off of the comparision
    if( $("#a").height() > $("#b").height() ){
      $("#b").css("height", $("#a").css("height") );
    }
  }
});