Showing posts with label jquery. Show all posts

Tutorial Trigger Click on Input when Label is Clicked

by in , 0

Labels should have "for" attributes that match the ID of the input they are labeling. This means we can snag that attribute and use it in a selector to trigger a click on the input itself. Assuming of course you have some reason to watch for clicks on inputs.

var labelID;

$('label').click(function() {
       labelID = $(this).attr('for');
       $('#'+labelID).trigger('click');
});

Tutorial Track Window Resizes through Google Analytics

by in , 0

Sparkbox has this snippet to help figure out how often browser windows really are resized.

(function() {
  var resizeTimer;
  
  // Assuming we have jQuery present
  $( window ).on( "resize", function() {
    
    // Use resizeTimer to throttle the resize handler
    clearTimeout( resizeTimer );
    resizeTimer = setTimeout(function() {

     /* Send the event to Google Analytics
      *
      * https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiEventTracking
      * _trackEvent(category, action, opt_label, opt_value, opt_noninteraction)   
      */
      var $window = $( window );
      _gaq.push( [ "_trackEvent", "User Actions", "Browser Resize", $window.width() + " x " + $window.height() ] );
    }, 1000);
  });
})();

Note how easy it is to track events in Google Analytics. That can be used for just about anything.

Tutorial Toggle Text

by in , 0

Let's say you have a link to show more options which expands a list of options. It's says "more options". It's easy to toggle those options with .toggle() or .slideToggle(), but the text remains the same. To toggle the text too...

$("#more-less-options-button").click(function() {
     var txt = $("#extra-options").is(':visible') ? 'more options' : 'less options';
     $("#more-less-options-button").text(txt);
     $("#extra-options").slideToggle();
});

There is a bunch of other ways, as well.

Tutorial Test if at least one checkbox is checked

by in , 0

In this example, a submit button is disabled if none of the checkboxes are checked and enabled if at least one is checked.

<form>
   <!-- bunch of checkboxes like: -->
   <input type="checkbox" ... >
   <input type="checkbox" ... >

   <!-- submit button, defaults to disabled -->
   <input type="submit" value="submit">
</form>

The trick is that you can use .is(":checked") on a jQuery object full of a bunch of elements and it'll return true if any of them are checked and false if none of them are. AND, using .attr() for the disabled attribute with that boolean value will enable/disable that button.

var checkboxes = $("input[type='checkbox']"),
    submitButt = $("input[type='submit']");

checkboxes.click(function() {
    submitButt.attr("disabled", !checkboxes.is(":checked"));
});

Reference URL

Tutorial Target Only External Links

by in , 0

Technique #1

$('a').filter(function() {
   return this.hostname && this.hostname !== location.hostname;
}).addClass("external");

Technique #2

$.expr[':'].external = function(obj) {
    return !obj.href.match(/^mailto\:/) && (obj.hostname != location.hostname);
};
$('a:external').addClass('external');

Technique #3

$('a:not([href^="http://your-website.com"]):not([href^="#"]):not([href^="/"])').addClass('external');

Technique #4

$('a').each(function() {
   var a = new RegExp('/' + window.location.host + '/');
   if (!a.test(this.href)) {
       // This is an external link
   }
});

Tutorial Styled Popup Menu

by in , 0

This idea is from Veer.com and how they handle the dropdowns for things like T-Shirt sizes. Thank you to Dennis Sa.

View Demo

HTML

We'll wrap a regular text input inside an <div>, which also contains an unordered list which will represent the values for the popup menu.

<div class="size">
	<input type="text" name="test" value="choose your size" class="field" readonly="readonly" />
	<ul class="list">
		<li>Male - M</li>
		<li>Female - M</li>
		<li>Male - S</li>
		<li>Female - S</li>
	</ul>
</div>

CSS

The lists will be hidden by default, but still all styled up and ready to go when a click triggers them to be shown.

.size { position:relative }
.size .field {
	width:300px; background:#EC6603; color:#fff; padding:5px; border:none; cursor:pointer;
	font-family:'lucida sans unicode',sans-serif; font-size:1em;
	border:solid 1px #EC6603;
	-webkit-transition: all .4s ease-in-out;
	transition: all .4s ease-in-out;
}
.size .field:hover {
	border:solid 1px #fff;
	-moz-box-shadow:0 0 5px #999; -webkit-box-shadow:0 0 5px #999; box-shadow:0 0 5px #999
}
.size>ul.list { display:none;
	position:absolute; left:30px; top:-30px; z-index:999;
	width:300px;
	margin:0; padding:10px; list-style:none;
	background:#fff; color:#333;
	-moz-border-radius:5px; -webkit-border-radius:5px; border-radius:5px;
	-moz-box-shadow:0 0 5px #999; -webkit-box-shadow:0 0 5px #999; box-shadow:0 0 5px #999
}
.size>ul.list li {
	padding:10px;
	border-bottom: solid 1px #ccc;
}
.size>ul.list li:hover {
	background:#EC6603; color:#fff;
}
.size>ul.list li:last-child { border:none }

jQuery

We'll throw a quick plugin together, so that this functionality can be called on any div wrapper that contains this same HTML setup.=

(function($){
	$.fn.styleddropdown = function(){
		return this.each(function(){
			var obj = $(this)
			obj.find('.field').click(function() { //onclick event, 'list' fadein
			obj.find('.list').fadeIn(400);
			
			$(document).keyup(function(event) { //keypress event, fadeout on 'escape'
				if(event.keyCode == 27) {
				obj.find('.list').fadeOut(400);
				}
			});
			
			obj.find('.list').hover(function(){ },
				function(){
					$(this).fadeOut(400);
				});
			});
			
			obj.find('.list li').click(function() { //onclick event, change field value with selected 'list' item and fadeout 'list'
			obj.find('.field')
				.val($(this).html())
				.css({
					'background':'#fff',
					'color':'#333'
				});
			obj.find('.list').fadeOut(400);
			});
		});
	};
})(jQuery);

Usage

Then we just call the plugin, when the DOM is ready of course.

$(function(){
	$('.size').styleddropdown();
});

Tutorial Smooth Scrolling

by in , 0

Performs a smooth page scroll to an anchor on the same page.

$(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }
  });
});

View Demo

Reference URL

Tutorial Smarter Event Binding

by in , 0

$("p").live("click", function(){
      $(this).css("color", "red");
});

The reason this is smarter is because there are likely many p elements on the page. If there were, say, 10 of them, traditional click event binding would require 10 handlers. The live function only requires one, reducing memory needed by the browser. Then imagine compounding the issue by 100 (for example, a table with 1000 cells with hover events).

Additionally, using the live function does not require events to be re-bound when additional elements are added to the page (like via AJAX).

Reference URL

Tutorial Sliding Background Links

by in , 0

$('a', '#nav').hover(function() {
         if(!$(this).parent().hasClass('current')) {
                 $(this).stop().animate({
                         backgroundPosition: '(0 -75px)'
                 });
         }
 }, function() {
         if(!$(this).parent().hasClass('current')) {
                 $(this).stop().animate({
                         backgroundPosition: '(0 -0)'
                 });
         }
 });

Slides up and down the background image of a link when rolled over. Requires background position plugin.

Tutorial Simple jQuery Accordion

by in , 0

jQuery

Make sure either to run on DOM ready or at the bottom of the page.

(function($) {
    
  var allPanels = $('.accordion > dd').hide();
    
  $('.accordion > dt > a').click(function() {
    allPanels.slideUp();
    $(this).parent().next().slideDown();
    return false;
  });

})(jQuery);

HTML

<dl class="accordion">

<dt><a href="">Panel 1</a></dt>
<dd>Pellentesque fermentum dolor. Aliquam quam lectus, facilisis auctor, ultrices ut, elementum vulputate, nunc.</dd>

<dt><a href="">Panel 2</a></dt>
<dd>Donec nec justo eget felis facilisis fermentum. Aliquam porttitor mauris sit amet orci. Aenean dignissim pellentesque felis.</dd>

<dt><a href="">Panel 3</a></dt>
<dd>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Phasellus hendrerit. Pellentesque aliquet nibh nec urna. In nisi neque, aliquet vel, dapibus id, mattis vel, nisi. Sed pretium, ligula sollicitudin laoreet viverra, tortor libero sodales leo, eget blandit nunc tortor eu nibh. Nullam mollis. Ut justo. Suspendisse potenti.</dd>

</dl>

SCSS

Sorry if you don't use SASS. Should be pretty easy to convert.

.accordion {
   margin: 50px;   
   dt, dd {
      padding: 10px;
      border: 1px solid black;
      border-bottom: 0; 
      &:last-of-type {
        border-bottom: 1px solid black; 
      }
      a {
        display: block;
        color: black;
        font-weight: bold;
      }
   }
  dd {
     border-top: 0; 
     font-size: 12px;
     &:last-of-type {
       border-top: 1px solid white;
       position: relative;
       top: -1px;
     }
  }
}

View Demo

Slightly more advanced, preventing closing of active panel:

View Demo

Tutorial Simple Auto-Playing Slideshow

by in , 0

HTML

Wrapper with div's as the "slides", which can contain any content.

<div id="slideshow">
   <div>
     <img src="http://farm6.static.flickr.com/5224/5658667829_2bb7d42a9c_m.jpg">
   </div>
   <div>
     <img src="http://farm6.static.flickr.com/5230/5638093881_a791e4f819_m.jpg">
   </div>
   <div>
     Pretty cool eh? This slide is proof the content can be anything.
   </div>
</div>

CSS

Slides need to be absolutely positioned within the wrapper. This has a tiny bit of extra pizazz:

#slideshow { 
    margin: 50px auto; 
    position: relative; 
    width: 240px; 
    height: 240px; 
    padding: 10px; 
    box-shadow: 0 0 20px rgba(0,0,0,0.4); 
}

#slideshow > div { 
    position: absolute; 
    top: 10px; 
    left: 10px; 
    right: 10px; 
    bottom: 10px; 
}

jQuery JavaScript

Run after DOM is ready.

$("#slideshow > div:gt(0)").hide();

setInterval(function() { 
  $('#slideshow > div:first')
    .fadeOut(1000)
    .next()
    .fadeIn(1000)
    .end()
    .appendTo('#slideshow');
},  3000);

See it

View Demo

Very similar one from Snook.

Tutorial Shuffle DOM Elements

by in , 0

This is from James Padolsey. Check out his article for a pure JavaScript technique as well.

Plugin

(function($){
 
    $.fn.shuffle = function() {
 
        var allElems = this.get(),
            getRandom = function(max) {
                return Math.floor(Math.random() * max);
            },
            shuffled = $.map(allElems, function(){
                var random = getRandom(allElems.length),
                    randEl = $(allElems[random]).clone(true)[0];
                allElems.splice(random, 1);
                return randEl;
           });
 
        this.each(function(i){
            $(this).replaceWith($(shuffled[i]));
        });
 
        return $(shuffled);
 
    };
 
})(jQuery);

Usage

Target elements, call shuffle.

$('ul#list li').shuffle();

Tutorial Shuffle Children

by in , 0

Nice clean version of a ghetto one that I wrote.

$.fn.shuffleChildren = function() {
    $.each(this.get(), function(index, el) {
        var $el = $(el);
        var $find = $el.children();

        $find.sort(function() {
            return 0.5 - Math.random();
        });

        $el.empty();
        $find.appendTo($el);
    });
};

Usage

$(".parent-element").shuffleChildren();

View Demo

