Simple HTML5 placeholders fallback for IE9 and older

I hoped I will never hear about IE9 and its lack of support for the placeholder attribute, … I had high hopes.

I’ve boiled a simple fallback, late in the evening and in a rush, using IE conditional comments for browser detection.

<!--[if IE 8 ]>    <html class="ie8 lt-ie10"> <![endif]-->
<!--[if IE 9 ]>    <html class="ie9 lt-ie10"> <![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--> <html><!--<![endif]-->
$(document).ready(function() {

	// HTML5 placeholders fallback for IE9 and older
	if ($('html').hasClass('lt-ie10')) {

		// add the placeholder text as value
		$('textarea, input:text').each(function() {
			$(this).attr('value', $(this).attr('placeholder'));
		});

		// clear form fields on focus
		$('textarea, input:text').on('focus click', function(){
			if (this.value == this.defaultValue) {
			this.value = '';
			}
		}).on('blur', function(){
			if (this.value == '') {
			this.value = this.defaultValue;
			}
		});
	}

});

Random start cycle

function randomBox(randomItem) {

  randomItem = $(randomItem);

  var random = Math.floor(Math.random() * randomItem.length);

  randomItem.eq(random % randomItem.length).addClass('active');

  function startRand() {

    var current = randomItem.parent().find('.active');

    if ( current.is(':last-child') ) {
      current.removeClass('active');
      current.siblings(':first-child').addClass('active');
    } else {
      current.removeClass('active');
      current.next().addClass('active');
    }

    setTimeout(function(){startRand()}, 2500);
  }

  startRand();
}

randomBox('.list > .item');

CSS target elements by partial class or ID name

This can simply be achieved using attribute selectors.

div[attr^="elem"]

// Matches any “div” with an “attr” attribute that begins with “elem”.

div[attr$="elem"]

// Matches any “div” with an “attr” attribute that ends with “elem”.

div[attr*="elem"]

// Matches any “div” with an “attr” attribute that contains the substring “elem”.

div[attr|='elem']

// Matches any “div” with an “attr” attribute that starts with “elem” and may continue with a dash (ex. “elem-string”).

Ex. target a “form” with the id=”login-[ID]-form” (where [ID] is a generated form ID)

form[id^="login"]
// or
form[id^="login"][id$="form"]
// or
form[id*="login"][id*="-form"]
// or
div[id|='login']

Network cable tester

With two cheap integrated circuits and a few parts from the ‘junkbox’, this very simple and useful circuit, can be put together in just a few hours.
This cable tester, tests all the 8 wires in a network cable in one move, if one of the 8 LEDs does not lit up, it means that the wire corresponding to that LED is faulty.

You need:

  • 1 x 4017 decade counter,
  • 1 x 555 timer,
  • 8 x LEDs,
  • 2 x 8P8C modular connector (RJ45),
  • 8 x 100Ω resistor,
  • 1 x 10KΩ resistor,
  • 1 x 15KΩ resistor,
  • 1 x 4,7µF capacitor.

network-tester

IMG_20150517_173252

IMG_20150517_173313

The yellow LED has no special significance, I only had 7 green LEDs.

CSS propeller

Just for fun!

See demo CSS3 Keyframe Animation Propeller

<html>
  <head>
    <title>CSS3 Propeller</title>
  </head>
  <body>
    <div class="propeller"></div>
  </body>
</html>
.propeller {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  margin: auto;
  
  width: 0px;
  height: 0px;
  border-width: 200px;
  border-style: solid;
  border-color: #fff #00f #fff #00f;
  border-radius: 50%;

  -webkit-animation-duration: 0.2s;
  -moz-animation-duration: 0.2s;
  -o-animation-duration: 0.2s;
  animation-duration: 0.2s;

  -webkit-animation-name: rotateCircle;
  -moz-animation-name: rotateCircle;
  -o-animation-name: rotateCircle;
  animation-name: rotateCircle;

  -webkit-animation-iteration-count: infinite;
  -moz-animation-iteration-count: infinite;
  -o-animation-iteration-count: infinite;
  animation-iteration-count: infinite;

  -webkit-animation-timing-function: linear;
  -moz-animation-timing-function: linear;
  -o-animation-timing-function: linear;
  animation-timing-function: linear;
}

@-webkit-keyframes rotateCircle {
  from {
    transform: rotate(0deg); 
  }

  to {
    transform: rotate(360deg);
  }
}

@-moz-keyframes rotateCircle {
  from {
    transform: rotate(0deg); 
  }

  to {
    transform: rotate(360deg);
  }
}

@-o-keyframes rotateCircle {
  from {
    transform: rotate(0deg); 
  }

  to {
    transform: rotate(360deg);
  }
}

@keyframes rotateCircle {
  from {
    transform: rotate(0deg); 
  }

  to {
    transform: rotate(360deg);
  }
}

More on CSS animations you can find here:
https://developer.mozilla.org/en-US/docs/Web/CSS/animation
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_animations
https://css-tricks.com/almanac/properties/a/animation
https://css-tricks.com/snippets/css/keyframe-animation-syntax

SASS sqrt function

There are times when a method of calculating the square root of a number is needed in SASS; for example calculating the sides of a right triangle, when the length of the hypotenuse is known, or the other way around, for a triangle mixin.

SASS provides us with some basic number operations, and there are libraries which implement more advanced math functions, but I wanted to experiment.

Using Newton’s method algorithm from Wikipedia, transcribed in SCSS scripting, we get the following:

@function sqrt($r) {
  $x0: 1; // initial value
  $solution: false;

  @for $i from 1 through 10 {
    @if abs(2 * $x0) < 0,00000000000001 { // Don't want to divide by a number smaller than this
      $solution: false;
    }

    $x1: $x0 - ($x0 * $x0 - abs($r)) / (2 * $x0) !global;

    @if ( abs($x1 - $x0) / abs($x1)) < 0,0000001 { // 7 digit accuracy is desired
      $solution: true;
    }

    $x0: $x1;
  }

  @if $solution == true {
    // If $r is negative, then the output will be multiplied with <a href="http://en.wikipedia.org/wiki/Imaginary_number">i = √-1</a>
    // (√xy = √x√y) => √-$r = √-1√$r
    @if $r < 0 {
      @return $x1 #{i};
    }
    @else {
      @return $x1;
    }
  }
  @else {
    @return "No solution";
  }
}

Which works, but looks too complicated.

We can simplify it into,

@function sqrt($r) {
  $x0: 1;
  $x1: $x0;

  @for $i from 1 through 10 {
    $x1: $x0 - ($x0 * $x0 - abs($r)) / (2 * $x0);
    $x0: $x1;
  }

  @return $x1;
}

Note: By default SASS computations are done with a precision of 5 decimals, if you need a higher precision use the “–precision N” (where N is the number of decimals) flag when compiling.

Get the closest next or previous integer in a sorted array of integers

// array = sorted array of integers
// val = pivot element
// dir = boolean, if true, returns the previous value

function getVal(array, val, dir) {
  for (var i=0; i < array.length; i++) {
    if (dir == true) {
      if (array[i] > val){
        return array[i-1] || 0;
      }
    } else {
      if (array[i] >= val) {
        return array[i];
      }
    }
  }
}

Example:

array = [0, 5, 7, 9, 22, 27];
pivot = 11;

getVal(array, pivot);        //returns 22
getVal(array, pivot, true);  //returns 9

Threshold voltmeter

threshold-voltmeter

This is not an actual voltmeter, it just “detects” if the input voltage is below or above a certain threshold. The threshold voltage is the breakdown voltage of a Zener diode.

I have seen this in a magazine described as an rudimentary car battery voltage indicator, recently I have used it as a protection circuit, just replaced the red LED with a relay, acting like a switch (closed when the voltage is under the threshold value and open if the voltage is grater).

Prevent inner elements trigger an event on the parent

Method 1
Stop propagation on inner elements before attaching an event on the parent.

$('#parent a').on('click', function(event){
  //stop the event bubbling up to the parent
  event.stopPropagation();
});

$('#parent').on('click', function(event){
  //attach event on the parent
  alert('Parent element clicked!');	
});

Method 2
Check if the event target matches the designated target.

$('#parent').on('click', function(event) {
  if(event.target == event.currentTarget) {
    alert('Parent element clicked!');
  } else {
    alert('Child element clicked!');
  }
});

Method 2.1
Check if the tag name of the event target matches a certain element.

$('#parent').on('click', function(event){
  if(event.target.tagName.toLowerCase() === 'a'){
    alert('Child anchor element clicked!');
  } else {
    alert('Parent element clicked!');
  }
});

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

4 bit relay computer

This is my first 4 bit adder built with nothing more than relays.

4bit-adder-schematic

4bit-adder

The forest of wires on the right are used to set the input values (in the picture Input1 = 0100 (4 in base 10) and Input2 = 0101 (5 in base 10)), and the LEDs on the left are used as output indicators for the SUM (in this picture 1001 (9 in base 10)).

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.

Square wave generator with 7400 series chip

This is a simple and useful oscillator, built, using  just a 7400 chip ( 4 NAND gates ) and very few other components.

7400-square-wave
7400-square-wave-pcb
square-wave-signal

Rudimentary text expander

There are jQuery plugins, like TextExpander, which work well with portions of text wrapped inside a single element (like a ‘<p>’ tag), but when it comes to collapse block elements, the animation is not so smooth.

Here is a very rudimentary (but working) solution for truncating sections of text paragraphs and adding a ‘read more’ button.

<div class="expandable">
    <div class="inner">
        <p>Some text ...</p>
        <p>Some text ...</p>
    </div>
</div>
.expandable .inner {
    overflow: hidden;
}
$('div.expandable > div.inner').each(function(){
	var expadable_height = $(this).height();
	var visible_lines = 42; //the height of the minimum visible lines of text in px
	$(this).css('height', visible_lines); 
	$(this).parent('div.expandable').append('<span class="see-more">See More</span>');
	
	var toggle = 0;
	$(this).siblings('.see-more').click(function(){
		if( toggle == 1 ){
			$(this).siblings('div.inner').animate({height: visible_lines}, 500);
			$(this).text('See More');
			toggle = 0;
		} else {
			$(this).siblings('div.inner').animate({height: expadable_height}, 500);
			$(this).text('See Less');
			toggle = 1;
		}
	});
});

Demo