Math trick to impress your friends

This is cool to impress someone with your “paranormal” skills.

Put someone to choose a random number, preferably a large one ( 3 or 4 figures ), and he (or she) have to keep this number secret from you and do the following math with it:

xyz = he’s or she’s chosen number ( ex. 315 )

Step1: xyz * 3 ( multiply by 3, ex. 315 * 3 = 945 )

Step2: then take the result and add all it’s figures ( abcd => a+b+c+d , ex. 945 => 9 + 4 + 5 = 18 )

Step3: Repeat Step1 with the new number ( the sum of figures, ex. 18 * 3 = 54 )

Step4: Repeat Step2 ( ex. 5 + 4 = 9 )

Repeat steps 1 and 2 until you get a one figure number.

When the person or persons finished the above algorithm, you tell them the number they’ve got ( which with the algorithm above will be always 9 !), and the question that will appear will sure be “How did you know ?”, … :) try it!

WordPress promoted posts and/or pages

Show a number of posts ( or pages ) links and thumbnails images, randomly picked from a certain set.

For this we will need the set of ‘promoted’ posts ( or pages ), and a function to get the posts thumbnails.

For get the posts thumbnails function i will not insist and just use this one here. The set of ‘promoted’ posts will be a simple array of ID’s.

Add this to the functions.php file

function getPromotedLinks() {
	// the array with the ID's of the posts ( or pages ) to be shown as promoted
	$promoted = array( x, xx, xxx, ... n ); //here put your posts or pages ID's
	$rand_ids = array_rand( $promoted, 5 ); //replace '5' with an integer of how many promoted items to be shown at once

	//what will be showed in frontend
	echo '<ul class="promotedlinks">';
		foreach ( $rand_ids as $i ) {
			//get the post (or page) image
			$postID = $promoted[$i];
			$all_images =& get_children('post_type=attachment&post_mime_type=image&post_parent=' . $postID );

			if($all_images) {
				$arr_of_all_images = array_keys( $all_images );
				// Get the first image attachment from post
				$firstImage = $arr_of_all_images[0];
				// Get the thumbnail url for the attachment
				// If you want the full-size image instead of the thumbnail, use wp_get_attachment_url() instead of wp_get_attachment_thumb_url().
				$thumb_url = wp_get_attachment_thumb_url( $firstImage );
				// Build the <img> string
				$First_thumb_image = '<img src="' . $thumb_url . '" width="100" height="100" alt="Thumbnail Image" title="Thumbnail Image" />';
			}

			echo '<li><a href="'. get_permalink( $promoted[$i] ) .'">';
				echo $First_thumb_image;
			echo '<span>'. get_the_title( $promoted[$i] ) .'</span></a></li>';
		}
	echo '</ul>';
}

this is all, … you get a list of 5 (or how many you like), random links with thumbnails, which you can call anywhere ( inside loop, outside loop-> sidebar etc ), by <?php getPromotedLinks(); ?>.

Style as you wish,… an example would be:

