After writing tones of code you’ll get bored to write the same (helper)functions over and over again for each new project. Functions to short tables, scroll to top, detect mouse position, show pop-up boxes and more are very useful on each public project. I’m not giving you optimized code here, instead I’m showing some basic stuff in order to get inspiration! It is better in my opinion not to use jQuery but for the sake of simplicity I’ll use this library here.
At the bottom of this article I referance some great articles with great javascipt helper functions.
Scrolling
This is a function that needs an html element with id scroll-top. This element will appear after you scroll down some pixels, and when you press it the page will scroll to the top. I won’t apply the animation here, which can be achievied by many different methods(link, js animation,toggle css classes).
/*HTML element. You can add an arrow in it*/ <span id="scroll-top" class="hide"></span> /*JAVASCRIPT*/ $(window).on('scroll',function( event ){ var my_scroll = $(window).scrollTop(); if(my_scroll>600){ $('#scroll-top').removeClass('hide'); } else{ $('#scroll-top').addClass('hide'); } }); $('#scroll-top').on('click', function(){ $(window).scrollTop(0); });
Hiding-removing
Here is a function that gives the ability to append an x button inside any element and when is pressed, it clears or hides the parent element and the button itself.
$(".fa-times-circle-o").each(function(){ $(this).on("click", function(){ $(this).parent().addClass("hide"); /*hide the element*/ $(this).parent().remove(); /*or remove the element*/ }); });
Info pop-up
A function that needs two elements. The elem 1 at which when you hover over it the elem 2 appears(like an explementary box). And when you hover off it the box disapears.
/*html like this*/ <span class="note">SSL</span> <span class="note-content hide">Secure Sockets Layer</span> /*JAVASCRIPT you can alternatively apply (on)click event*/ $(".note").each(function(index){ $(this).on("mouseenter mouseleave", function(event){ $(this).next(".note-content").toggleClass("hide"); }); });
Shuffle
This function shuffles an array (or a deck of cards!)
function shuffle(a) { for (let i = a.length; i; i--) { let j = Math.floor(Math.random() * i); [a[i - 1], a[j]] = [a[j], a[i - 1]]; } }
Future events
Like this you can assign events to appearing DOM element after load(maybe AJAX elements)
The class has to be EXACLTY future-element!
$(document).on( "click" , $( ".future-element" ) , function( event ){
var target_class = $(event.target)[0].getAttribute('class');
if(target_class == 'future-element' ){
/*Do stuff*/
}
});
Custom alert
Create a custom alert message. The alert should be position fixed and you can have a full screen black overlay so the user won’t be able to click anywhere on the screen
/*HTML*/ <div id="alert"> <span class="fa .fa-times-circle-o"><span> //To self clear itself <h3 id="alert-header"></h3> <p id="alert-message"></p> </div> /*JS*/ function show_alert( header, message ){ $("#alert-header").html(header); $("#alert-message").html(message); $("#alert").removeClass("hide"); }
Writing
A computer writing like helper.
/*HTML*/ <div id="message"></div> /*JS*/ function write_down(elem, message, speed){ var len = 0; writing = setInterval(function(){ if( message.length > len ){ len+=1; } else{ clearInterval(writing); } $(elem).html(message.substr(0,len)); }, speed); } write_down('#message','Hello world!',500);
Mouse position
Inpect mouse position when it hovers over particular element(s).
function mouse_inspector(elem){ $(elem).on("mousemove",function(e){ var x = e.pageX - this.offsetLeft; var y = e.pageY - this.offsetTop; $(this).html("X Axis : " + x + " Y Axis : " + y); }); } mouse_inspector('#message');
Expanding arrays
Expand the functionality of all arrays with a method that checks if all of their values are the same.
Array.prototype.allValuesSame = function() { for(var i = 1; i < this.length; i++) { if(this[i] !== this[0]) return false; } return true; }
Absolute path
A pure js closure for getting the absolute path of the page.
var getAbsoluteUrl = (function() { var a; return function(url) { if(!a) a = document.createElement('a'); a.href = url; return a.href; }; })(); alert( getAbsoluteUrl('where_to') );
Shorting tables
After a lot of database interaction, I’ve decided to write this function so I can sort big tables by pressing the corresponding column header. I have two helpers, the create_table which helps to re-create the table after sorting and the make_table_sorted function which takes a jQuery selector as argument, and when invoked it makes the particular table sortable.
There are some bugs! If the column is alphanumeric and more especially if one column’s data values start with both letters or numbers!
function create_table(which,cols,rows,data){ for(i=0;i<rows;i+=1){ for(j=0;j<cols;j+=1){ $(which + " tr").eq(i).children().eq(j).text(data[i][j]); } } } function make_table_sorted(which){ var rows = $(which + " tr").length; var data = $(which + " td").length; var cols = $(which + " tr").eq(0).children().length; /*if view has a table rendered*/ if( rows !==0 && data !==0 && cols !==0 ){ var my_data = []; for(var i=0;i<rows;i+=1){ var row_data = []; for(var j=0;j<cols;j+=1){ var return_data = $(which + " tr").eq(i).children().eq(j).text(); row_data.push(return_data); } my_data.push(row_data); } /*get datatype for each columh*/ var col_types = []; var patt = new RegExp(/[^0-9]/); for(var k=0;k<cols;k+=1){ var my_type = patt.test(my_data[1][k]); col_types.push(my_type); } /*event*/ $( which + " th" ).each( function( index ){ var who = index; $(this).on( "click" , function( event ){ $(this).toggleClass('reversed'); var table_headers = my_data.shift(); my_data.sort(function sortFunction(a, b) { if(col_types[who]===false){ a[index] = parseInt(a[index])||a[index]; b[index] = parseInt(b[index])||b[index]; } if (a[index] === b[index]) { return 0; } else { return (a[index] < b[index]) ? -1 : 1; } }); if( $(this).hasClass('reversed') ){ my_data.reverse(); } my_data.unshift(table_headers); create_table(which,cols,rows,my_data); }); }); } }
Check-uncheck
Create a checkbox which checks-unchecks all checkboxes in the page.
$("#check-all").on("change", function(){ $( this ).prop( "checked", function( i, val ) { return !val; }); $( "input[type='checkbox']" ).prop( "checked", function( i, val ) { return !val; }); });
Get url parameters
With this function you can gather all parameters appended in the url.
function get_url_params() { var query_string = {}; var query = window.location.search.substring(1); var vars = query.split("&"); for (var i=0;i<vars.length;i++) { var pair = vars[i].split("="); if (typeof query_string[pair[0]] === "undefined") { query_string[pair[0]] = decodeURIComponent(pair[1]); } else if (typeof query_string[pair[0]] === "string") { var arr = [ query_string[pair[0]],decodeURIComponent(pair[1]) ]; query_string[pair[0]] = arr; } else { query_string[pair[0]].push(decodeURIComponent(pair[1])); } } return query_string; };
Shuffle arrays same manner
With this one, you can shuffle two arrays the same way. They must both have same length. The helper shuffle from above is also used in this function.
function shuffle_arrays_same_manner(array1, array2) { var len = array1.length; var init_arr = []; var arr1 = [], arr2 = []; for(var i=0;i<len;i+=1){ init_arr.push(i); } var init_arr = shuffle(init_arr); for(var j=0;j<len;j+=1){ var rand_index = init_arr[j]; arr1.push(array1[rand_index]); arr2.push(array2[rand_index]); } var a1= [],a2= []; for(var i=0;i<len;i+=1){ a1.push(arr1[i]); a2.push(arr2[i]); } var arrays = [a1,a2]; return arrays; }
More articles
In this amazing article you can find many pure javascript helper functions.( Collection of useful JavaScript functions and patterns )
Here you’ll find another excellent article( 45 Useful JavaScript Tips, Tricks and Best Practices )