Skip to content

Instantly share code, notes, and snippets.

@chrdek
Created November 5, 2022 19:29
Show Gist options
  • Save chrdek/3a83ceb3ffc4a2e25b668a63065c6f94 to your computer and use it in GitHub Desktop.
Save chrdek/3a83ceb3ffc4a2e25b668a63065c6f94 to your computer and use it in GitHub Desktop.
Several jquery methods, jquery relevant functionalities for general web development
var filterTable = (function () { //start IIFE ..
return { //filtering parts..
addFilterTextBoxes: function() {
/* IIFE to activate filtering on keypress textboxes on jQuery DataTables columns */
var api = this.api();
// For each column
api
.columns()
.eq(0)
.each(function (colIdx) {
// Set the header cell to contain the input element
var cell = $('.filters th').eq(
$(api.column(colIdx).header()).index()
);
var title = $(cell).text();
$(cell).html('<input class="form-control py-2" type="text" placeholder="' + title + '" style="max-width:100px; max-height:30px; font-size:1rem; border-radius:0.98rem" />');
// On every keypress in this input
$(
'input', //filtering part 1.. [textbox columns]
$('.filters th').eq($(api.column(colIdx).header()).index())
)
.off('keyup change')
.on('change', function (e) {
// Get the search value
$(this).attr('title', $(this).val());
var regexr = '({search})'; //$(this).parents('th').find('select').val();
var cursorPosition = this.selectionStart;
// Search the column for that value
api
.column(colIdx)
.search(
this.value != ''
? regexr.replace('{search}', '(((' + this.value + ')))')
: '',
this.value != '',
this.value == ''
)
.draw(); //filtering part 2.. [row filters on column keypresses]
})
.on('keyup', function (e) {
e.stopPropagation();
$(this).trigger('change');
$(this)
.focus()[0]
.setSelectionRange(cursorPosition, cursorPosition);
})
})
}
}
})(); //end IIFE .. //usage: add initComplete:filterTable.addFilterTextBoxes, to instantiated .DataTable({..}) property
/***********************************************************************/
/* other jQuery dataTables event handling cases */
// Handle event when cell looses focus
$('#example').on('key-blur.dt', function(e, datatable, cell){
// Deselect highlighted row
$(table.row(cell.index().row).node()).removeClass('selected');
});
// Handle key event that hasn't been handled by KeyTable
$('#example').on('key.dt', function(e, datatable, key, cell, originalEvent){
// If ENTER key is pressed
if(key === 13){
// Get highlighted row data
var data = table.row(cell.index().row).data();
// FOR DEMONSTRATION ONLY
$("#example-console").html(data.join(', '));
}
});
/***********************************************************************/
/* jQuery dataTable plugin buttons layout initialization etc [EXAMPLE ONLY] */
// Disable buttons
DataTable.Api.register( ['buttons().disable()', 'button().disable()'], function () {
return this.each( function ( set ) {
set.inst.disable( set.node );
} );
} );
// Button index
DataTable.Api.register( 'button().index()', function () {
var idx = null;
this.each( function ( set ) {
var res = set.inst.index( set.node );
if (res !== null) {
idx = res;
}
} );
return idx;
} );
// Get button nodes
DataTable.Api.registerPlural( 'buttons().nodes()', 'button().node()', function () {
var jq = $();
// jQuery will automatically reduce duplicates to a single entry
$( this.each( function ( set ) {
jq = jq.add( set.inst.node( set.node ) );
} ) );
return jq;
} );
/***********************************************************************/
$(function () {
'use strict'
/* jQuery.ready for js rad extensions using strict evals */
});
/***********************************************************************/
(function ($) {
'use strict'
/* jQuery default cookie-like check for pop-up display with notif.-landing page message */
setTimeout(function () {
if (window.___browserSync___ === undefined && Number(localStorage.getItem('Cookie1:Demo:MessageShowed')) < Date.now()) {
localStorage.setItem('Cookie1:Demo:MessageShowed', (Date.now()) + (15 * 60 * 1000))
// eslint-disable-next-line no-alert
alert('Loaded OK!"demo.js", \nthis file is only created for testing purposes!')
}
}, 1000)
function createSkinBlock(colors, callback, noneSelected) {
/* jQuery generate multicolored selection boxes for theme */
var $block = $('<select />', {
class: noneSelected ? 'custom-select mb-3 border-0' : 'custom-select mb-3 text-light border-0 ' + colors[0].replace(/accent-|navbar-/, 'bg-')
})
if (noneSelected) {
var $default = $('<option />', {
text: 'None Selected'
})
$block.append($default)
}
colors.forEach(function (color) {
var $color = $('<option />', {
class: (typeof color === 'object' ? color.join(' ') : color).replace('navbar-', 'bg-').replace('accent-', 'bg-'),
text: capitalizeFirstLetter((typeof color === 'object' ? color.join(' ') : color).replace(/navbar-|accent-|bg-/, '').replace('-', ' '))
})
$block.append($color)
})
if (callback) {
$block.on('change', callback)
}
return $block
}
})(jQuery)
/***********************************************************************/
$.fn.setgreen = function() {
this.css( "color", "green" );
return this;
}
/* jQuery extend current selector functionality */
$("a").setgreen().addClass("green");
$("a:visited").setgreen().addClass("green");
/***********************************************************************/
(function ($) {
/* same as jQuery extended selector funct. but scope-specific */
$.fn.setgreen = function() {
this.css( "color", "green" );
return this;
};
/* use jQuery.noConflict() to set the jQuery as IIFE parameter */
}(jQuery));
$("a").setgreen().addClass("green");
$("a:visited").setgreen().addClass("green");
/***********************************************************************/
(function($) {
/* jQuery extended selector funct. for links filtering */
$.fn.showLinkLocation = function() {
this.filter( "a" ).each(function() {
var link = $( this );
link.append( " (" + link.attr( "href" ) + ")" );
});
return this;
};
}(jQuery));
// Usage example - filter all links from a website.
$("a").showLinkLocation();
/***********************************************************************/
/* jQuery in-browser test per BOM scope - not for production purpose */
javascript:(function(e,s){e.src=s;e.onload=function(){jQuery.noConflict();console.log('jQuery setup OK')};document.head.appendChild(e);})(document.createElement('script'),'https://code.jquery.com/jquery-latest.min.js')
/***********************************************************************/
/* Most on-loaded function variants to detect that web content is loaded */
// with jQuery
$(document).ready(function(){ /* ... */ });
// shorter jQuery version
$(function(){ /* ... */ });
// without jQuery (doesn't work in older IEs)
document.addEventListener('DOMContentLoaded', function(){
// your code goes here
}, false);
// and here's the trick (works everywhere)
function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}
// use like
r(function(){
alert('DOM Ready!');
});
//Firefox, Chrome, IE9/8
document.onreadystatechange = function () {
var state = document.readyState;
if (state == 'interactive') {
init(); console.log("DOM loading");
} else if (state == 'complete') {
initOnCompleteLoad(); console.log("DOM loaded");
}
}​;
//IIFE for onready-loaded DOM (IE9+ support)
(function(fn){var d=document;(d.readyState=='loading')?d.addEventListener('DOMContentLoaded',fn):fn();})(function(){
//add your code here when DOM is avail..
});
/***********************************************************************/
function init($) {
/* IIFE alternative with jQuery */
// your code here..
}
init(jQuery);
/***********************************************************************/
var href_val1 = { id:10, value: { href:true, color:"red" } };
var href_val2 = { id:20, value: { href:false },test:true };
/* Merge the contents of two or more objects with jQuery */
$.extend(href_val1, href_val2); //shallow object copy => { id:20, value:{ href:true, color:"red" }, test:true }
$.extend(true, href_val1, href_val2); //deep(recursive) object copy => { id:20, value:{ href:false,color:"red" }, test:true }
/***********************************************************************/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment