how to

Automatically add line breaks in SVG text

Add line breaks in SVG text with jQuery, based on a separator. In the example below the separator is plain text <br>.

<div class="svg-container">
  <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <text>
      <tspan x="0" y="0" style="font-family: Helvetica; font-size: 8px;">Lorem ipsum <br> dolor sit amet</tspan>
    </text>
  </svg>
</div>
$('.svg-container').each(function() {
  // line breaks
  $(this).find('text').each(function() {
    if (/<br>/i.test($(this).text())) {
      var tspan = $(this).find('tspan:first-child');
      var tspanX = tspan.attr('x');
      var tspanY = tspan.attr('y');
      var tspanStyle = tspan.attr('style');
      
      tspan.hide();
      
      var lines = $(this).text().split('<br>');
      var lineHeight = parseFloat(tspan.css('fontSize'));
      for (var i = 0; i < lines.length; ++i) {
        $(this).append('<tspan x="'+ tspanX +'" y="'+ (parseFloat(tspanY) + (lineHeight * i)) +'" style="'+ tspanStyle +'">'+ $.trim(lines[i]) +'</tspan>');
      }
    }
  });

  // refresh svg
  $(this).html($(this).html());
});

Using fullPage.js to make a vertical split-screen parallax

fullPage.js, as its author states, is a jQuery plugin which allows you to “create full screen pages fast and simple”.

How about using it to make a split-screen parallax fast and simple ?

First the required HTML structure:

<div id="splitscreen">
  <div class="section">
    <div class="column column-left">Left Side</div>
    <div class="column column-right">Right Side</div>
  </div>
</div>

Then init the fullPage.js, and customize the settings to your taste.

$(document).ready(function() {
  $('#splitscreen').fullpage({
    navigation: false,
    scrollingSpeed: 1000,
  });
});

Now the CSS for the split-screen:

#splitscreen > .section .column-left {
  float: left;
  width: 50%;
  color: #000;
  background: #fff;
}

#splitscreen > .section .column-right {
  float: right;
  width: 50%;
  color: #fff;
  background: #000;
}

#splitscreen > .section .column-left {
  transition: all 1s ease 0s;
  transform: translateY(100%);
  backface-visibility: hidden;
}

#splitscreen > .section .column-right {
  transition: all 1s ease 0s;
  transform: translateY(-100%);
  backface-visibility: hidden;
}

#splitscreen > .section.active {
  z-index: 1;
}

#splitscreen > .section.active .column-left {
  transform: translateY(0);
}

#splitscreen > .section.active .column-right {
  transform: translateY(0);
}

#splitscreen > .section.active~.section .column-left {
  transform: translateY(-100%);
}

#splitscreen > .section.active~.section .column-right {
  transform: translateY(100%);
}

/* prevent fullpage from "scrolling" the page */
#splitscreen {
  transform: translate3d(0px, 0px, 0px) !important;
}

#splitscreen > .section {
  position: absolute;
  top: 0;
  left: 0;
}

Split screen parallax demo.

CSS only slide out menu

Neat trick to toggle the display of something in the page, using only CSS. In this case, a slide out menu.

First we need the HTML:

<input id="menu-toggle" type="checkbox">
<label class="menu-trigger" for="menu-toggle"></label>
<nav id="menu">
  <ul>
    <li>
      <a href="">Menu Item</a>
    </li>
  </ul>
</nav>

Use the “:checked” pseudo-class, to check the state of the menu (open/close).
Hide the checkbox input, as it is not vissually needed, and style the label as a menu button.

#menu {
  width: 100%;
  position: fixed;
  right: -100%; /* move the menu out of the screen */
  top: 0;
  bottom: 0;
  overflow-y: auto;
  transition: all 1s cubic-bezier(0.2, 1, 0.2, 1) 0s;
  z-index: 999;
}

#menu-toggle {
  position: absolute;
  left: 0;
  top: 0;
  opacity: 0;
  visibility: hidden;
}

#menu-toggle:checked ~ #menu {
  right: 0; /* add the menu into the screen */
}

.menu-trigger {
  /* Closed menu style ☰ */
}

#menu-toggle:checked ~ .menu-trigger {
  /* Opened menu style × */
}

Hide popup when clicking outside

//show popup when clicking the trigger
$('#trigger').on('click touch', function(){
  $('#tooltip').show();
});			

//hide it when clicking anywhere else except the popup and the trigger
$(document).on('click touch', function(event) {
  if (!$(event.target).parents().addBack().is('#trigger')) {
    $('#tooltip').hide();
  }
});

// Stop propagation to prevent hiding "#tooltip" when clicking on it
$('#tooltip').on('click touch', function(event) {
  event.stopPropagation();
});

Demo

Prevent bxSlider stop auto

Prevent bxSlider stop auto slides transition, when navigating through slides.

$(document).ready(function(){
	var slider = $('#slideshow').bxSlider({
		auto: true,
		stopAuto: false,
		startSlide: 0
	});
	
	$(document).on('click','.bx-pager-link',function() {
	    slider.stopAuto();
	    slider.startAuto();
	});
});

Slide out hamburger menu

It is known that the slide out menus ( or hamburger menus ) are the best way of making a menu usable for mobile.

This method uses jQuery in order to clone the markup of the desktop version menu, and make it slide out. Check out the demo.

<body>
	<div id="container">
		<div id="header">
			<div id="navigation">
				<ul>
					<li>
						<a href="#">Lorem Ipsum</a>
					</li>
					<li>
						<a href="#">Lorem Ipsum</a>
					</li>
				</ul>
			</div>
			<span id="toggle-menu">Menu</span>
		</div>
	</div>
</body>
$('#navigation').clone().prependTo('body').addClass('mobile-navigation').removeAttr('id');
$('div.mobile-navigation').prepend('<span class="close">Close</span>');

$('#toggle-menu').bind('click touch', function(){
	if( $('div.mobile-navigation').hasClass('open') ){
		$('div.mobile-navigation').animate({width: "0px"}, 300).removeClass('open');
		$('#container').animate({left: "0px"}, 300);
	} else {
		$('div.mobile-navigation').animate({width: "210px"}, 300).addClass('open');
		$('#container').animate({left: "-210px"}, 300);
	}
});

$('div.mobile-navigation span.close').bind('click touch', function(){
	$('div.mobile-navigation').animate({width: "0px"}, 300).removeClass('open');
	$('#container').animate({left: "0px"}, 300);
});
#container {
  position: relative;
  width: 100%;
}

.mobile-navigation {
  width: 0;
  height: 100%;
  overflow: hidden;
  position: fixed;
  right: 0;
  top: 0;
  z-index: 200;
}

Check out demo.

Check if page scroll is at bottom

May seem odd to check if the page scroll is at bottom, but can be useful if you need to hide something or show something else, as in a back to top button for example.

$('#back-to-top').hide();
$(window).scroll(function(){
    if ( document.body.scrollHeight - $(this).scrollTop()  <= $(this).height() ){
        $('#back-to-top').show();
    } else {
        $('#back-to-top').hide();
    }
});

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.

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');

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.

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.

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.