jQuery bind after ajax load

Sometimes it is needed to add a jQuery event listener to an element that isn’t present in the DOM at the creation of the page but created during runtime or the result of an ajax call.

What doesn’t work is

jQuery(document).ready(function () {
    jQuery('.selector').on({
        click: function  (event){
            event.preventDefault();
            console.log('I work only with existing elements');
        }
    });
});

However, there is a way to achieve that.

jQuery(document).ready(function () {
    jQuery(document).on('click', '.selector', function (event){
        event.preventDefault();
        console.log('I work with a dynamically created elements');
    });
});

JavaScript loop / foreach an object

Coming from PHP I wondered how do to a simple foreach() in JavaScript.

function loopObject($object) {
    for (const [$key, $value] of Object.entries($object)) {
        // dome something
    }
}

Not that once I found the entries function. Why I use the dollar sign $ for the variables? It is a habit and easier to read and it avoids conflicts with language reserved words.

Javascript money format

Number.prototype.moneyformat = function(decPlaces, thouSeparator, decSeparator) {
	var n = this,
	sign = n < 0 ? "-" : "",
	i = parseInt(n = Math.abs(+n || 0).toFixed(decPlaces),10) + "",
	j = (j = i.length) > 3 ? j % 3 : 0;
	return sign + (j ? i.substr(0, j) + thouSeparator : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thouSeparator) + (decPlaces ? decSeparator + Math.abs(n - i).toFixed(decPlaces).slice(2) : "");
};

usage:

var myMoney=3543.75873;
var formatedMoney = myMoney.moneyformat(2,'.',',') + ' EUR';

Javascript get type

Get the type in javascript

var TYPES = {
    'undefined'        : 'undefined',
    'number'           : 'number',
    'boolean'          : 'boolean',
    'string'           : 'string',
    '[object Function]': 'function',
    '[object RegExp]'  : 'regexp',
    '[object Array]'   : 'array',
    '[object Date]'    : 'date',
    '[object Error]'   : 'error'
},
TOSTRING = Object.prototype.toString;

function type(o) {
    return TYPES[typeof o] || TYPES[TOSTRING.call(o)] || (o ? 'object' : 'null');
};

jQuery UI autocomplete mustMatch Ersatz

jQuery UI autocomplete versagt leider, wenn nur Begriffe aus der Liste ausgewählt werden dürfen. Die eingebaute option mustMatch: true funktioniert leider gar nicht. Deshalb eine Funktion, die Abhilfe schafft.

function jQueryUIAutoCompleteMustMatch(input) {
    var found = 0;
    var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( jQuery.trim($(input).val()) ) + "$", "i" );
    jQuery.each($('.ui-autocomplete li'), function(i, val) {
        if(jQuery.trim( $(val).text() ).match( matcher ) ) {
            found = 1;
        }
    });
    if (found) {
        return true;
    }
    else
    {
        $(input).val('');
        return false;
    }
}

Und dann

change: function(event, ui) {
                jQueryUIAutoCompleteMustMatch($(this));
            }

jQuery zoom with all browers

Well all browsers can do the same, except for Firefox. Wired, indeed! However this zoom script works in IE, Firefox,Chrome,Safari.

jQuery(document).ready(function() {
    var currFFZoom = 1;
    var currIEZoom = 100;

    jQuery(".make_greater").click(function(){
        var step;
        //only firefox sux in this case
        if (jQuery.browser.mozilla){
            step = 0.05;
            currFFZoom += step;
            jQuery('.maincontent').css('MozTransform','scale(' + currFFZoom + ','+ currFFZoom + ')');
            jQuery('.maincontent').css('transform-origin','0 0');
        }
        else
        {
            step = 5;
            currIEZoom += step;
            jQuery('body').css('zoom', ' ' + currIEZoom + '%');
        }
    });

    jQuery(".make_smaller").click(function(){
        var step;
        //only firefox sux in this case
        if (jQuery.browser.mozilla){
            step = 0.05;
            currFFZoom -= step;
            jQuery('.maincontent').css('MozTransform','scale(' + currFFZoom + ','+ currFFZoom +')');
            jQuery('.maincontent').css('transform-origin','0 0');
        }
        else
        {
            step = 5;
            currIEZoom -= step;
            jQuery('body').css('zoom', ' ' + currIEZoom + '%');
        }
    });
});
jquery zoom source
jquery zoom

jQuery wait

jQuery.fn.wait = function(time, type) {
    time = time || 1000;
    type = type || "fx";
    return this.queue(type, function() {
        var self = this;
        setTimeout(function() {
            jQuery(self).dequeue();
        }, time);
    });
};
Anwendung:
jQuery(SELECTOR).wait().css('display','block');

Javascript getElmentsByClassName

If not having jquery this could be a solution

<script type="text/javascript">
function getElementsByClassName(classname, node)  {
    if(!node) node = document.getElementsByTagName("body")[0];
    var a = [];
    var re = new RegExp('\\b' + classname + '\\b');
    var els = node.getElementsByTagName("*");
    for(var i=0,j=els.length; i<j; i++){
        if(re.test(els[i].className)){
            a.push(els[i]);
        }
    }
    return a;
}
</script>

Posts Tagged javascript

Archives by Month: