Tutorial Change Avatar Size
The wp_list_comments function has a parameter to change the default (48px) size to anywhere between 0 and 80px.
wp_list_comments('avatar_size=80');
The wp_list_comments function has a parameter to change the default (48px) size to anywhere between 0 and 80px.
wp_list_comments('avatar_size=80');
The bloginfo() function in WordPress gives you access to lots of useful information about your site. See the complete list. To access all these values from inside Page/Post content itself, we can make a shortcode to return the values. Add this to your functions.php file in your theme:
function digwp_bloginfo_shortcode( $atts ) {
extract(shortcode_atts(array(
'key' => '',
), $atts));
return get_bloginfo($key);
}
add_shortcode('bloginfo', 'digwp_bloginfo_shortcode');
Now you can output any of the values by calling that shortcode with "key". For example, the name of your site:
[bloginfo key='name']
Or directly to images in your theme folder:
<img src="[bloginfo key='template_url']/images/logo.jpg" alt="[bloginfo key='name'] logo" />
ol.commentlist { list-style:none; margin:0 0 1em; padding:0; text-indent:0; }
ol.commentlist li { }
ol.commentlist li.alt { }
ol.commentlist li.bypostauthor {}
ol.commentlist li.byuser {}
ol.commentlist li.comment-author-admin {}
ol.commentlist li.comment { border-bottom:1px dotted #666; padding:1em; }
ol.commentlist li.comment div.comment-author {}
ol.commentlist li.comment div.vcard { font:normal 16px georgia,times,serif; }
ol.commentlist li.comment div.vcard cite.fn { font-style:normal; }
ol.commentlist li.comment div.vcard cite.fn a.url {}
ol.commentlist li.comment div.vcard img.avatar { border:5px solid #ccc; float:right; margin:0 0 1em 1em; }
ol.commentlist li.comment div.vcard img.avatar-32 {}
ol.commentlist li.comment div.vcard img.photo {}
ol.commentlist li.comment div.vcard span.says {}
ol.commentlist li.comment div.commentmetadata {}
ol.commentlist li.comment div.comment-meta { font-size:9px; }
ol.commentlist li.comment div.comment-meta a { color:#ccc; }
ol.commentlist li.comment p { font-size:11px; margin:0 0 1em; }
ol.commentlist li.comment ul { font-size:11px; list-style:square; margin:0 0 1em 2em; }
ol.commentlist li.comment div.reply { font-size:11px; }
ol.commentlist li.comment div.reply a { font-weight:bold; }
ol.commentlist li.comment ul.children { list-style:none; margin:1em 0 0; text-indent:0; }
ol.commentlist li.comment ul.children li {}
ol.commentlist li.comment ul.children li.alt {}
ol.commentlist li.comment ul.children li.bypostauthor {}
ol.commentlist li.comment ul.children li.byuser {}
ol.commentlist li.comment ul.children li.comment {}
ol.commentlist li.comment ul.children li.comment-author-admin {}
ol.commentlist li.comment ul.children li.depth-2 { border-left:5px solid #555; margin:0 0 .25em .25em; }
ol.commentlist li.comment ul.children li.depth-3 { border-left:5px solid #999; margin:0 0 .25em .25em; }
ol.commentlist li.comment ul.children li.depth-4 { border-left:5px solid #bbb; margin:0 0 .25em .25em; }
ol.commentlist li.comment ul.children li.depth-5 {}
ol.commentlist li.comment ul.children li.odd {}
ol.commentlist li.even { background:#fff; }
ol.commentlist li.odd { background:#f6f6f6; }
ol.commentlist li.parent { border-left:5px solid #111; }
ol.commentlist li.thread-alt { }
ol.commentlist li.thread-even {}
ol.commentlist li.thread-odd {}
This would go inside the loop, probably underneath the_content(), probably in your single.php file.
// bookmark on Delicious
<a rel="nofollow" href="http://delicious.com/post?url=<?php the_permalink(); ?>&title=<?php echo urlencode(get_the_title($id)); ?>" title="Bookmark this post at Delicious">Bookmark at Delicious</a>
// submit to Digg
<a rel="nofollow" href="http://digg.com/submit?phase=2&url=<?php the_permalink(); ?>" title="Submit this post to Digg">Digg this!</a>
// tweet on Twitter
<a rel="nofollow" href="http://twitter.com/home?status=<?php echo urlencode("Currently reading: "); ?><?php the_permalink(); ?>" title="Share this article with your Twitter followers">Tweet this!</a>
// submit to StumbleUpon
<a rel="nofollow" href="http://www.stumbleupon.com/submit?url=<?php the_permalink(); ?>&title=<?php echo urlencode(get_the_title($id)); ?>" title="Share this post at StumbleUpon">Stumble this!</a>
// share on Facebook
<a rel="nofollow" href="http://www.facebook.com/sharer.php?u=<?php the_permalink();?>&t=<?php echo urlencode(get_the_title($id)); ?>" title="Share this post on Facebook">Share on Facebook</a>
// submit to Blinklist
<a rel="nofollow" href="http://blinklist.com/index.php?Action=Blink/addblink.php&url=<?php the_permalink(); ?>&Title=<?php echo urlencode(get_the_title($id)); ?>" title="Share this post on Blinklist" >Blink This!</a>
// store on Furl
<a rel="nofollow" href="http://furl.net/storeIt.jsp?t=<?php echo urlencode(get_the_title($id)); ?>&u=<?php the_permalink(); ?>" title="Share this post on Furl">Furl This!</a>
// submit to Reddit
<a rel="nofollow" href="http://reddit.com/submit?url=<?php the_permalink(); ?>&title=<?php echo urlencode(get_the_title($id)); ?>" title="Share this post on Reddit">Share on Reddit</a>
Add to the functions.php file:
add_action('admin_head', 'my_custom_fonts');
function my_custom_fonts() {
echo '<style>
body, td, textarea, input, select {
font-family: "Lucida Grande";
font-size: 12px;
}
</style>';
}
For your functions.php file or a functionality plugin:
function cc_mime_types( $mimes ){
$mimes['svg'] = 'image/svg+xml';
return $mimes;
}
add_filter( 'upload_mimes', 'cc_mime_types' );
Without this, SVG files will be rejected when attempting to upload them through the media uploader.
<?php if (current_user_can("manage_options")) : ?>
<a href="<?php echo bloginfo("siteurl") ?>/wp-admin/">Admin</a>
<?php endif; ?>
If a user is logged in and they are an Admin of the site (not just an subscriber or author), then display a link to get them to the WordPress Admin area. Otherwise, display nothing.
More specific than the regular log in / log out function, which will show for everyone:
<?php wp_loginout(); ?>
User profiles in WordPress by default have these fields for Contact Info by default: E-mail, Website, AIM, Yahoo IM, Jabber / Google Talk. You can remove those and add new ones as you wish, like in this example code for your functions.php file in your theme:
function new_contactmethods( $contactmethods ) {
$contactmethods['twitter'] = 'Twitter'; // Add Twitter
$contactmethods['facebook'] = 'Facebook'; // Add Facebook
unset($contactmethods['yim']); // Remove YIM
unset($contactmethods['aim']); // Remove AIM
unset($contactmethods['jabber']); // Remove Jabber
return $contactmethods;
}
To display that publicly, you could:
$user_id = 1;
$key = 'twitter';
$single = true;
$user_twitter = get_user_meta( $user_id, $key, $single);
echo $user_twitter;
These two functions create anchor links, and you can customize a lot of it, but it's impossible to add a class through just using their parameters alone. Gotta add a function to functions.php:
add_filter('next_posts_link_attributes', 'posts_link_attributes');
add_filter('previous_posts_link_attributes', 'posts_link_attributes');
function posts_link_attributes() {
return 'class="styled-button"';
}
The body_class function is nice for adding a bunch of classes to the body tag that have information about what kind of page is currently being displayed. Probably for styling purposes. But for whatever reason, it doesn't include a class for the current category (or categories) for a single post.
This adds that category "nice" name:
add_filter('body_class','add_category_to_single');
function add_category_to_single($classes, $class) {
if (is_single() ) {
global $post;
foreach((get_the_category($post->ID)) as $category) {
// add category slug to the $classes array
$classes[] = $category->category_nicename;
}
}
// return the $classes array
return $classes;
}
<?php edit_post_link(__('Edit This')); ?>
Put this in the theme file somewhere near where you output the_content() (likely in the single.php or page.php file) to make a link you can click that takes you into the admin to edit it. This link will only be visible when the viewer is logged in and has appropriate permissions to edit that page (administrator or author).
When you upload an image through the WordPress media uploader and then insert it into the editor, it comes with width and height attributes. These are normally desirable, as it assists the browser in making the appropriate room for the image during layout. But if you want to remove the insert action from adding these attributes, you can add this code to you functions.php file or a functionality plugin of your own making:
add_filter( 'post_thumbnail_html', 'remove_width_attribute', 10 );
add_filter( 'image_send_to_editor', 'remove_width_attribute', 10 );
function remove_width_attribute( $html ) {
$html = preg_replace( '/(width|height)="\d*"\s/', "", $html );
return $html;
}
$("img").attr("src", "http://cdn.css-tricks.com/images/banner.jpg");
$("div").attr("id", function (arr) {
return "div-id" + arr;
})
$("img").attr({
src: "http://cdn.css-tricks.com/images/banner.jpg",
title: "banner",
alt: "banner"
});
var $source = $("img").attr("src");
window.load can fire super duper fast if the page is cached. If you want to use that event but make sure a minimum amount of time has passed until it does...
(function fn() {
fn.now = +new Date;
$(window).load(function() {
if (+new Date - fn.now < 500) setTimeout(fn, 500);
// Do something
});
})();
This snippet presupposed an HTML form with and ID of "age-form" and three inputs (text or select) with the IDs "day", "month", and "year" respectively.
$("#age-form").submit(function(){
var day = $("#day").val();
var month = $("#month").val();
var year = $("#year").val();
var age = 18;
var mydate = new Date();
mydate.setFullYear(year, month-1, day);
var currdate = new Date();
currdate.setFullYear(currdate.getFullYear() - age);
if ((currdate - mydate) < 0){
alert("Sorry, only persons over the age of " + age + " may enter this site");
return false;
}
return true;
});
You may wish to do something more elegant than an alert, and should also probably validate the form with server side code or else this protection only works for users with JavaScript enabled.
There is no CSS for applying an underline (text-decoration: underline;
) only to individual words in a multiple-word element. The best way would be to wrap each word in a span (not the spaces, just the words) in spans and apply underline to those spans. Here's jQuery to do that to h1
elements.
$('h1').each(function() {
var words = $(this).text().split(' ');
$(this).empty().html(function() {
for (i = 0; i < words.length; i++) {
if (i == 0) {
$(this).append('<span>' + words[i] + '</span>');
} else {
$(this).append(' <span>' + words[i] + '</span>');
}
}
});
});
Then you could do:
h1 span {
text-decoration: underline;
}
Similar and slightly more robust solution: Lettering.js
$.event.special.tripleclick = {
setup: function(data, namespaces) {
var elem = this, $elem = jQuery(elem);
$elem.bind('click', jQuery.event.special.tripleclick.handler);
},
teardown: function(namespaces) {
var elem = this, $elem = jQuery(elem);
$elem.unbind('click', jQuery.event.special.tripleclick.handler)
},
handler: function(event) {
var elem = this, $elem = jQuery(elem), clicks = $elem.data('clicks') || 0;
clicks += 1;
if ( clicks === 3 ) {
clicks = 0;
// set event type to "tripleclick"
event.type = "tripleclick";
// let jQuery handle the triggering of "tripleclick" event handlers
jQuery.event.handle.apply(this, arguments)
}
$elem.data('clicks', clicks);
}
};
$("#whatever").bind("tripleclick", function() {
// do something
}
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');
});
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.
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.
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"));
});
$('a').filter(function() {
return this.hostname && this.hostname !== location.hostname;
}).addClass("external");
$.expr[':'].external = function(obj) {
return !obj.href.match(/^mailto\:/) && (obj.hostname != location.hostname);
};
$('a:external').addClass('external');
$('a:not([href^="http://your-website.com"]):not([href^="#"]):not([href^="/"])').addClass('external');
$('a').each(function() {
var a = new RegExp('/' + window.location.host + '/');
if (!a.test(this.href)) {
// This is an external link
}
});
This idea is from Veer.com and how they handle the dropdowns for things like T-Shirt sizes. Thank you to Dennis Sa.
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>
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 }
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);
Then we just call the plugin, when the DOM is ready of course.
$(function(){
$('.size').styleddropdown();
});
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;
}
}
});
});
$("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).
$('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.
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);
<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>
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;
}
}
}
Slightly more advanced, preventing closing of active panel:
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>
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;
}
Run after DOM is ready.
$("#slideshow > div:gt(0)").hide();
setInterval(function() {
$('#slideshow > div:first')
.fadeOut(1000)
.next()
.fadeIn(1000)
.end()
.appendTo('#slideshow');
}, 3000);
This is from James Padolsey. Check out his article for a pure JavaScript technique as well.
(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);
Target elements, call shuffle.
$('ul#list li').shuffle();
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);
});
};
$(".parent-element").shuffleChildren();
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>");
}
});
});
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>");
}
});
});
$('.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;
}
});
});
$.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;
};
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.
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)
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);
});
});
Mouse Wheel plugin is here.
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js?ver=1.3.2'></script>
<script type='text/javascript' src='/js/jquery.mousewheel.min.js'></script>
The "30" represents speed. preventDefault ensures the page won't scroll down.
$(function() {
$("body").mousewheel(function(event, delta) {
this.scrollLeft -= (delta * 30);
event.preventDefault();
});
});
$(window).bind("load", function() {
// code here
});
Normally you set and width and height for iframes. If the content inside is bigger, scrollbars have to suffice. The script below attempts to fix that by dynamically resizing the iframe to fit the content it loads.
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js?ver=1.3.2'></script>
<script type='text/javascript'>
$(function(){
var iFrames = $('iframe');
function iResize() {
for (var i = 0, j = iFrames.length; i < j; i++) {
iFrames[i].style.height = iFrames[i].contentWindow.document.body.offsetHeight + 'px';}
}
if ($.browser.safari || $.browser.opera) {
iFrames.load(function(){
setTimeout(iResize, 0);
});
for (var i = 0, j = iFrames.length; i < j; i++) {
var iSource = iFrames[i].src;
iFrames[i].src = '';
iFrames[i].src = iSource;
}
} else {
iFrames.load(function() {
this.style.height = this.contentWindow.document.body.offsetHeight + 'px';
});
}
});
</script>
Will resize an iframe like this:
<iframe src="content.html" class="iframe" scrolling="no" frameborder="0"></iframe>
var arr = [1, 2, 3, 4, 5];
var removeItem = 2;
arr = $.grep(arr, function(value) {
return value != removeItem;
});
When you scroll down a page with a long table on it, typically the header of the table scrolls away and becomes useless. This code clones the table header and applies it at the top of the page once you have scrolled beyond it, and disappears when you have scrolled past the table.
function UpdateTableHeaders() {
$("div.divTableWithFloatingHeader").each(function() {
offset = $(this).offset();
scrollTop = $(window).scrollTop();
if ((scrollTop > offset.top) && (scrollTop < offset.top + $(this).height())) {
$(".tableFloatingHeader", this).css("visibility", "visible");
$(".tableFloatingHeader", this).css("top", Math.min(scrollTop - offset.top, $(this).height() - $(".tableFloatingHeader", this).height()) + "px");
}
else {
$(".tableFloatingHeader", this).css("visibility", "hidden");
$(".tableFloatingHeader", this).css("top", "0px");
}
})
}
$(document).ready(function() {
$("table.tableWithFloatingHeader").each(function() {
$(this).wrap("<div class="divTableWithFloatingHeader" style="position:relative"></div>");
$("tr:first", this).before($("tr:first", this).clone());
clonedHeaderRow = $("tr:first", this)
clonedHeaderRow.addClass("tableFloatingHeader");
clonedHeaderRow.css("position", "absolute");
clonedHeaderRow.css("top", "0px");
clonedHeaderRow.css("left", "0px");
clonedHeaderRow.css("visibility", "hidden");
});
UpdateTableHeaders();
$(window).scroll(UpdateTableHeaders);
});
$.fn.pasteEvents = function( delay ) {
if (delay == undefined) delay = 20;
return $(this).each(function() {
var $el = $(this);
$el.on("paste", function() {
$el.trigger("prepaste");
setTimeout(function() { $el.trigger("postpaste"); }, delay);
});
});
};
Call this plugin on an element, then you get callback events for before and after pasting:
$("#some-element").on("postpaste", function() {
// do something
}).pasteEvents();
$('#pass').keyup(function(e) {
var strongRegex = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W).*$", "g");
var mediumRegex = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g");
var enoughRegex = new RegExp("(?=.{6,}).*", "g");
if (false == enoughRegex.test($(this).val())) {
$('#passstrength').html('More Characters');
} else if (strongRegex.test($(this).val())) {
$('#passstrength').className = 'ok';
$('#passstrength').html('Strong!');
} else if (mediumRegex.test($(this).val())) {
$('#passstrength').className = 'alert';
$('#passstrength').html('Medium!');
} else {
$('#passstrength').className = 'error';
$('#passstrength').html('Weak!');
}
return true;
});
<input type="password" name="pass" id="pass" />
<span id="passstrength"></span>
Refresh certain elements of a page using jQuery after a set amount of time, can be used with any element with an ID. I amended the example given with the URL to only refresh once and not intermittently. Works in all browsers.
$('#button1').click(function() {
var url = "http:www.your-url.com?ID=" + Math.random(); //create random number
setTimeout(function() {
$("#elementName").load(url+" #elementName>*","");
}, 1000); //wait one second to run function
});
innerHTML() is native and returns the contents of a DOM node (e.g. <span>I live inside a div.</span>
. outerHTML() is not, which would include the current DOM node (e.g. <div><span>I live inside a div.</span></div>
). This is a chain-able jQuery version of doing that.
$.fn.outerHTML = function(){
// IE, Chrome & Safari will comply with the non-standard outerHTML, all others (FF) will have a fall-back for cloning
return (!this.length) ? this : (this[0].outerHTML || (
function(el){
var div = document.createElement('div');
div.appendChild(el.cloneNode(true));
var contents = div.innerHTML;
div = null;
return contents;
})(this[0]));
}
$('a').each(function() {
var a = new RegExp('/' + window.location.host + '/');
if(!a.test(this.href)) {
$(this).click(function(event) {
event.preventDefault();
event.stopPropagation();
window.open(this.href, '_blank');
});
}
});
You can do this straight with HTML, but that is invalid markup, this takes care of business without invalid code and unnecessary markup.
Or, you can still avoid the validation problems and just append the class target=_blank thing to any links with href attributes starting with http://. The example below only targets links in a #content area. Scoping down like that might be a good idea in case your menus are dynamic and create full URLs.
$("#content a[href^='http://']").attr("target","_blank");
Also note that there are a wide variety of different ways to only target external links.
jQuery.fn.putCursorAtEnd = function() {
return this.each(function() {
$(this).focus()
// If this function exists...
if (this.setSelectionRange) {
// ... then use it (Doesn't work in IE)
// Double the length because Opera is inconsistent about whether a carriage return is one character or two. Sigh.
var len = $(this).val().length * 2;
this.setSelectionRange(len, len);
} else {
// ... otherwise replace the contents with itself
// (Doesn't work in Google Chrome)
$(this).val($(this).val());
}
// Scroll to the bottom, in case we're in a tall textarea
// (Necessary for Firefox and Google Chrome)
this.scrollTop = 999999;
});
};
Check out this Pen!
Assuming HTML like this:
<ul>
<li>one</li>
<li>two</li>
<li>three</li>
</ul>
So if "Two" is clicked, move it to the top of the list.
$("li").click(function() {
$(this).parent().prepend($(this));
});
Will work for multiple lists...
// NEW selector
jQuery.expr[':'].Contains = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
// OVERWRITES old selecor
jQuery.expr[':'].contains = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
$.expr[":"].contains = $.expr.createPseudo(function(arg) {
return function( elem ) {
return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
};
});
With this in place,
$("div:contains('John')")
would select all three of these elements:
<div>john</div>
<div>John</div>
<div>hey hey JOHN hey hey</div>
Demo via Pablo Fortes.
$(".myBox").click(function(){
window.location=$(this).find("a").attr("href");
return false;
});
Looks for a link inside div with class of "myBox". Redirects to that links value when anywhere in div is clicked.
Reference HTML:
<div class="myBox">
blah blah blah.
<a href="http://google.com">link</a>
</div>
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
google.load("jquery", "1.2.6");
</script>
<script type="text/javascript" src="js/example.js"></script>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js?ver=1.3.2'></script>
var jQueryScriptOutputted = false;
function initJQuery() {
//if the jQuery object isn't available
if (typeof(jQuery) == 'undefined') {
if (! jQueryScriptOutputted) {
//only output the script once..
jQueryScriptOutputted = true;
//output the script (load it from google api)
document.write("<scr" + "ipt type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></scr" + "ipt>");
}
setTimeout("initJQuery()", 50);
} else {
$(function() {
//do anything that needs to be done on document.ready
});
}
}