Showing posts with label jquery. Show all posts

Tutorial Find and Wrap Ampersands

by in , 0

Load this plugin. Then:

$("body *").replaceText( /&/gi, '<b class="ampersand">' + '&' + '</b>' );

Change the selector as needed. That one is pretty intense.

Now you have a class name you can use to style them specially.

.ampersand {
   font-family: Baskerville, Some Other Cool Font, Serif;
   font-style: italic;
}

Reference URL

Tutorial Find all Internal Links

by in , 0

Find all links that start with the sites domain, a slash, relative file path, or a hashtag.

var siteURL = "http://" + top.location.host.toString();

var $internalLinks = $("a[href^='"+siteURL+"'], a[href^='/'], a[href^='./'], a[href^='../'], a[href^='#']");

Tutorial Fallback for CDN hosted jQuery

by in , 0

Several big companies offer copies of jQuery hosted on their CDN's (Content Delivery Network). Most notoriously Google, but also Microsoft and jQuery themselves. A lot of people swear by this since it saves bandwidth, downloads faster, and perhaps even stays cached jumping between different sites that use the same script.

There is always that twinge of doubt though, that perhaps something goes wrong with these big companies CDN at the script isn't available (it happens). It's more reliable to use your own website, as hey, if they are loading your webpage, then your server is up and will server the script just fine, albeit with out the benefits of the CDN.

So perhaps the best solution is to use both methods! Use the CDN first, and if it fails, load the local copy. Here is a technique:

<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
if (typeof jQuery == 'undefined') {
    document.write(unescape("%3Cscript src='/js/jquery-1.4.2.min.js' type='text/javascript'%3E%3C/script%3E"));
}
</script>

Reference URL

Tutorial Fade One Image to Another Menu

by in , 0

Make a CSS sprite image, with the top half and the bottom half being the two images you want to animate between. The jQuery adds a <span> tag, and adds the bottom half of the sprite image as its background. As you hover on and off, the span animates between fully transparent and fully opaque, fading one image into another.

HTML:

<ul id="menu">
       <li id="home"><a href="#">home</a></li>
       <li id="about"><a href="#">about</a></li>
       <li id="services"><a href="#">services</a></li>
       <li id="contact"><a href="#">contact</a></li>
</ul>

CSS:

ul#menu li a{float:left;display:block;background:url("images/menu.png")  no-repeat;width:150px;text-indent:-9999px;height:50px}
ul#menu li#home a{background-position:0px 0px}
ul#menu li#about a{background-position:-150px 0px}
ul#menu li#services a{background-position:-300px 0px}
ul#menu li#contact a{background-position:-450px 0px}

ul#menu li a span {background:url("images/menu.png");height:50px;display:block}
ul#menu li#home a span{background-position:0px -50px}
ul#menu li#about a span{background-position:-150px -50px}
ul#menu li#services a span{background-position:-300px -50px}
ul#menu li#contact a span{background-position:-450px -50px}

jQuery:

$(function() {
       $("ul#menu li a").wrapInner("<span></span>");
       $("ul#menu li a span").css({"opacity" : 0});

       $("ul#menu li a").hover(function(){
               $(this).children("span").animate({"opacity" : 1}, 400);
       }, function(){
               $(this).children("span").animate({"opacity" : 0}, 400);
       });
});

Reference URL

Tutorial Fade Image Into Another Image

by in , 0

Make a div that is the exact size of the image. This div will have a background image applied to it of the second image. Then put an inline image inside it.

<div id="kitten">
    <img src="http://cdn.css-tricks.com/images/kitten.jpg" alt="Kitten" />
</div>

Fading the inline image in and out will reveal/hide the second (background) image.

$("#kitten").hover(function(){

    $(this).find("img").fadeOut();

}, function() {

    $(this).find("img").fadeIn();

});

Tutorial Exclude $(this) from Selector

by in , 0

Let's say you want to attach a click handler to every link on a page. The function for that click handler turns all the other links a different color.

var $allLinks = $("a");

$allLinks.click(function() {

     $allLinks.not(this).css("color", "red");

});

You can use the .not() function to remove elements from a set, so padding this to that function will remove the current element before the color change.

Tutorial Equalize Heights of Divs

by in , 0

var maxHeight = 0;

$("div").each(function(){
   if ($(this).height() > maxHeight) { maxHeight = $(this).height(); }
});

$("div").height(maxHeight);

Tutorial Draggable without jQuery UI

by in , 0

It doesn't have all the fancy callbacks and options, but hey, it makes things draggable (and with a specified handle optionally).

