Check whether a function exists

1
2
3
if(typeof functionName == 'function') {
/* Your code here */
}
Reference:

Validation using RegExp

Example, to validate a Year:

1
2
3
4
5
var year = 2012;
var myRegex = /^\d{4}$/;
if(myRegex.test(year)) {
alert('Is a valid year');
}

/^ indicate a beginning of the pattern
$/ indicate an ending of the pattern
\d refer to integer
{4} exactly 4 occurance must matched

Reference:

Get total row in a table

1
var totalRows = document.getElementById('tableId').getElementsByTagName('tr').length;
Reference:

Replace text with submatch (parenthesis)

Change a text abc_123 to abc_321

1
2
3
var str = "abc_123";
var new_str = str.replace(/([A-Za-z]+)_\d+/, "$1_321");
document.write(new_str); // abc_321

OR using callback function

1
2
3
4
5
6
var str = "abc_efg";
var new_str = str.replace(/([A-Za-z]+)_([A-Za-z]+)/, function(s, p1, p2) {
// p1 refer to first submatch (i.e. abc), p2 refer to second submatch (i.e. efg)
return [p1, p2].join('-');
});
document.write(new_str); // abc-efg
  • [A-Za-z] - only match alphabet excluding underscore (_)
  • (.....) - keep the text inside the parenthesis into a variable ($1 in this case as it is the first parenthesis, if second then use $2)
  • \d - match only integer
  • + - one or more occurance
References:

Change element’s ID

1
document.getElementById('originalId').id = "newId";
Reference:

For each row in table

1
2
3
4
5
6
7
8
9
var rows = document.getElementById('tableName').rows;
for(rowIndex in rows) {
if(/^\d+$/.test(rowIndex)) {
/*
Your code here, accessed by rows[rowIndex]
i.e. rows[rowIndex].id = "resetNewId";
*/
}
}

NOTE
if(/^\d+$/.test(rowIndex)) is to get only the integer index, because in document.getElementById('tableName').rows there are extra 3 attributes: length, item and namedItem. I just want to ignore this 3 attributes. Since the indexes are all integer, so I use regular expression to filter it.

Reference:

Remove DOM element attribute

1
document.getElementById('elementId').removeAttribute('class');
Reference:

Binding event on future (i.e. add row) using jQuery

If you have an Add Row function, the normal binding doesn’t affected. i.e.

1
2
3
4
5
6
$(function() {
$('.row-div').click(function() {
// This doesn't work
alert('added a new row');
});
});

The example above doesn’t work because it already binded when the page loaded, thus the elements after added doesn’t bind. In order for this to work, use delegate

1
2
3
4
5
6
$(function() {
$('.parent-element').delegate('.row-div', 'click', function() {
// This work
alert('added a new row');
});
});
Reference:

Disable: This cannot be done by disabled attribute

1
2
3
4
5
6
$(function() {
$('a#hyperlink').click(function (e) {
// To avoid its default behavior
e.preventDefault();
});
});

Resume: There is no way to resume this, but you can hack on it.

1
2
3
4
5
$(function() {
$('a#hyperlink').click(function() {
window.location.href = $(this).attr('href');
});
});
References:

Select second child element using jQuery

1
2
3
4
<div id="main-div">
<div>Some text here</div>
<div>Some <em>description</em> here</div>
</div>

Let say you want to access the second div

1
2
var contentHtml = $('div#main-div').children().eq(1).html();
alert(contentHtml);

Output will be:

1
Some <em>description</em> here

Note: eq(1) the digit inside the eq is refer to index which is start with 0

Reference:

Remove all inside a DOM element using jQuery

1
2
3
4
5
// Easiest way
$('#foo').html('');

// Other way
$('#foo').empty();
References:

Access the content of style using jQuery

1
2
3
4
5
// Set the height value to 100px
$('#foo').css('height', '100px');

// Get the height value
var height = $('#foo').css('height');
Reference:

Select elements with :not operator using jQuery

Let say we have an html

1
2
3
4
5
6
7
<ul>
<li class="foo">I don't want this</li>
<li class="bar">I don't want this as well</li>
<li>I just want this</li>
<li>this</li>
<li>and this</li>
</ul>

