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');
    });
});

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');

jquery input title hint

jQuery.fn.inputHints=function() {
    // hides the input display text stored in the title on focus
    // and sets it on blur if the user hasn't changed it.

    // show the display text
    jQuery(this).each(function(i) {
        jQuery(this).val(jQuery(this).attr('title')).addClass('hint');
    });

    // hook up the blur & focus
    return jQuery(this).focus(function() {
        if (jQuery(this).val() == jQuery(this).attr('title')){
            jQuery(this).val('').removeClass('hint');
        }
    }).blur(function() {
        if (jQuery(this).val() === ''){
            jQuery(this).val(jQuery(this).attr('title')).addClass('hint');
        }
    });
};

jQuery(document).ready(function() {
    jQuery('input[title]').inputHints();
});

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>

Jquery IE .html() Error

Ein einfacher html code, der per ajax verändert werden soll.

<div><img src="icons/reddotadd.gif" title="Add Page" id="AddPageTrigger" alt="Add Page" style="border:0; cursor:pointer;" /></div>
$("#AddPageTrigger").text("TEXT hier");

schlägt im IE fehl. Warum? Keine Ahnung, aber was funktioniert ist

$("#AddPageTrigger").parent().text("TEXT hier");

JQuery Ajax cross domain request

If you try to do an ajax request on a different domain. You’ll get nothing. Looking a bit deeper into the request I noticed that the status code isn’t 200 or 403 nor 404 like expected. Nope it is 0. (jquery ajax statusCode 0). This means the browser doesn’t allow a crossdomain request. The easiest way for me to solve this was to create a proxy php script. Now I can send my ajax request to a url on my server while the PHP script does the real request to the other server.

This is the php script

/**
* GetFromHost()
*
* @param string $host
* @param int $port
* @param string $path
* @param string $referer
* @param bool $keepalive
* @return
*/
function GetFromHost($host, $port, $path, $referer,$keepalive=false) {

 $fsocket = fsockopen($host, 80, $errno, $errstr, 30);

 if($fsocket){
 $request =     "GET $path HTTP/1.1\r\n";
 $request .= "Host: $host\r\n";
 $request .= "Referer: $referer\r\n";
 $request .= 'User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.2.1) ';
 $request .= "Gecko/20021204\r\n";
 $request .= 'Accept: text/xml,application/xml,application/xhtml+xml,';
 $request .= 'text/html;q=0.9,text/plain;q=0.8,video/x-mng,image/png,';
 $request .= "image/jpeg,image/gif;q=0.2,text/css,*/*;q=0.1\r\n";
 $request .= "Accept-Language: en-us, en;q=0.50\r\n";
 //$request .= "Accept-Encoding: gzip, deflate, compress;q=0.9\r\n";
 $request .= "Accept-Charset: ISO-8859-1, utf-8;q=0.66, *;q=0.66\r\n";
 if($keepalive==true){
 $request .= "Keep-Alive: 300\r\n";
 $request .= "Connection: keep-alive\r\n";
 }
 else
 {
 $request .= "Connection: close\r\n";
 }
 //$request .= "Content-Type: application/x-www-form-urlencoded\r\n";
 //$request .= "Content-length: ". strlen($data_to_send) ."\r\n";
 $request .= "\r\n";
 //$request .= $data_to_send;

 fputs($fsocket, $request);

 $res ='';
 while(!feof($fsocket)) {
 $res .= fgets($fsocket, 1024);
 }
 fclose($fsocket);

 return $res;

 }
 else
 {
 return false;
 //echo "Fehlgeschlagen: ".$fsocket . $host .':'. $port;
 }

}

$x = GetFromHost("www.example", "80", "/deep/url/kinda/", "");
$x = explode('Content-Type: text/html',$x);
$output = preg_replace('/\s+(\r\n|\r|\n)/', '$1', $x['1']);//remove white space and tabs at the line ends
echo $output;

maybe you have to edit the explode part for server to separate the header fom the real content.

Posts Tagged jquery

Archives by Month: