Simple jQuery Snippets to Spruce Up Your Website

Tuesday, May 17th, 2011

Matcha Design – Tuesday, May 17, 2011

The purpose of these tricks is to take existing, perfectly valid code, and add little touches to it. They all use jQuery, though could potentially be adapted. They’re meant to be called after the DOM has loaded, such as within $(function(){}); or $(document).ready(function() {}); if you prefer.

PDF Icons

$('a[href$=.pdf]').addClass('pdf');

Couple this with some CSS targeting a.pdf similar to the following

a.pdf {
    padding-right: 15px;
    background: url('pdf-icon.gif') no-repeat right;
}

…or…

a.pdf:after {
    content:url('pdf-icon.gif');
}

This will attach an icon to all your links that end in .pdf (customize the details to point to your icon and be the correct size, etc). Of course, you could use any file extension/icon combination to let users know what type of link they’re clicking on.

External Links

Using the selector

$('a[href^=http:],a[href^=https:]')
.not('[href^=http://www.example.com/],[href^=https://www.example.com/]')

you can target all the links on a page that go to a different domain. (Replace example.com with your own website address).

Once you have those links targeted, you can do a number of useful things with them. You can add an icon as with PDF links above, or make them open in a separate window using .attr(‘rel’, ‘external’) or direct users to a confirmation page warning them they’re about to leave your site

$('a[href^=http:],a[href^=https:]')
 .not('[href^=http://www.example.com/],[href^=https://www.example.com/]')
 .each(function(index, element) {
    $(element).attr('href', '/redirectwarning.php?target='
     + encodeURIComponent($(element).attr('href'));
});

Then external links will first redirect users to redirectwarning.php on your site, passing the original URL as the GET variable ‘target’. (In PHP, you would retrieve this value as $url = $_GET[“target”];)

You could also target specific domains to customize their links. For example, $(‘a[href^=http://www.youtube.com/watch]’) would target links to YouTube videos. You could use this to cause them to open in a lightbox for example.

Magic Links

This snippet will cause URLs, email addresses, and US/Canada phone numbers to be clickable links.

var email = /\b([A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4})\b/ig;
var phone = /\b([01]?[- .]?\(?[2-9]\d{2}\)?[- .]?\d{3}[- .]?\d{4})\b/g;
var url =
 /\b((?:https?):\/\/(?:-\.)?(?:[^\s\/?\.#-]+\.?)+(?:\/[^\s]*)?[A-Z0-9+&@#\/%=~_|])/ig;
var alink = /(<a [^>]*>.*?<\/a>)/i;
$('p').each(function() {
    var h = $(this).html();
    var alist = [];
    while(alink.test(h)) {
        var lnk = alink.exec(h)[0];
        h = h.replace(lnk, '<a' + alist.length + '>');
        alist.push(lnk);
    }
    h = h.replace(email, '<a href="mailto:$1">$1</a>');
    h = h.replace(phone, '<a href="tel:$1">$1</a>');
    h = h.replace(url, '<a href="$1">$1</a>');
    for(var i = 0; i < alist.length; i++) {
        h = h.replace('<a' + i + '>', alist[i]);
    }
    $(this).html(h);
});

Note that part of this code extracts the existing links and then replaces them afterward, to prevent messing them up with the regular expressions. If anything has been done “behind the scenes” on your paragraphs or children of your paragraphs, this code might cause a problem because it replaces the code. In particular, events that have been registered will not work. Therefore if you have any fancy stuff like that going on, I recommend you run this code first. You could also skip the link extraction/replacement if you use these regular expressions on user input that’s meant to be displayed, such as blog comments (which usually shouldn’t allow html tags to begin with), or on any code that you know for sure won’t have links in it. Bottom line – test it on your pages thoroughly before using it, to ensure it won’t break anything.

\

About Matcha Design
Matcha Design is a full-service creative agency specializing in web designprintidentitybrandinginterface designvideo productionstill photography and motion design. Using our passion for excellence, multi-cultural background, and award winning practices, we consistently provide high-quality, custom, innovative solutions to meet the diverse marketing needs of our clients. For more information, visit www.MatchaDesign.com.

About Matcha Design

Matcha Design is a full-service creative B2B agency with decades of experience executing its client’s visions. The award-winning company specializes in web design, logo design, branding, marketing campaign, print, UX/UI, video production, commercial photography, advertising, and more. Matcha Design upholds the highest personal standards for excellence and can see things from a unique perspective due to its multicultural background.  The company consistently delivers custom, high-quality, innovative solutions to its clients using technical savvy and endless creativity. For more information, visit MatchaDesign.com.

Related Tags

You Might Also Like