In jQuery

1
2
3
4
5
$(function() {
$('ul li:not([class=foo]):not([class=bar])').each(function(index) {
// do something here
});
});
Reference:

Store $.ajax result to global variable

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function foo(arg1, arg2) {
var bar;

$.ajax({
type: 'POST',
url: '/path/to/action.php',
data: {
param1: arg1,
param2: arg2
},
success: function(data) {
bar = data.bar;
},
complete: function(jqXHR, textStatus) {
alert(textStatus);
},
error: function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
},
async: false // force the client to wait
});

return bar;
}

By setting async to false, so it won’t continue to run until the request is completed.

Reference:

Get selected text from dropdown list

1
$('#dropdown :selected').text();
Reference:

jQuery - add a wrapper to element

Initial

1
<div class="inner">Some content</div>

Add a wrapper via jQuery

1
$('.inner').wrapAll($('<div></div>').addClass('outer'));

Page rendered

1
2
3
<div class="outer">
<div class="inner">Some content</div>
</div>
Reference:

Match certain text via RegEx

Example to retrive the element name from HTML text.

1
2
3
4
5
6
var str = '<input class="required" type="text" value="" required="required" placeholder="First Name" name="first_name">'; 
var result = str.match(/name="(\w+)"/);
/*
* result[0] => 'name: "first_name"'
* result[1] => 'first_name'
*/
Reference:

Remove next element

In jQuery

1
$('#foo').next().remove();

In pure JavaScript

1
2
3
4
5
6
// store the DOM object into a variable
var fooObject = document.getElementById('foo');
// store the next object into a variable
var nextElement = fooObject.nextSibling;
// access the parent element and remove the next element by removeChild method
fooObject.parentNode.removeChild(nextElement);
Reference:

Access class variable inside callback function

Example here:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function Foo() {
this.username = 'mr foo';

this.loadSomeDataFromServer = function(url) {
$.ajax({
url: url,
success: function(data) {
// LOOK AT HERE
var text = 'Dear ' + this.username + '\n';
text += data;

alert(text);
}
});
}
}

You’re not able to get the actual value from this.username, as the word this is refer to the success function, in order to use the variable, create a that variable

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function Foo() {
// LOOK AT HERE
var that = this;

this.username = 'mr foo';

this.loadSomeDataFromServer = function(url) {
$.ajax({
url: url,
success: function(data) {
// NOW YOU SHOULD BE ABLE TO GET THE RIGHT username
var text = 'Dear ' + that.username + '\n';
text += data;

alert(text);
}
});
}
}
Reference:

jQuery ajax request from other domain

There are no error, textStatus is 0, finally I solved it using jsonp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
$.ajax({
url: 'http://otherdomain.com/api.php',
type: 'GET',
dataType: 'jsonp', // <----- IMPORTANT
data: {
param1: 'foo',
param2: 'bar'
},
success: function(data) {
console.log(data);
},
complete: function(jqXHR, textStatus) {
alert(textStatus);
},
error: function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
Reference:

jQuery check if method exists

1
2
3
4
// check before use it
if (!!$.prototype.functionName) {
$('#dom-id').functionName();
}
Reference:

Trigger dropdown on change event by jQuery

1
$('#dropdown').change();
Reference:

jQuery check is dropdown contain a value

1
2
3
if ($('#dropdown > option[value="foo"]').length > 0) {
alert('The dropdown menu contains a "Foo" value');
}
Reference:

Get image width & height

1
2
3
4
5
6
7
8
9
10
11
function getImgSize(imgSrc) {
var newImg = new Image();

newImg.onload = function() {
var height = newImg.height;
var width = newImg.width;
console.log('The image size is '+width+' x '+height);
}

newImg.src = imgSrc; // this must be done AFTER setting onload
}
Reference:

Prepend zero in front like sprintf in PHP

i.e. get the result like sprintf('%03d' 3)

1
2
3
var someInteger = 3;
// add 3 '0' in front of it, then get the last 3 characters
('0' + someInteger).slice(-3);
Reference:

Clear file input element with jQuery

1
2
$('#myfile').wrap('<form>').closest('form').get(0).reset();
$('#myfile').unwrap();
Reference:

delegate & datepicker on text field

1
2
3
4
5
$('#wrapper').delegate('#birthday', 'focusin', function() {
$(this).datepicker({
dateFormat: 'yy-mm-dd'
});
});
Reference:

Get query string

1
2
3
4
5
function queryString(key) {  
return unescape(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + escape(key).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1"));
}

var token = queryString('token');
Reference:

Trigger window resize event on page load

1
$(window).trigger('resize');
Reference:

jQuery where condition

e.g.

1
2
3
4
var arr = [
{ a: 'abc', b: 'efg', c: 'hij' },
{ a: 'klm', b: 'nop', c: 'qrs' }
]

Now want to find the json which contain a attr is klm

1
2
3
filtered = jQuery.grep(arr, function(e) {
return e.a == 'klm';
});

The result will be

1
[{ a: 'klm', b: 'nop', c: 'qrs' }]
Reference:

DataTable

Reload table with new params

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
function getFilters() {
let data = {
q: $('#q').val(),
};
let status = $('#status').select2('val');
if (status) {
data.status = status;
}
return data;
}

...

'ajax': {
'url': '/path/to/data-table',
'type': 'GET',
'data': function (d) {
Object.assign(d, getFilters());
return d;
},
'beforeSend': function (request) {
},
'error': function () {
}
},

Must use function (d) { ... return d; }

Reference:

Bootstrap 2

Autocomplete with Ajax

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$(function() {
$('#textboxid').typeahead({
minLength: 1,
source: function(query, process) {
return $.getJSON('/path/to/ajax/source', {query: query}, function(data) {
var compiledData = [];
$.each(data, function() {
compiledData.push(this.name);
});
return process(compiledData);
});
},
});
});

Where the data source is

1
2
3
4
5
6
[
{'id': 1, 'name': 'Foo'},
{'id': 2, 'name': 'Bar'},
{'id': 3, 'name': 'FooBar'},
...
]
Reference:

Bootstrap 3

Callback event on navbar show/hide

1
2
3
4
5
6
$('.navbar-collapse').on('shown.bs.collapse', function() {
alert('shown');
});
$('.navbar-collapse').on('hidden.bs.collapse', function() {
alert('hidden');
});

There are 4 events

1
2
3
4
show.bs.collapse
shown.bs.collapse
hide.bs.collapse
hidden.bs.collapse
Reference:

Bootstrap 4

Multi-modal not scrollable

When open 1st modal, it’s scrollable;
When open 2nd modal, it’s scrollable;
When close the 2nd modal, the 1st modal become not scrollable.

Here’s the fix

1
2
3
4
5
$('body').on('hidden.bs.modal', '.modal', function (e) {
if ($('.modal:visible').length) {
$('body').addClass('modal-open');
}
});
Reference:

CK editor

Remove the control at the bottom bar (i.e. body)

1
CKEDITOR.config.removePlugins = 'elementspath';
Reference:

Configure toolbar

1
2
3
4
5
CKEDITOR.config.toolbar =
[
{ name: 'basicstyles', items : [ 'Bold','Italic','Underline' ] },
{ name: 'paragraph', items : [ 'NumberedList','BulletedList' ] }
]
Reference:

Edit html source code

1
2
3
4
5
CKEDITOR.config.toolbar =
[
...
{ name: 'document', items : [ 'Source' ] }
]

tinyMCE

Add in custom button with input textbox

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
tinymce.init({
toolbar1: 'undo redo .... insertcontent',
setup: function (editor) {
editor.addButton('insertcontent', {
tooltip: 'Insert content',
text: 'Content',
icon: false,
onclick: function (e) {
editor.windowManager.open({
title: 'Insert Content',
body: [
{ type: 'textbox',
size: 150,
height: '100px',
name: 'content',
label: 'Content'
}
],
onsubmit: function(e) {
tinyMCE.activeEditor.insertContent(e.data.content);
}
});
}
});
},
});

Gulp

Elixir copy files except some files

Copy all js files except for app.js & bootstrap.js

1
mix.copy(['resources/assets/js/*.js', '!resources/assets/js/app.js', '!resources/assets/js/bootstrap.js'], 'public/assets/js');
Reference: