Quick and simple jQuery accordion

A simple jQuery snippet for those times when you don’t need an entire plugin, but just something quick, and on the spot.

<ul class="accordion">
	<li>
		<div class="heading">Lorem ipsum dolor</div>
		<div class="content">
			Lorem ipsum dolor sit amet...
		</div>
	</li>
</ul>
//accordion
$('.accordion .content').hide();

$('.accordion .heading').click(function(){
	$(this).siblings('.content').slideToggle('fast');
	$(this).parent().toggleClass('active');
	$(this).parent().siblings().children('.content:visible').slideUp('fast');
	$(this).parent().siblings().children('.content:visible').parent().removeClass('active');
});

See demo here.

1bit half adder with one relay

With just one double relay, you can make an adder capable of performing 1bit additions:

0 + 0 = 0
0 + 1 = 1
1 + 0 = 1
1 + 1 = 0 ( with Carry = 1 )

1bit-half-adder

The circuit design isn’t mine, I found it with a quick google search.

1bit-relay-adder-1
1bit-relay-adder-2

1bit-half-adder-full-detail

This is the complete schematic of the above circuit.

DIY high power USB car charger

For some time I felt the need of an USB charger in my car, but all the commercial ones I’ve seen haven’t convinced me they are reliable. So I proposed myself to build one which would have to be “virtually indestructible”, stable and safe for the devices I connect to it.

I remembered that I had a LM340KC-5.0 (5V positive regulator in TO-3 case), laying around somewhere, and told myself that this is perfect for the job. After I looked over the datasheet, I did a test circuit, and it performed perfectly.

I bought a telephone outlet to use it as a case, and I mounted two USB receptacles (which I dismembered from an old computer motherboard) instead of the telephone jack, and the LM340 on top of the case.

The USB pins configuration you can find on Wikipedia.

I have also added a green LED to know if is working.

Have fun.

jQuery toggle functions

The toggle() method was deprecated in jQuery 1.8 and removed in 1.9.
In jQuery 1.9 the toggle() method does not toggle between two or more functions on a click event, it just toggles the visibility of an element.

Here is a quick way of replacing it:

var toggle = 0;
$('#toggle-btn').on('click', function(event) {
	event.preventDefault();
	if ( toggle == 1 ){
		// not clicked
		$(this).removeClass('clicked');
		toggle = 0;
	} else {
		// clicked
		$(this).addClass('clicked');
		toggle = 1;
	}
});

or just using a class,

$('#toggle-btn').on('click', function(event) {
	event.preventDefault();
	if ( $(this).hasClass('active') ) {
		$(this).removeClass('active');
	} else {
		$(this).addClass('active');
	}
});

See demo here.

BxSlider slides counter

Update! Scroll to updated code.

Add a slides counter ( current/total ) to bxSlider carousels, using bxSlider callbacks and methods.
You just have to add an html element ( ex. ‘<div id=”slide-counter”></div>’ ), where to show the numbers, and the code below will do the rest.

function insertCount(slide_curr,slide_count){
	$('#slide-counter').html('<strong>'+ (slide_curr + 1) +'</strong>/'+ slide_count);
};

var slider = $('#slideshow').bxSlider({
	auto: true,
	pager: false,
	onSliderLoad: function (){
		var slide_count = slider.getSlideCount();
		var slide_curr = slider.getCurrentSlide();
		insertCount(slide_curr,slide_count);
	},
	onSlideNext: function (){
		var slide_count = slider.getSlideCount();
		var slide_curr = slider.getCurrentSlide();
		insertCount(slide_curr,slide_count);
	},
	onSlidePrev: function (){
		var slide_count = slider.getSlideCount();
		var slide_curr = slider.getCurrentSlide();
		insertCount(slide_curr,slide_count);
	}
});

Because ‘onSlideNext’ and ‘onSlidePrev’ callbacks are executed only before each “Next” or “Prev” slide transition, if you want to use a ‘pager’ for navigating through slides, you’ll need to use the ‘onSlideAfter’ callback.

function insertCount(slide_curr,slide_count){
	$('#slide-counter').html('<strong>'+ (slide_curr + 1) +'</strong>/'+ slide_count);
};

var slider = $('#slideshow').bxSlider({
	auto: true,
	pager: false,
	onSliderLoad: function (){
		var slide_count = slider.getSlideCount();
		var slide_curr = slider.getCurrentSlide();
		insertCount(slide_curr,slide_count);
	},
	onSlideAfter: function (){
		var slide_count = slider.getSlideCount();
		var slide_curr = slider.getCurrentSlide();
		insertCount(slide_curr,slide_count);
	}
});

Here you can find a demo.