Tutorial Show Most Recent Picasaweb Uploads

by in , 0

Replace the "tester" username below with your own, and the target value with the selector of the element you wish to append the pictures to.

$(document).ready(function() {
	$.getJSON("http://picasaweb.google.com/data/feed/base/user/tester/?kind=photo&access=public&alt=json&callback=?",
	function(data) {
		var target = "#latest-picasaweb-images ul"; // Where is it going?
		for (i = 0; i <= 9; i = i + 1) { // Loop through the 10 most recent, [0-9]
			var pic = data.feed.entry[i].media$group;
			var liNumber = i + 1; // Add class to each LI (1-10)
			var thumbSize = 0; // Size of thumbnail - 0=small 1=medium 2=large
			$(target).append("<li class='no-" + liNumber + "'><a title='" + pic.media$description.$t + "' href='" + pic.media$content[0].url + "'><img src='" + pic.media$thumbnail[thumbSize].url + "' /></a></li>");
		}
	});
});

Example

Reference URL

Tutorial Show Most Recent Flickr Uploads

by in , 0

This code will display the most recent uploads from Flickr for any account. Replace the "35591378@N03" (the Whitehouse account) in the code below with the ID of the account you are fetching from. Use this if you need help finding it. Alter the "9" in the loop to show more or less than 10.

$(document).ready(function() {
       $.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?id=35591378@N03&format=json&jsoncallback=?", function(data) {
               var target = "#latest-flickr-images ul"; // Where is it going?
               for (i = 0; i <= 9; i = i + 1) { // Loop through the 10 most recent, [0-9]
                       var pic = data.items[i];
                       var liNumber = i + 1; // Add class to each LI (1-10)
                       $(target).append("<li class='flickr-image no-" + liNumber + "'><a title='" + pic.title + "' href='" + pic.link + "'><img src='" + pic.media.m + "' /></a></li>");
               }
       });
});

Example

Reference URL

Tutorial Set/Clear Default Input Value

by in , 0

$('.default-value').each(function() {

       var default_value = this.value;

       $(this).focus(function(){
               if(this.value == default_value) {
                       this.value = '';
               }
       });

       $(this).blur(function(){
               if(this.value == '') {
                       this.value = default_value;
               }
       });

});

Tutorial Serialize Form to JSON

by in , 0

$.fn.serializeObject = function()
{
   var o = {};
   var a = this.serializeArray();
   $.each(a, function() {
       if (o[this.name]) {
           if (!o[this.name].push) {
               o[this.name] = [o[this.name]];
           }
           o[this.name].push(this.value || '');
       } else {
           o[this.name] = this.value || '';
       }
   });
   return o;
};

Reference URL

Tutorial Select List Item Only If Doesn’t Contain Another List (and is top level)

by in , 0

I realize this is rather specific, but I had to write this selector earlier to fix a problem and I used jQuery because the selector is rather advanced (and needed to work cross-browser). I needed to select the anchor link of a list item but only if that list item didn't contain another list and was at the top level of the nested list structure (no deeper).

$("ul.dropdown > li:not(:has('ul')) a").css({
        "background-image": "none",
});

The idea was that each of the top level links in the dropdown menu had a "down arrow" graphic, but the list items that did not have a dropdown should have that arrow removed.

Tutorial Select Element Only if Children are Not Animated

by in , 0

var myChildrenBehave =  $(".element").filter(function() {
  var filtered = $(this).children().not(":animated");
  return filtered;
 });

This selects the element only if its children behave (not being animated). Very helpful on a drop down menu (on hover or click)

Tutorial Search/Replace

by in , 0

jQuery(function () { 
    jQuery(":contains(FIND)").not(":has(:contains(FIND))").each(function () { 
        var that = $(this), 
            html = that.html(); 
         
        html = html.replace(/(\(FIND:.*?\))/g, "REPLACE-WITH"); 
        that.html(html); 
    }); 
});

Reference URL