Top 10 Helpful JavaScript Snippets
Top 10

Top 10 Helpful JavaScript Snippets

Maximum breadth or altitude in a set of components is a very practical tool to create columns and rows of equal height and width very easily. Top 10 JavaScript Snippets are given below, please have a look.

1. Maximum height or width

This javascript is extremely useful to build columns of equal width and height and also rows easily:
[code lang=”js”]var getMaxHeight = function ($elms) {
var maxHeight = 0;
$elms.each(function () {
// In some cases you may want to use outerHeight() instead
var height = $(this).height();
if (height > maxHeight) {
maxHeight = height;
}
});
return maxHeight;
};[/code]

Usability:

[code lang=”js”]$(elements).height( getMaxHeight($(elements)) );[/code]

To achieve the max Width, replace entire occurrences of width and height respectively.

demo

2.Date validation

The date records in JavaScript are a lot too easy and generally not adequate for sophisticated date formatting. Even though there are a lot of JS libraries, which create functioning with dates a lot easier, at times you merely want a bit simpler that formalizes from a particular string to a date. Under such situations you can make use of the subsequent script:

[code lang=”js”]function isValidDate(value, userFormat) {
// Set default format if format is not provided
userFormat = userFormat || ‘mm/dd/yyyy’;
// Find custom delimiter by excluding
// month, day and year characters
var delimiter = /[^mdy]/.exec(userFormat)[0];
// Create an array with month, day and year
// so we know the format order by index
var theFormat = userFormat.split(delimiter);
// Create array from user date
var theDate = value.split(delimiter);
function isDate(date, format) {
var m, d, y, i = 0, len = format.length, f;
for (i; i < len; i++) {
f = format[i];
if (/m/.test(f)) m = date[i];
if (/d/.test(f)) d = date[i];
if (/y/.test(f)) y = date[i];
}
return (
m > 0 && m < 13 &&
y && y.length === 4 &&
d > 0 &&
// Check if it’s a valid day of the month
d <= (new Date(y, m, 0)).getDate()
);
}
return isDate(theDate, theFormat);
}[/code]

Usability:

The following will return false because November doesn’t have 31 days.

[code lang=”js”]sValidDate(‘dd-mm-yyyy’, ’31/11/2012′)[/code]
demo

3.Setting Breakpoints

This function is an easy approach to position breadth breakpoints when operating on receptive designs. It is a speedy way to transmit CSS media queries in your JavaScript encrypt as you proceed.
[code lang=”js”]function isBreakPoint(bp) {
// The breakpoints that you set in your css
var bps = [320, 480, 768, 1024];
var w = $(window).width();
var min, max;
for (var i = 0, l = bps.length; i < l; i++) {
if (bps[i] === bp) {
min = bps[i-1] || 0;
max = bps[i];
break;
}
}
return w > min && w <= max;
}[/code]

Usability:

[code lang=”js”]if ( isBreakPoint(320) ) {
// breakpoint at 320 or less
}
if ( isBreakPoint(480) ) {
// breakpoint between 320 and 480
}
…[/code]

demo

4. Highlight Text

There are a lot of jQuery Plugins to emphasize text. HoweverI found this method authoritative, simple to put into practice and modify and it works devoid of any libraries, merely simple JavaScript. The script gives back the creative text with the conditions cloaked in a tag so as to style them with CSS.

[code lang=”js”]function highlight(text, words, tag) {

// Default tag if no tag is provided
tag = tag || ‘span’;

var i, len = words.length, re;
for (i = 0; i < len; i++) {
// Global regex to highlight all matches
re = new RegExp(words[i], ‘g’);
if (re.test(text)) {
text = text.replace(re, ‘<‘+ tag +’ class=”highlight”>$&</’+ tag +’>’);
}
}
return text;
}[/code]

For unhighlight text the code is:

[code lang=”js”]function unhighlight(text, tag) {
// Default tag if no tag is provided
tag = tag || ‘span’;
var re = new RegExp(‘(<‘+ tag +’.+?>|<\/’+ tag +’>)’, ‘g’);
return text.replace(re, ”);
}[/code]

Usability:

[code lang=”js”]$(‘p’).html( highlight(
$(‘p’).html(), // the text
[‘foo’, ‘bar’, ‘baz’, ‘hello world’], // list of words or phrases to highlight
‘strong’ // custom tag
));[/code]

These 2 oddments would create a grand start to put up your own individual text spotlighting plugin.

demo

5. Animated Effects

Straightforward yet influential script to sentient text attributes. It concedes some interesting consequences when joint with CSS3 conversions. This snip is furnished as jQuery connect for simplicity of use:

[code lang=”js”]$.fn.animateText = function(delay, klass) {
var text = this.text();
var letters = text.split(”);
return this.each(function(){
var $this = $(this);
$this.html(text.replace(/./g, ‘<span class=”letter”>$&</span>’));
$this.find(‘span.letter’).each(function(i, el){
setTimeout(function(){ $(el).addClass(klass); }, delay * i);
});
});
};[/code]

Usability:

[code lang=”js”]$(‘p’).animateText(15, ‘foo’);[/code]

demo

6.Fading elements 

JQuery hook up to grow fainter a set of components individually with custom holdup:

[code lang=”js”]$.fn.fadeAll = function (ops) {
var o = $.extend({
delay: 500, // delay between elements
speed: 500, // animation speed
ease: ‘swing’ // other require easing plugin
}, ops);
var $el = this;
for (var i=0, d=0, l=$el.length; i<l; i++, d+=o.delay) {
$el.eq(i).delay(d).fadeIn(o.speed, o.ease);
}
return $el;
}[/code]

Usability:

[code lang=”js”]$(elements).fadeAll({ delay: 300, speed: 300 });[/code]

demo

7. Counting clicks

At times you may want to know as to the number of times the user clicks on a particular element. The most ordinary solution is to produce a counter as a universal variable but by means of jQuery you can avert contaminating the universal range by using data() to hoard the counter.

[code lang=”js”]$(element)
.data(‘counter’, 0) // begin counter at zero
.click(function() {
var counter = $(this).data(‘counter’); // get
$(this).data(‘counter’, counter + 1); // set
// do something else…
});[/code]

demo

8. Embed YouTube 

Practical script to generate implanted YouTube videos from connections with custom parameters. It functions with generally every YouTube link arrangement as it applies a cute merciful regex, however it might not function for every particular case.

[code lang=”js”]function embedYoutube(link, ops) {
var o = $.extend({
width: 480,
height: 320,
params: ”
}, ops);
var id = /\?v\=(\w+)/.exec(link)[1];
return ‘<iframe style=”display: block;”‘+
‘ class=”youtube-video” type=”text/html”‘+
‘ width=”‘ + o.width + ‘” height=”‘ + o.height +
‘ “src=”http://www.youtube.com/embed/’ + id + ‘?’ + o.params +
‘&amp;wmode=transparent” frameborder=”0″ />’;
}[/code]

Usability:

Check out the Youtube API parameters for more info on params.

[code lang=”js”]embedYoutube(
‘https://www.youtube.com/watch?v=JaAWdljhD5o’,
{ params: ‘theme=light&fs=0’ }
);[/code]

demo

9. Reduce text by limiting word 

This javascript is same like excerpt function of WordPress. It lets you to shorten a thread to a specific number of terms and it contributes abbreviation if needed. It operates with text having other aligned tags for instance strong/em/associations.

[code lang=”js”]function excerpt(str, nwords) {
var words = str.split(‘ ‘);
words.splice(nwords, words.length-1);
return words.join(‘ ‘) +
(words.length !== str.split(‘ ‘).length ? ‘&hellip;’ : ”);
}[/code]

demo

10.  Creating active menus

Generate any kind of menu animatedly, like prescribed listings, out of order lists, choose dropdowns etc. It is a very easy script with copious numbers of potential.

[code lang=”js”]function makeMenu(items, tags) {

tags = tags || [‘ul’, ‘li’]; // default tags
var parent = tags[0];
var child = tags[1];
var item, value = ”;
for (var i = 0, l = items.length; i < l; i++) {
item = items[i];
// Separate item and value if value is present
if (/:/.test(item)) {
item = items[i].split(‘:’)[0];
value = items[i].split(‘:’)[1];
}
// Wrap the item in tag
items[i] = ‘<‘+ child +’ ‘+
(value && ‘value=”‘+value+'”‘) +’>’+ // add value if present
item +'</’+ child +’>’;
}
return ‘<‘+ parent +’>’+ items.join(”) +'</’+ parent +’>’;
}[/code]

Usability:

[code lang=”js”]// Dropdown select month
makeMenu(
[‘January:JAN’, ‘February:FEB’, ‘March:MAR’], // item:value
[‘select’, ‘option’]
);
// List of groceries
makeMenu(
[‘Carrots’, ‘Lettuce’, ‘Tomatos’, ‘Milk’],
[‘ol’, ‘li’]
);[/code]

Savita Singh is the author of computergeekblog, She has a superlative knowledge of Graphic and Web designing. She is a part time and award winning tech blogger who loves to write about latest technology, social media and web design. Her blog focuses on creative things of designing and tech, providing professional opinions on designing products, performances and a variety of business.

Please wait...

Subscribe to our newsletter

Want to be notified when our article is published? Enter your email address and name below to be the first to know.