(function($) {
    $.fn.drags = function(opt) {

        opt = $.extend({handle:"",cursor:"move"}, opt);

        if(opt.handle === "") {
            var $el = this;
        } else {
            var $el = this.find(opt.handle);
        }

        return $el.css('cursor', opt.cursor).on("mousedown", function(e) {
            if(opt.handle === "") {
                var $drag = $(this).addClass('draggable');
            } else {
                var $drag = $(this).addClass('active-handle').parent().addClass('draggable');
            }
            var z_idx = $drag.css('z-index'),
                drg_h = $drag.outerHeight(),
                drg_w = $drag.outerWidth(),
                pos_y = $drag.offset().top + drg_h - e.pageY,
                pos_x = $drag.offset().left + drg_w - e.pageX;
            $drag.css('z-index', 1000).parents().on("mousemove", function(e) {
                $('.draggable').offset({
                    top:e.pageY + pos_y - drg_h,
                    left:e.pageX + pos_x - drg_w
                }).on("mouseup", function() {
                    $(this).removeClass('draggable').css('z-index', z_idx);
                });
            });
            e.preventDefault(); // disable selection
        }).on("mouseup", function() {
            if(opt.handle === "") {
                $(this).removeClass('draggable');
            } else {
                $(this).removeClass('active-handle').parent().removeClass('draggable');
            }
        });

    }
})(jQuery);

Usage

$('div').drags();

Demo

Reference URL

Tutorial Display Only First X Divs, Toggle Rest

by in , 0

var news = 2;
hidenews = "- Hide news archive";
shownews = "+ Show news archive";

$(".archive").html( shownews );
$(".news:not(:lt("+news+"))").hide();

$(".archive").click(function (e) {
   e.preventDefault();
       if ($(".news:eq("+news+")").is(":hidden")) {
           $(".news:hidden").show();
           $(".archive").html( hidenews );
       } else {
           $(".news:not(:lt("+news+"))").hide();
           $(".archive").html( shownews );
       }
});

HTML:

<div class="news">First news</div>
<div class="news">Second news</div>
<div class="news">Third news</div>
<a class="archive" href="#"></a>

Reference URL

Tutorial Display Latest FeedBurner Post

by in , 0

This snippet will display the latest post in a specified FeedBurner feed. Just set the URL to your desired FeedBurner feed.

$(document).ready(function(){
       $.ajax({
               type: "GET",
               url: "http://feeds.feedburner.com/examplefeed",
               success: function(data){
                       $("#date").text($(data).find("item:first>pubDate:first").text());
                       $("#title").html("<a href='"+$(data).find("item:first>link:first").text()+"'>"+$(data).find("item:first>title:first").text()+"</a>");
                       $("#description").html($(data).find("item:first>description:first").text());
               }
       });
});

This example assumes that there are 3 elements that this information will be sent to, with the ID attributes set to date, title and description respectively.

Tutorial Display Last Tweet

by in , 0

The code below no longer works as-is with the Twitter API update to 1.1 as of 2013-06-11. The 1.1 API requires oAuth which requires a server side component. Here's a PHP way to interact with the new API. Googling around will find you many other libraries and such. There is an all-JavaScript method for getting tweets, but it may be a bit of a loophole that you may not want to count on.
$.getJSON("https://api.twitter.com/1/statuses/user_timeline/chriscoyier.json?count=1&include_rts=1&callback=?", function(data) {
     $("#twitter").html(data[0].text);
});

Make sure you change username.json to your actual username and #twitter to the actual selector you wish to replace the contents of.

You can play around with this on this CodePen (deprecated).

Tutorial Display Browser and Version

by in , 0

This is jQuery specific, and contains a bit of a hack/fix for dealing with Chrome. This works between jQuery 1.5.1 and jQuery 1.8.3. It's gone in jQuery 1.9. Presumably because it was used too improperly too frequently and it was hurting the web. Better to feature detect when possible.

var userAgent = navigator.userAgent.toLowerCase(),
    browser   = '',
    version   = 0;

$.browser.chrome = /chrome/.test(navigator.userAgent.toLowerCase());

// Is this a version of IE?
if ($.browser.msie) {
  userAgent = $.browser.version;
  userAgent = userAgent.substring(0,userAgent.indexOf('.'));	
  version = userAgent;
  browser = "Internet Explorer";
}

// Is this a version of Chrome?
if ($.browser.chrome) {
  userAgent = userAgent.substring(userAgent.indexOf('chrome/') + 7);
  userAgent = userAgent.substring(0,userAgent.indexOf('.'));	
  version = userAgent;
  // If it is chrome then jQuery thinks it's safari so we have to tell it it isn't
  $.browser.safari = false;
  browser = "Chrome";
}