Updated code, and demo with the latest BxSlider version.
The old code with the 4.1.2 bxSlider version, throws an error if the “getSlideCount()” public method is called in a callback fuction.

$('#slide-counter').prepend('<strong class="current-index"></strong>/');

var slider = $('#slideshow').bxSlider({
	auto: true,
	onSliderLoad: function (currentIndex){
		$('#slide-counter .current-index').text(currentIndex + 1);
	},
	onSlideBefore: function ($slideElement, oldIndex, newIndex){
		$('#slide-counter .current-index').text(newIndex + 1);
	}
});

$('#slide-counter').append(slider.getSlideCount());

Updated demo

JQuery Cycle pager with leading zeros

Adding leading zeros to Cycle’s pager can sometimes make a big visual difference. Using the pagerAnchorBuilder this can be achieved very simple:

pagerAnchorBuilder: function(idx, slide) {
	if (idx < 10) {
		return '<li><a href="#">0' + (idx+1) + '</a></li>';
	} else {
		return '<li><a href="#">' + (idx+1) + '</a></li>';
	}

WordPress get posts by taxonomy terms

With get_posts() you can do a lot of things, like creating multiple posts loops, retrieve posts by all sorts of criteria, etc.

One of the interesting part comes when you want to create a posts loop with only the posts from certain taxonomy term/terms.

On the codex page of the get_posts function, we find an example, which tells us to rename the ‘category’ argument with our taxonomy name, and it’s value is one of taxonomy’s terms name; but they don’t say anything about multiple terms. Well, it seems like it works if you pass a comma separated string of terms, the question now is how you can get a comma separated string of terms, of the current post, in single-posttype.php.

The get_the_term_list() seems to be just perfect for the job. The problem with this is that it also returns html anchor tags with the terms link; this can be solved with the strip_tags() php function.

$terms = strip_tags( get_the_term_list( $post->ID, 'taxonomy-name', '', ',', '' ) );

$arg = array(
	'numberposts' => 4,
	'orderby' => 'rand',
	'post_type' => 'post-type-name',
	'taxonomy-name' => $terms,
	'post_status' => 'publish'
);
$related_posts = get_posts ( $arg );

This can be a nice way to get random related posts who share same taxonomy terms.

How to test a bipolar transistor

This post refers to how to test a bipolar junction transistor (BJT) with an ohmmeter.

A bipolar transistor has two PN junctions; a PN junction basically behaves as a simple diode. Bipolar transistors come in two types, NPN and PNP, based on how the base of the transistor is doped.

A simple method to see if the transistor is good ( presuming you have just an ohmmeter ), is to use the ohmmeter to test each of the two junctions.

Note: You can use any type of ohmmeter ( analogical or digital )

Set your ohmmeter on the X1 domain, and:

Step1: Connect the red probe to the base(B) of the transistor and the black probe to the emitter(E)

Now we test the PN junction between the base and emitter ( BE ).

Red probe to base and black to emitter.

Step2: Connect the red probe to the base(B) of the transistor and the black probe to the collector(E)
Now we test the PN junction between the base and collector ( BC ).

Red probe to base black to collector.

If you get readings ( higher then 0Ω ) in both cases, then the junctions are good, and because the red probe was connected to the base, means that the transistor is NPN type. ( You should NOT get any readings ( Ω ) with the black probe connected to the base. )

Step3: If you didn’t get readings at Step1 and 2, then move the black probe to base(B), and repeat Step1 and 2

If you get readings, as in steps 1 and 2, but with the black probe connected to the base, and no readings at all with the red probe connected to the base, that means your transistor is also good, but is of PNP type.

Summary:

  • Red probe connected to base, and readings with the black probe connected to both emitter and collector ( one at the time ) => transistor is GOOD and is NPN.
  • Black probe connected to base, and readings with the red probe connected to both emitter and collector ( one at the time ) => transistor is GOOD and is PNP.
  • Both cases above, but no readings ( Ω )  or short-circuit ( 0Ω ), means the transistor is fried.

Change the default throbber in Drupal 7

‘Throbber’ in Drupal is the animated loader ( found at  /misc/throbber.gif ), used to indicate Ajax progress.

If you want to change it evenly across your theme, don’t even think to just replace the ‘/misc/throbber.gif’, instead save your .gif file in your drupal theme, and in your theme’s .css file override drupal’s default CSS rules which style the ‘throbber’. This default CSS can be found ( but not edited ) at ‘/modules/system/system.base.css’, and you just have to copy them to your css file, as shown below.

Keep in mind that ‘throbber.gif’ is in fact a sprite image, which contains two states ( one static, used for idle state, and one animated used for progress ).

Add these in your theme’s .css, and tweak them accordingly to your animated loader :

/* these apply to auto-completing form fields */
html.js input.form-autocomplete {
  background-image: url(path-to-your/loader.gif); /* tweak this according to your gif */
  background-position: 100% 0px; /* tweak this according to your gif */
  background-repeat: no-repeat;
}
html.js input.throbbing {
  background-position: 100% -20px; /* tweak this according to your gif */
}

/* these apply to all ajax progresses */
.ajax-progress {
  display: inline-block;
  *display: inline;
  *zoom: 1;
}
.ajax-progress .throbber {
  background: transparent url(path-to-your/loader.gif) no-repeat 0px 0px; /* tweak this according to your gif */
  float: left;
  height: 20px; /* tweak this according to your gif */
  width: 20px; /* tweak this according to your gif */
  margin: 2px;
}

ECC81 tube radio

I’ve seen a lot of circuits with tubes at low voltage ( max 20V ), so I wanted to experiment with one too,… and what could be more fun to play with than a radio.

I started from a short-wave radio schematic with an ECL82, in which I replaced the ECL82 with a ECC81, which I knew could work at low voltage, and did a little tweaking with the resistors, and coils.

ecc81 radio schematic

L1 = 4 turns, L2 = ~40 turns, L3 = 4turns, in this order on a ferrite stick. ( the fun part is to play with these coils and the variable capacitor, until you hear something ).

Note, that all the values are not strict, tweak them as you see fit.

I’ve also had great results leaving aside L1, and connect the antenna by a 100pF capacitor directly in L2.

Have fun.

Custom select input

Using some jQuery and CSS you can make a cross-browser custom select (dropdown) box.

<div class="select-wrapper">
    <select>
        <option selected="selected" value="1">Option 1</option>
        <option value="2">Option 2</option>
        <option value="3">Option 3</option>
        <option value="4">Option 4</option>
        <option value="5">Option 5</option>
    </select>
</div>
.select-wrapper {
  position: relative;
  width: 215px;
  height: 30px;
  padding: 0 25px 0 0;
  margin: 0;
  border: 1px solid #0D5995;
  overflow: hidden;
  background: url(select-arrow.png) no-repeat right center transparent;
}

select {
  position: absolute;
  left: 0;
  top: 0;
  opacity : 0;
  width: 240px;
  height: 30px;
  padding: 5px 0;
  border: none;
  background: transparent !important;
  -webkit-appearance: none;
}

.select-wrapper span {
  display: block;
  width: 210px;
  height: 30px;
  line-height: 30px;
  padding: 0 0 0 5px;
}
$(document).ready(function() {
  $('select').after('<span>' + $('option:selected', this).text() + '</span>');
  
  $('select').click(function(event) {
    $(this).siblings('span').remove();
    $(this).after('<span>' + $('option:selected', this).text() + '</span>');
  });
})

See the demo.

Remove dashed outline of contextual links in drupal

Annoying dashed border ( which isn’t even a border, is an outline ) appears around the blocks when the “gear” edit link is hovered, but more annoying is when you want to hide some text by the old “text-indent: -9999em” method; then the annoying border stretches all the way to the left ( normally, cause of the ‘-9999em’ ).

A quick way to remove it:

.block.contextual-links-region-active {
	outline: 0;
}

VU-meter with EM84 tube

From all the existing tubes, for sure the most interesting ones are the indicator tubes. From the 1930’s when they were invented, they captivated the eyes with the greenish shimmering light, thus the “Magic Eye” term appeared. The magic eye tubes are just small CRT derivations, usually they also have a triode built-in, as an amplifier.

I had two EM84 laying around for some time ( EM84 are cheap and easy to find, mostly on eBay ), and as I was planning to start an all tube stereo amplifier, it made perfect sense to use magic eye tubes as vu-meters, although EM84 can hardly be called a magic eye, it is more a “magic stripe”.

I started from the circuit in the right picture, and tweaked the values of the anode and grid resistor for a full range of indication.

If the bar is at full range and not moving, try to adjust the 5M potentiometer connected to the grid.

The grid voltage varies between 0 to -22V ( yes, the grid is negative ).

If this circuit is used with a tube amplifier, the “IN” connection in the picture is connected to the anode of the last tube in the amplifier. For an input from another signal source, a preamp stage with a BC171 transistor ( a MOSFET would be a better choice for high input impedance ), is needed.

Here is a picture with the tube and circuit.

em-84-vu-meter

If you don’t have a transformer that outputs 200+ volts, you can get this voltage by building a small DC-DC converter.

To check if the tube is working, first feed the tube with the correct voltages like is described here.

How to move WP database to new domain without sql queries

It happened that i needed to move a wordpress site from one domain to another, all simple, move the files, export the database, make a search and replace for the site’s url and replace it with the new url, then import the DB and all should be fine, …except that all the text widgets were missing. It seems like, the text widgets have serialized data stored in sql, so a blind find/replace messed up the data.

You could use a tool that handles serialized data to do a find/replace, but wordpress makes it easy, and you can add just to lines to the wp-config.php file and you’re done.

define('WP_HOME','http://new-domain-path');
define('WP_SITEURL','http://new-domain-path');

jQuery Cycle with carousel thumbs pager

A nice cycle gallery with thumbnail pictures navigation ( like here http://jquery.malsup.com/cycle/pager3.html ), but to use less space, make the thumbnails pager a carousel. ( see a demo here … note, that this is just to prove the concept, not much attention was given to styles ).

If you have “Prev / Next” controls on the cycle slideshow, then you will stumble upon an annoying situation: When you cycle through the slides with the cycle controls, and reach the last visible thumbnail in carousel, you will have to use the carousel controls to go to the current slide’s thumb; to avoid this i used the cycle’s ‘onPrevNextEvent’ callback to navigate through the carousel in the same time you cycle through the slides.

You will need:

1. jQuery

2. Cycle plugin

3. any jquery carousel you want ( i have used jCarousel lite )

Make the markup as you want, and adapt the jQuery code to it.

$('#slideshow').cycle({
    fx: 'scrollHorz',
    speed: 'fast',
    timeout: 0,
    prev: '#prev',
    next: '#next',
    nowrap: 1,
    pager: '#slide-pager ul',
    pagerAnchorBuilder: function(idx, slide) {
        // return selector string for existing anchor
        return '#slide-pager ul li:eq(' + idx + ') a';
    },
    onPrevNextEvent: function(dir, id, el) {
        if (dir === true) {
		if (id >= 3) { //replace '3' with your number of visible elements
			$('#slide-pager_next').click();
		}
        }
        else {
		if (id >= 1) {
			$('#slide-pager_prev').click();
		}
        }
    }
});

$("#slide-pager").jCarouselLite({
    btnNext: "#slide-pager_next",
    btnPrev: "#slide-pager_prev",
    circular: false,
    visible: 3
});

See the demo here.

Add repeating CSS selectors

Have you ever needed a way to style the elements of a set ( lets say 5 ) individually, but the same rules to be applied to other set ( of 5 ) ?

For example:

<div>
     <h4>first</h4>
     <p>lorem ipsum ...</p>
     <h4>second</h4>
     <h4>third</h4>
     <h4>forth</h4>
     <div>lorem ipsum ...</div>
     <h4>fifth</h4>
     <!-- here end our first set -->
     <h4>first</h4>
     <h4>second</h4>
     <h2>lorem ipsum ...</h2>
     <h4>third</h4>
     <span>lorem ipsum ...</span>
     <h4>forth</h4>
     <h4>fifth</h4>
     <!-- here end our 2nd set -->
</div>

and we want that the first h4 in the first set have same styles as the first h4 in the second and so on, of course our h4’s are not grouped, but they are scattered between other elements, and other h4’s can be added in the future.

If we have a way to distinguish our elements from the other then we can make a short script with jQuery to add classes.

For a group of five css classes that will repeat after a number ( for this example we took, n = 5 ), this means that our h4’s from 1 to 5 will have same classes with the h4’s from 6 to 10, and so on; for this we will use something that in math is called ‘modulo’, basically gives us the remaining of the division of two numbers, and as we can get the index of our element we can see which position has in our set ( in this case of 5 ).

$('div h4').each(function(index) {

	if(index%5 == 0){
		$(this).addClass('first');
	} else if(index%5 == 1){
		$(this).addClass('second');
	} else if(index%5 == 2){
		$(this).addClass('third');
	} else if(index%5 == 3){
		$(this).addClass('forth');
	} else if(index%5 == 4){
		$(this).addClass('fifth');
	}
});

the result would be:

<div>
     <h4 class="first">first</h4>
     <p>lorem ipsum ...</p>
     <h4 class="second">second</h4>
     <h4 class="third">third</h4>
     <h4 class="forth">forth</h4>
     <div>lorem ipsum ...</div>
     <h4 class="fifth">fifth</h4>
     <!-- here end our first set -->
     <h4 class="first">first</h4>
     <h4 class="second">second</h4>
     <h2>lorem ipsum ...</h2>
     <h4 class="third">third</h4>
     <span>lorem ipsum ...</span>
     <h4 class="forth">forth</h4>
     <h4 class="fifth">fifth</h4>
     <!-- here end our 2nd set -->
</div>

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.