ul.promotedlinks { margin: 0; list-style-type: none; }
ul.promotedlinks li { width: 125px; float: left; padding: 0; border-left: 1px solid #DDDDEE; overflow: hidden; }
ul.promotedlinks li:first-child { border-left: none; }
ul.promotedlinks li a { display: block; height: 100%; padding: 6px; }
ul.promotedlinks li a:hover { text-decoration: none; background: #DDDDEE; }
ul.promotedlinks li a img, ul.promotedlinks li a span { display: block; }

WordPress – Show author meta on author archive

A neat feature for wordpress blogs or custom sites is to show the author biography and other information on the ‘author archive’ page.

For this we could use the ‘the_author_meta()‘ or get_the_author_meta functions to get the meta information we need, but if we want to show the author info outside the loop, so that even if the user hasn’t published any posts, it will still be visible. In order to do this we will get an object with all the info we need.

$userInfo = get_user_by('slug', get_query_var('author_name'));

and this holds all the info we need, and we will get it like this:

echo $userInfo->display_name
echo $userInfo->first_name
echo $userInfo->last_name
echo $userInfo->eme_phone
echo $userInfo->user_email
echo $userInfo->user_url
echo nl2br($userInfo->description)
//etc

the nl2br() php function is used to return the user description with <br /> which are striped out by wordpress.

And changing the first parameter of the get_user_by function, to one of the supported values $field = ‘id’, ‘slug’, ’email’, or ‘login’ , you can use this object in all places you need.

WordPress shortcodes for attachments

A nice cool way to organize the attachments from a post or page, and not having to deal with ugly html in the wysiwyg editor, is using shortcodes. Just add the code below into your theme functions.php.

// [attachments]
function attachmentUrl($atts) {
  extract(shortcode_atts(array(
      "src" => ''
  ), $atts));
  /* $filename_match = preg_match("/([a-zA-Z0-9_\.\-]+\.[a-zA-Z]+)$/", $src, $filename); */
  $filename_match = preg_match("/\/([^\/]*$)/", $src, $filename);
  return '<div class="attachments"><h4>Attachments</h4><ul class="attachments_list attachment"><li><a href="'.$src.'" target="_blank">'.$filename[1].'</a></li></ul></div>';
}
add_shortcode("attachment", "attachmentUrl");

// Audio shortcode
function audioURL($atts) {
  extract(shortcode_atts(array(
      "src" => ''
  ), $atts));
  return '<audio src="'.$src.'" type="audio/mp3" controls="controls"></audio>';
}
add_shortcode("audio", "audioURL");

// Video shortcode
function videoURL($atts) {
  extract(shortcode_atts(array(
      "src" => ''
  ), $atts));
  return '<video controls="controls" preload="none"><source src="'.$src.'" type="video/mp4" /></video>';
}
add_shortcode("video", "videoURL");

// Customize the 'insert into Post' action

add_filter('media_send_to_editor', 'my_filter_iste', 20, 3);

function my_filter_iste($html, $id, $caption, $title, $align, $url, $size, $alt) {
    $attachment = get_post($id); //fetching attachment by $id passed through
    $src = wp_get_attachment_url( $id );
    $videoext = '.mp4';
    $audioext = '.mp3';

    $mime_type = $attachment->post_mime_type; //getting the mime-type

    if ((substr($mime_type, 0, 5) == 'video') || (substr_compare($src, $videoext, strlen($str)-strlen($videoext), strlen($videoext)) === 0)) { //checking mime-type
        $html = '';
    } elseif ((substr($mime_type, 0, 5) == 'audio') || (substr_compare($src, $audioext, strlen($str)-strlen($audioext), strlen($audioext)) === 0)) { //checking mime-type
        $html = '';
    } else {
      $html = '[attachment src="'.$src.'"]';
    }
    return $html; // return new $html
}

and the ‘insert into post’ action will insert a shortcode similar to [attachment src=”URL_to_attachment”] , that returns in frontend the HTML that corresponds to the uploaded file mime type.

CSS3 for IE with PIE

PIE stands for “Progressive Internet Explorer”, and is capable to add support for the most useful, cool CSS3 features, to the old and grumpy internet explorer (6, 7 and 8), and make your life easier.

Look and this page ( http://www.antimath.info/demos/csspie/ ) in internet explorer, … border-radius, box-shadow, background gradient, …good bye images and useless markup, hello PIE.

.element {
   width: 250px;
   height: 150px;
   line-height: 150px;
   font-style: italic;
   text-align: center;

    border: 1px solid #999;
    -webkit-border-radius: 10px;
    -moz-border-radius: 10px;
    border-radius: 10px;

    -webkit-box-shadow: #444 0 0 10px;
    -moz-box-shadow: #444 0 0 10px;
    box-shadow: #444 0 0 10px;

    background: #CCC; /*non-CSS3 browsers will use this*/
    background: -webkit-gradient(linear, 0 0, 0 100%, from(#BEE224) to(#E9F648)); /*old webkit*/
    background: -webkit-linear-gradient(#BEE224, #E9F648); /*new webkit*/
    background: -moz-linear-gradient(#BEE224, #E9F648); /*gecko*/
    background: -ms-linear-gradient(#BEE224, #E9F648); /*IE10 preview*/
    background: -o-linear-gradient(#BEE224, #E9F648); /*opera 11.10+*/
    background: linear-gradient(#BEE224, #E9F648); /*future CSS3 browsers*/
    -pie-background: linear-gradient(#BEE224, #E9F648); /*PIE*/

    behavior: url(pathTo/PIE.htc);
}

CSS3 PIE supports:

  • border-radius
  • box-shadow
  • border-image
  • multiple background images
  • linear-gradient as background image

See more on css3pie.com

WordPress registration form in a regular page

Note: This code is old, and it may not work with the latest versions of WordPress

WordPress provides a function to echo in front end a simple login form (  wp_login_form( $args ) ), but it doesn’t provide a simple way to embed the registration form ( the form displayed in /wp-login.php?action=register ) in a regular page or sidebar.

After some google-ing and trying a few plugins, i decided it is more flexible if i make one myself. In my research to do this I stumble upon this article here which is the base of what i will explain below.

Make your own WordPress registration form:

Step 1

Create a file called ‘registration_form.php’ in your theme in which paste the code below.

<div class="registration-form-wrapper">
<?php
/* the captcha result is stored in session */
session_start();

if( isset( $_POST['svalue'] ) ) {
	if($_POST['svalue'] != $_SESSION['answer']) {
		$matherror = "Wrong math!";
	}
	else {
		$matherror = " ";
	}
}

include('arithmetic_captcha.php');

if(defined('REGISTRATION_ERROR')){
    foreach(unserialize(REGISTRATION_ERROR) as $error){
	echo '<p class="error">'.$error.'</p';
    }
} elseif(defined('REGISTERED_A_USER')){
	echo '<p class="success">Successful registration, an email has been sent to '.REGISTERED_A_USER .'</p>';
}
echo '<p class="error">'. $matherror .'</p>';
?>

  <form id="my-registration-form" method="post" action="<?php echo add_query_arg('do', 'register', get_permalink( $post->ID )); ?>">
    <ul>
	<li>
	    <label for="username">Username</label>
	    <input type="text" id="username" name="user" value=""/>
	</li>
	<li>
	    <label for="email">E-mail</label>
	    <input type="text" id="email" name="email" value="" />
	</li>
	<li>
	    What is the result <strong><?php echo $math;?></strong> ? &nbsp; <input type="text" name="svalue" value="" size="7" />
	</li>
	<li>
	    <input type="submit" value="Register" />
	</li>
    </ul>
  </form>
</div>

This is basically the HTML of the form.

Step 2

Add the ‘register user’ function, which you will find below, to your theme’s ‘functions.php‘ file, ..this will register the user and validate the form.

add_action('template_redirect', 'register_a_user');
function register_a_user(){

  if(isset($_GET['do']) && $_GET['do'] == 'register'):
    $errors = array();
    if(empty($_POST['user']) || empty($_POST['email'])) $errors[] = 'Please enter a user name and e-mail.';

    $user_login = esc_attr($_POST['user']);
    $user_email = esc_attr($_POST['email']);

    $sanitized_user_login = sanitize_user($user_login);
    $user_email = apply_filters('user_registration_email', $user_email);

    if(!is_email($user_email)) $errors[] = 'Invalid e-mail.';
    elseif(email_exists($user_email)) $errors[] = 'This email is already registered.';

    if(empty($sanitized_user_login) || !validate_username($user_login)) $errors[] = 'Invalid user name.';
    elseif(username_exists($sanitized_user_login)) $errors[] = 'User name already exists.';

    if(empty($errors)):
      $user_pass = wp_generate_password();
      $user_id = wp_create_user($sanitized_user_login, $user_pass, $user_email);

      if(!$user_id):
        $errors[] = 'Registration failed';
      else:
        update_user_option($user_id, 'default_password_nag', true, true);
        wp_new_user_notification($user_id, $user_pass);
      endif;
    endif;

    if(!empty($errors)) define('REGISTRATION_ERROR', serialize($errors));
    else define('REGISTERED_A_USER', $user_email);
  endif;
}

Step 3

Create a file called ‘arithmetic_captcha.php‘ which will contain a simple random numbers generator, for a simple ‘math captcha’ to keep the spam away. This simple captcha can be used with other forms as well, …just use the code below and the check made at Step 1.

<?php
session_start();

$nr1 = mt_rand(1,10); //mt_rand($min, $max)
$nr2 = mt_rand(1,10);
if( $nr1 > $nr2 ) {
	$math = "$nr1 - $nr2";
	$_SESSION['answer'] = $nr1 - $nr2;
} else {
	$math = "$nr1 + $nr2";
	$_SESSION['answer'] = $nr1 + $nr2;
}

Step 4

Just include the ‘registration_form.php’ file created at Step 1 in your page template or wherever you want the form to appear.

<?php include('registration_form.php');?>

Or you can just download the files here (wp_registration_form.zip) and include them in your theme.

Simple confirm password or email validation

If you have a form with a ‘confirm password’ field or ‘confirm email’, and you don’t want to use a heavy validation plugin just for a simple confirmation like this, you can always use some simple ‘old school’ javascript and the onblur event, so when the field loses focus triggers the validation function.

<script type="text/javascript">
	function confirmPass() {
		var pass = document.getElementById("pass").value
		var confPass = document.getElementById("c_pass").value
		if(pass != confPass) {
			alert('Wrong confirm password !');
		}
	}
</script>
<form id="form" action="" method="post">
    <label for="pass">Password</label>
    <input type="password" id="pass" class="text" name="your_pass" value=""/>
    <label for="c_pass">Confirm Password</label>
    <input type="password" id="c_pass" class="text" name="your_c_pass" value="" onblur="confirmPass()"/>
</form>

See a demo.

Open flowplayer in fancybox

Flowplayer is a good choice when it comes to embedding videos into websites, …but what about flowplayer in fancybox ?

If you google a bit certainly you’ll find some ideas of how to play a video in flowplayer in fancybox, but by far the most simple one and the one that gives you the control on every option of every movie embedded, is to embed each of your videos in one different page (ex. lets say we have movie1.mp4 and movie2.mp4 then we should have /movie1.html and /movie2.html or if you have just one video then just one page ), and then set the ‘href’ of the link that is supposed to open that video to the URL of the video page, and now when you click on the link it will open the video page in an iframe in the modalbox. To easily understand this see the demo.

Take note of the snippet of code bellow when you set fancybox.

$("#video-link").fancybox({
	'width' : 336,
	'height' : 256,
	'overlayShow' : false,
	'autoScale' : false,
	'transitionIn' : 'none',
	'transitionOut' : 'none',
	'type' : 'iframe' //tweek the other, do not change this;
});

Demo

How to test an optocoupler

An optocoupler or optoisolator, is a device that contains a light-emitting diode (LED) and a photosensor ( photodetector, such as a photoresistor, a photodiode, a phototransistor, …etc ). The purpose of an optocoupler is to transfer signals from one circuit to another yet keep them galvanically isolated.

Here I want to show you how to check if an optocoupler is working. So I’ve chosen one of the most commonly used optocouplers ( PC123 – 4 pins) for the demonstration, but you can use the same principle for all optocouplers ( note: check the datasheet first ).

Step 1pc123

Using the diagram in the right identify the pins; first the anode and cathode of the LED ( in this case pins 1 and 2 ), and then using an ohmmeter set on the ‘X1 Ohm’ domain, measure between pins 1 and 2, and you should get one reading measuring one way and no reading the opposite way (just like you check a diode). If you get a value either way or no value at all, then certainly there is a problem with the LED, and you should find another optocoupler.

Step 2

If the LED is good then we should check the phototransistor, you could measure it with the ohmmeter just like the LED between pins 3 and 4 ( the emitter and collector ), and you should get a high resistance value both ways if the phototransistor is good. If you’ll get no reading at all, is probably because most phototransistors have such high resistance between emitter and collector that the ohmmeter can’t measure; if this is the case you could connect two ohmmeters in series thus increasing the measuring domain; …although i think most don’t have two meters so i recommend the ’empirical’ method, presuming you have a variable DC regulated power supply.

“Empirical” methodOptocoupler test

Connect the ohmmeter ( X1K Ohm or  X10K Ohm ) between emitter and collector ( 3 and 4 ) like this: red probe to collector and black probe to emitter. Now connect a resistor of a few hundred ohms ( ~300 ohms ) in series with the LED anode, after this turn on the power supply and start increasing the voltage from 0 to 2…3 volts, and you should be able to see on the ohmmeter how the output resistance decreases as the input voltage increases and viceversa.

Post type targeting

If you need custom displaying for different registered post types, you can use this trick:

$post_type = get_post_type( $post );
if ( is_single() &&  $post_type == 'your-post-type' ){
	//what to be shown on single 'your-post-type' "page";
} else {
       //what to be shown on every else single post "page";
}

you can use the same method on archive pages, by replacing the is_single() with is_archive(). Like an universal method you can try using,

$post_type = get_post_type( $post );
if ($post_type == 'your-post-type' ){

} else {

}

with same results, but if you want to be sure use the first example.

A more elegant solution is to use WordPress is_singular() function, but there are reported cases in which this would not work, …but is good to have more options from which to choose.

Hover effect on the parent of an anchor tag

It ever happened that you need to apply some CSS style to the parent of a link ( anchor tag <a href=””></a> ), when the link is hovered ?

For example this HTML:

<div>
   <a href="#">Some Link</a>
</div>

you want to apply some styles to the <div> ( some background color for example ), and you can achieve this by using some ugly css selectors, but sure you will stumble upon some cross-browser problems, so you better use some simple jQuery manipulation.

$('a').mouseover(function (){
	$(this).parent().addClass('hover');
}).mouseout(function (){
	$(this).parent().removeClass('hover');
});

and now you can use the .hover class to style the <div>.

WordPress admin panels disappearing

Hi,

I encountered an annoying problem in wordpress admin, suddenly my Pages panel disappeared, I didn’t find the problem, and I needed that panel, so I added it manually, but as soon as i did that, other panels start to disappear. I thought it was an wordpress upgrade problem ( just did an upgrade ), but doing a downgrade didn’t solve it, so I start deactivating plugins, ( i mention i used MagicFields and Gravity forms, and i had 6 magic fields wright panels ), and when i deactivated Gravity forms all was normal, then i googled a bit and found that this is because plugins that use ‘add_object_page‘ function ( Magic Fields use it and Gravity forms as well ) make the Pages panel disappear when are more than 11 panels in the wordpress upper admin panel ( the one with Posts and Pages ), and the only solution is to change the ‘add_object_page‘ function to ‘add_menu_page‘, so i changed it in gravity forms and the Pages panel appeared.

This is not recommended, because the plugins might be upgraded and you have to be careful, but this was the only workaround that worked for me.

Float & margin

Hi,

I am sure you all know this, but i will make a short description anyway. It is about the code below:

<div id="container">
	<img style="display: block; float: left;" src="http://placehold.it/468x60" alt="" />
	<p class="element" style="margin-top: 30px;">
		Sed ut perspiciatis unde omnis ...
	</p>
</div>

an element containing a floated element and a block element wrapping around the float, but you want that the block element to be lower than the floated one, so you set a margin on the block element, but the floated one is pushed by the margin… annoying. ( ex. demo 1 ).  So the simplest solution is to set a padding of 1px on the same direction as the margin on the container.

<div id="container" style="padding-top: 1px;">
	<img style="display: block; float: left;" src="http://placehold.it/468x60" alt="" />
	<p class="element" style="margin-top: 30px;">
		Sed ut perspiciatis unde omnis ...
	</p>
</div>

see it on demo 2 .

WordPress the_date vs. the_time

Hi !

This article is a friendly reminder for those like me, who can’t remember which wordpress function is used when.

Like the article title says is about the_date and the_time , because I wanted to make a post date look something like this:displaying the date on two rows. Like any “partially educated” web developer I wanted to achieve this by using the_date function with different parameters, like this:

<div class="post-date">
	<div class="month"><?php the_date(M) ?></div>
	<div class="day"><?php the_date(d) ?></div>
</div>

and then I discovered that it doesn’t work like I wanted to; the problem is that the second instance of the_date doesn’t work, is returning nothing, therefor just the month, no day … no good.

Lucky for me, I didn’t overload my brain too much trying to understand why is not working, and I gave another try, this time with the_time function, and … voilà ! , worked like a charm.

<div class="post-date">
	<div class="month"><?php the_time(M) ?></div>
	<div class="day"><?php the_time(d) ?></div>
</div>

So keep in mind !

How to add a class to the current slide in jQuery Cycle

I think that every web developer heard about jQuery Cycle plugin, and we all know that is the most simple to use, and the best regarding the options that it has, but that doesn’t mean is bullet proof. In some weird coincidence, I needed a css selector on the current slide ( something like class=”current” ), after I clicked “Inspect element”, I was surprised to find out that Cycle doesn’t have any kind of css selector on the slides ( what looney would need it ) ; so I start searching for a solution,  and that’s how we end up to the snippet of code bellow.

Here is the markup,

<ul id="slideshow">
      <li>
           <img src="path-to-slide1.jpg" width="400" height="300" alt="" />
      </li>
      <li>
           <img src="path-to-slide2.jpg" width="400" height="300" alt="" />
      </li>
     ... etc
 </ul>

and the js,

$('#slideshow').cycle({
     fx: 'fade',
     speed: 'slow',
     timeout: 3000,
     before: function(){
           $(this).parent().find('li.current').removeClass();
     },
      after: function(){
           $(this).addClass('current');
     }
});

I still don’t think this is the best approach to this problem, but it works, and if you know a better way, please leave a comment.

Here you will find a demo, to see it in action.

Checkbox tree with jQuery

Update:

With nothing to do, I remembered the failure with the checkbox tree, and I started re-thinking it. With nothing else on my mind, took me very short time to figure my mistakes; …so now i will update this post and the demo. Of course my opinion about checkboxtree jQuery plugin remains the same, but if you don’t want to use an entire plugin, then you can always use the code here.


Sometime ago I needed an “checkbox tree” ( a nested list with checkboxes in every node ), for options that have sub-options. I decided to write one of my own.

After some try & error, I come up with the following code :

Below is the new improved and corrected code.


(function($){

$('ul#checkboxes input[type="checkbox"]').each (
 function () {
  $(this).bind('click change', function (){
   if($(this).is(':checked')) {
    $(this).siblings('ul').find('input[type="checkbox"]').attr('checked', 'checked');
    $(this).parents('ul').siblings('input[type="checkbox"]').attr('checked', 'checked');
   } else {
    $(this).siblings('ul').find('input[type="checkbox"]').removeAttr('checked', 'checked');
   }
  });
 }
);

})(jQuery);

you can see it in action here. (updated demo, with the new code).

I also found this checkboxtree jQuery plugin . I gave it a try, and worked perfectly, and you just have to write:

$('ul#checkboxes').checkboxTree({ });

and you will have a checkboxtree. This plugin has a lot of options, that you will find on the plugin homepage.

I made a simple demo using the plugin, that you can see it here, but you can see a lot more here.

Ancient babylonian math problem

Last week i was watching a documentary that  i wanted to see for some time. it is about this documentary from BBC, story of maths . If you didn’t see it, i recommend it to you.

The documentary has 4 parts, and i believe that in the first part, “The Language of the Universe”, i saw an interesting problem from the time of babylonians.

Like the most math problems of the time is about areas; the modern math has it’s roots to the desire of man to be able to calculate and store information about distances, surfaces and patterns.

Archaeologists found pieces of clay with inscriptions that are believed to be children homework, one of them captivated my attention, it was something like this, ( please excuse my lack of talent for graphic art ) :

Let say we have a square with four circles inside it ( equal radius circles ), all circles are tangent to the square and to one each other. The square has a given length of it sides, let say x, for algebraic purpose.

The question is, what is the area of one circle ?


You will say, “what is so hard ?

We know the length of the square’s side ( x = any pozitive real number ), so we can extrapolate the circle radius ( r = one circle radius), and then calculate  the surface of the circle.” … simple, huh ?!

r = x / 4

Scirc = πr2 = π(x / 4)2 = πx2 / 16 , for a discrete value, let’s say x = 5,  Scirc = π52 / 16 = 0.5625 * π

The fun part is that the ancient babylonians did not have a precise method to calculate the surface of a circle, this was done by considering the circle a polygon with “many” sides.

Other method is to calculate the area of the square, and then subtract the area of the shapes between the circles and the square’s sides ( approximating those to known geometric figures, 8 triangles and a square ), and divide the result by four … quite laborious and not so precise.

Math sophism on Pythagorean theorem

Good way to keep an idiot busy for a couple of hours.

cos2x + sin2x = 1 is the trigonometric form of the Pythagorean theorem

cos2x + sin2x = 1
cos2x = 1 – sin2x
cos x = (1 – sin2x)1/2
1 + cos x = 1 + (1 – sin2x)1/2
(1 + cos x)2 = (1 + (1 – sin2x)1/2)2
for x = π (pi = 3,14159265…), we have,
(1 – 1)2 = (1 + (1 – 0)1/2)2
0 = (1 + 1)2
0 = 4 //interesting ?!

Clear form fields on focus

If you want to make a form without labels for text inputs or textareas, and instead give the fields default values, you will encounter a little annoying  problem, when you focus the field to write something the default value stays there. To make the default value disappear you will need a few lines of javascript.

$('textarea, input:text').bind('focus click', function(){
		if (this.value == this.defaultValue) {
		this.value = '';
		}
	}).bind('blur', function(){
		if (this.value == '') {
		this.value = this.defaultValue;
		}
	});

Note that this script uses jQuery so in order to work you’ll need to have jQuery installed.

To make all clear here is a demo.

CSS fixed background

Sometimes you will need to make a background image fixed ( not to scroll with the page ), that because you have a very large image that does not repeat, or you want to make something like an watermark, the solution is simple and is around for ages, all you have to do is use the CSS background-attachment property.

Background-attachment supports three values: scroll ( which is default ), fixed and inherit.

In most cases the fixed background is applied to the body element, but can be applied to any HTML element. Without further ado, … the CSS code.

body {
      background-image: url('path/to/background.jpg');
      background-repeat: no-repeat;
      background-attachment: fixed;
      background-position: center;
}

Below is the shorthand version .


body {
      background: url('path/to/background.jpg') no-repeat fixed center;
}

Here you have a demo.