// Is this a version of Safari?
if ($.browser.safari) {
  userAgent = userAgent.substring(userAgent.indexOf('safari/') + 7);	
  userAgent = userAgent.substring(0,userAgent.indexOf('.'));
  version = userAgent;	
  browser = "Safari";
}

// Is this a version of Mozilla?
if ($.browser.mozilla) {
	//Is it Firefox?
	if (navigator.userAgent.toLowerCase().indexOf('firefox') != -1) {
		userAgent = userAgent.substring(userAgent.indexOf('firefox/') + 8);
		userAgent = userAgent.substring(0,userAgent.indexOf('.'));
		version = userAgent;
		browser = "Firefox"
	}
	// If not then it must be another Mozilla
	else {
	  browser = "Mozilla (not Firefox)"
	}
}

// Is this a version of Opera?
if ($.browser.opera) {
	userAgent = userAgent.substring(userAgent.indexOf('version/') + 8);
	userAgent = userAgent.substring(0,userAgent.indexOf('.'));
	version = userAgent;
	browser = "Opera";
}

// Now you have two variables, browser and version
// which have the right info

Tutorial Disable / Re-enable Inputs

by in , 0

Disable:

$("#submit-button").attr("disabled", true);

Re-enable:

$("#submit-button").removeAttr("disabled");

Tutorial Detect First Visible Element of Certain Class

by in , 0

Adds a class of "first" to the first element that has a class of "activity" that is visible in the browser window.

$(window).scroll(function(){
	var scrollTop = $(window).scrollTop();
	var windowHeight = $(window).height();		
	var first = false;
	$(".activity").each( function() {
		var offset = $(this).offset();
		if (scrollTop <= offset.top && ($(this).height() + offset.top) < (scrollTop + windowHeight) && first == false) {
			$(this).addClass("first");
			first=true;
		} else {
			$(this).removeClass("first");
			first=false;
		}
	});
});

Tutorial Cycle Through a List

by in , 0

This code will cycle through an unordered list with an ID of 'cyclelist'. Can be used on any element with children. Replace "ul#cyclelist li" with the elements you want to cycle through.

$(document).ready(function() {

	 var j = 0;
	 var delay = 2000; //millisecond delay between cycles
	 function cycleThru(){
	         var jmax = $("ul#cyclelist li").length -1;
	         $("ul#cyclelist li:eq(" + j + ")")
	                 .animate({"opacity" : "1"} ,400)
	                 .animate({"opacity" : "1"}, delay)
	                 .animate({"opacity" : "0"}, 400, function(){
	                         (j == jmax) ? j=0 : j++;
	                         cycleThru();
	                 });
	         };

	 cycleThru();

 });
ul#cyclelist {width:200px;border:solid;position:relative;overflow:hidden;height:200px}
ul#cyclelist li {font-size:1.4em;padding:20px;opacity:0;position:absolute}

Reference URL

Tutorial Combine Slide and Fade Functions

by in , 0

$.fn.slideFadeToggle  = function(speed, easing, callback) {
        return this.animate({opacity: 'toggle', height: 'toggle'}, speed, easing, callback);
}; 

Usage

$("#something").click(function() {
   $(this).slideFadeToggle();
});

Tutorial Click Once and Unbind

by in , 0

Have something happen on a click event, but only once! Unbind the click handler after the element has been clicked once.

$('#my-selector').bind('click', function() {
       $(this).unbind('click');
       alert('Clicked and unbound!');
});

Also see Ben's comment below for jQuery's .one() function which is essentially the same thing.

Tutorial Clear Default Search String on Focus

by in , 0

$("#s")
    .val("Search...")
    .css("color", "#ccc")
    .focus(function(){
        $(this).css("color", "black");
        if ($(this).val() == "Search...") {
            $(this).val("");
        }
    })
    .blur(function(){
        $(this).css("color", "#ccc");
        if ($(this).val() == "") {
            $(this).val("Search...");
        }
    });
Set value of field to "Search..." When field comes into focus, set color to black. If value is default, remove it. When field goes out of focus, set color back to light gray. If value is empty, put back default value

Tutorial Clear a File Input

by in , 0

You can just clone it and replace it with itself, with all events still attached.

var input = $("#control");

function something_happens() {
    input.replaceWith(input.val('').clone(true));
};

Tutorial Check if jQuery is Loaded

by in , 0

if (typeof jQuery == 'undefined') {

    // jQuery IS NOT loaded, do stuff here.

}