ドキュメント

Tutorials:5 Quick jQuery Tips

From jQuery JavaScript Library

Jump to: navigation, search

Some quick, short, examples of what you can do with jQuery.

Original: http://pixelcarnage.net/articles/development/5-quick-jquery-tips/
Author: Rowan Lewis

Similar Tutorials: SelectorsAttributesTraversingManipulationCSS

jQuery is the best thing to happen to JavaScript since… well, ever! In this tutorial I’ll show you a few good examples of why jQuery is so darned good.

Contents

Mark External Links

Something which I like to do is to mark all outgoing links with a special symbol (?). To do this I start all internal links with a forward slash, for example: /articles/development/5-quick-jquery-tips.

JavaScript:

  $("a").not("[href^=/]").not("[href^=#]").append("<span class='External'>?</span>");

That selects all a elements, then excludes those whose href attributes start with “/” or “#”.

Alternatively, you could also use the following to get all links that don't contain "mysite" in the href attribute.

$("a:not([href*=mysite])").append("<span class='External'>?</span>");

Use Your Own Bullets

Sometimes you want to break away from the usual circle and square bullets and say, use an EM dash or even an image. There are two steps to this:

JavaScript:

 $("ul").addClass("Replaced");
 $("ul > li").prepend("‒ ");

This adds an extra class to each affected ul element, this means we can apply alternate styling to the list.

CSS:

 ul.Replaced {
   list-style : none;
 }

Switch A Stylesheet

Want to add a style switch so your viewers can change between say, a high contrast style and a print style? It’s very easy to do, what you’ll need is a set of links with unique IDs:

HTML:

 <!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" xml:lang="en" lang="en">
   <head>
     <title>jQuery Demo</title>
     <link rel="stylesheet" type="text/css" media="screen" href="Normal.css" />
   </head>
   <body>
     <h1>Choose A Style:</h1>
     <ul>
       <li><a id="StyleContrast" href="#">Contrast</a></li>
       <li><a id="StylePrint" href="#">Print</a></li>
       <li><a id="StyleNormal" href="#">Normal</a></li>
     </ul>
   </body>
 </html>

JavaScript:

 $("#StyleContrast").click(function() {
   $("link[media='screen']").attr("href", "Contrast.css");
 });
 
 $("#StylePrint").click(function() {
   $("link[media='screen']").attr("href", "Print.css");
 });
 
 $("#StyleNormal").click(function() {
   $("link[@media='screen']").attr("href", "Normal.css");
 });

It would also be a good idea to use a cookie function to store which stylesheet the viewer wants, but I’ll let you figure that out on your own.

“Type your search here…”

A small script, which populates a form-field with a default text as description. This text will clear if the input is in focus and repopulate if the focus is lost without any input.

HTML:

 <form action="#" method="post">
   <input id="SearchText" name="text" />
   <button>Search</button>
 </form>

JavaScript:


As this task may be used in different situations, it's a good idea to write a reusable function for it. The first parameter is a selector (in our case "#SearchText" but something like "input[@name=search]" might be usefull too), the second parameter is the default value of that input element (e.g. "Enter your search term here..").

 function populateElement(selector, defvalue) {
    $(selector).each(function() {
        if($.trim(this.value) == "") {
            this.value = defvalue;
        }
    });
  
    $(selector).focus(function() {
        if(this.value == defvalue) {
            this.value = "";
        }
    });
    
    $(selector).blur(function() {
        if($.trim(this.value) == "") {
            this.value = defvalue;
        }
    });
 }

In our special case the Javascript might look like this:

 populateElement('#SearchText', 'Enter your search term here..');

To prevent giving non-javascript users a hard time with deleting default values manually, we write the default-value with javascript, without using the value=".." attribute of <input>.

Alter The First Paragraph

Yeah, here we go, making up for IEs shortcomings again. So you want to alter the first paragraph after every header of your site? Perhaps you want to make the font a little larger? This is really simple to do:

JavaScript:

 $("h2 + p").addClass("Large");

CSS:

 p.Large {
   font-size : 1.1em;
 }

Bonus Tip

Yeah, here’s a quick bonus tip, which I wouldn’t have included if it wasn’t for someone complaining… Here’s how to specify JavaScript only for Internet Explorer:

JavaScript:

 if ($.browser.msie) {
   // Internet Explorer is a sadist.
 }