javascript - jQuery function after an AJAX Content load -
when reload page ajax php, can't seem jquery function affects each item in enlarge
class. html:
<!doctype html> <html> <head> <meta charset="utf-8"> <title>gallery</title> <link rel="stylesheet" href="css/gallery.css"/> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"> </script> <script src="js/enlarge.js"></script> <script> function showimage(str) { if (str.length == 0) { document.getelementbyid("image").innerhtml = ""; return; } else { var xmlhttp = new xmlhttprequest(); xmlhttp.onreadystatechange = function () { if (xmlhttp.readystate == 4 && xmlhttp.status == 200) { document.getelementbyid("image").innerhtml = xmlhttp.responsetext; } } xmlhttp.open("get", "info.php?q=" + str, true); xmlhttp.send(); } } </script> </head> <body> <div id="side-nav"> <div class="dropdown"> <select id="categories" onchange="showimage(this.value)"> <option value="all_cat">all</option> <option value="inks">inks</option> </select> </div> <!-- image container --> <div id="image"></div> </form> </body> </html>
php:
<?php $folder = ""; $array = array(); // q parameter url $q = $_request["q"]; $display_image = ""; //switch statement evaluate $q switch ($q) { case "all_cat": $folder = './img_gallery/*'; foreach (glob($folder . '*.*') $filename) { $array[] = $filename; } foreach ($array $image) { if ($array === "") { $display_image = $image; } else { $display_image .= " <img height=\"100\" width=\"100\" class=\"enlarge\" src='$image'/>"; } } break; default: echo "no images"; } // output "no suggestion" if no hint found or output correct values echo $display_image === "" ? "no images" : $display_image;
javascript/jquery:
jquery.noconflict() jquery.imageenlarge = { dsettings: { enlargeby: 4.3, //default increase factor of enlarged image duration: 500, //default duration of animation, in millisec imgopacity: 0.2 //opacify of original image when enlarged image overlays }, zindexcounter: 100, refreshoffsets: function ($window, $target, warpshell) { var $offsets = $target.offset() var winattrs = {x: $window.scrollleft(), y: $window.scrolltop(), w: $window.width(), h: $window.height()} warpshell.attrs.x = $offsets.left //update x position of original image relative page warpshell.attrs.y = $offsets.top warpshell.newattrs.x = winattrs.x + winattrs.w / 2 - warpshell.newattrs.w / 2 warpshell.newattrs.y = winattrs.y + winattrs.h / 2 - warpshell.newattrs.h / 2 if (warpshell.newattrs.x < winattrs.x + 5) { //no space left? warpshell.newattrs.x = winattrs.x + 5 } else if (warpshell.newattrs.x + warpshell.newattrs.w > winattrs.x + winattrs.w) {//no space right? warpshell.newattrs.x = winattrs.x + 5 } if (warpshell.newattrs.y < winattrs.y + 5) { //no space @ top? warpshell.newattrs.y = winattrs.y + 5 } }, enlarge: function ($, $target, options) { var setting = {} //create blank object store combined settings var setting = jquery.extend(setting, this.dsettings, options) var attrs = (options.thumbdimensions) ? {w: options.thumbdimensions[0], h: options.thumbdimensions[1]} : {w: $target.outerwidth(), h: $target.outerheight()} var newattrs = {} newattrs.w = (setting.enlargeto) ? setting.enlargeto : math.round(attrs.w * setting.enlargeby) newattrs.h = (setting.enlargeto) ? math.round(attrs.h * newattrs.w / attrs.w) : math.round(attrs.h * setting.enlargeby) $target.css('cursor', jquery.imageenlarge.cursorcss) if ($target.data('imgshell')) { $target.data('imgshell').$clone.remove() $target.css({opacity: 1}).unbind('click.enlarge') } var $clone = $target.clone().css({position: 'absolute', left: 0, top: 0, visibility: 'hidden', border: '1px solid gray', cursor: 'pointer'}).appendto(document.body) $clone.data('$relatedtarget', $target) //save $target image enlarged image associated $target.data('imgshell', {$clone: $clone, attrs: attrs, newattrs: newattrs}) $target.bind('click.enlarge', function (e) { //action when original image clicked on var $this = $(this).css({opacity: setting.imgopacity}) var imageinfo = $this.data('imgshell') jquery.imageenlarge.refreshoffsets($(window), $this, imageinfo) //refresh offset positions of original , warped images var $clone = imageinfo.$clone $clone.stop().css({zindex: ++jquery.imageenlarge.zindexcounter, left: imageinfo.attrs.x, top: imageinfo.attrs.y, width: imageinfo.attrs.w, height: imageinfo.attrs.h, opacity: 0, visibility: 'visible', display: 'block'}) .animate({opacity: 1, left: imageinfo.newattrs.x, top: imageinfo.newattrs.y, width: imageinfo.newattrs.w, height: imageinfo.newattrs.h}, setting.duration, function () { //callback function after warping complete //none added }) //end animate }) //end click $clone.click(function (e) { //action when enlarged image clicked on var $this = $(this) var imageinfo = $this.data('$relatedtarget').data('imgshell') jquery.imageenlarge.refreshoffsets($(window), $this.data('$relatedtarget'), imageinfo) //refresh offset positions of original , warped images $this.stop().animate({opacity: 0, left: imageinfo.attrs.x, top: imageinfo.attrs.y, width: imageinfo.attrs.w, height: imageinfo.attrs.h}, setting.duration, function () { $this.hide() $this.data('$relatedtarget').css({opacity: 1}) //reveal original image }) //end animate }) //end click } }; jquery.fn.imageenlarge = function (options) { var $ = jquery return this.each(function () { //return jquery obj var $imgref = $(this) if (this.tagname != "img") return true //skip next matched element if (parseint($imgref.css('width')) > 0 && parseint($imgref.css('height')) > 0 || options.thumbdimensions) { //if image has explicit width/height attrs defined jquery.imageenlarge.enlarge($, $imgref, options) } else if (this.complete) { //account ie not firing image.onload jquery.imageenlarge.enlarge($, $imgref, options) } else { $(this).bind('load', function () { jquery.imageenlarge.enlarge($, $imgref, options) }) } }) }; jquery.fn.applymagnifier = function (options) { //dynamic version of imageenlarge() apply enlarge effect image dynamically var $ = jquery return this.each(function () { //return jquery obj var $imgref = $(this) if (this.tagname != "img") return true //skip next matched element }) }; //** following applies enlarge effect images class="enlarge" , optional "data-enlargeby" , "data-enlargeduration" attrs //** looks links attr rel="enlarge[targetimageid]" , makes them togglers image jquery("document").ready(function ($) { var $targets = $('.enlarge') $targets.each(function (i) { var $target = $(this) var options = {} if ($target.attr('data-enlargeto')) options.enlargeto = parsefloat($target.attr('data-enlargeto')) if ($target.attr('data-enlargeby')) options.enlargeby = parsefloat($target.attr('data-enlargeby')) if ($target.attr('data-enlargeduration')) options.duration = parseint($target.attr('data-enlargeduration')) $target.imageenlarge(options) }) var $triggers = $('a[rel^="enlarge["]') $triggers.each(function (i) { var $trigger = $(this) var targetid = $trigger.attr('rel').match(/\[.+\]/)[0].replace(/[\[\]']/g, '') //parse 'id' rel='enlarge[id]' $trigger.data('enlargeimageid', targetid) $trigger.click(function (e) { $('#' + $(this).data('enlargeimageid')).trigger('click.enlarge') e.preventdefault() }) }) })
the ajax call function within html code loads images "image" container. have php respond "class="enlarge"
within img item, query doesn't kick off. have found out because jquery loading when site launched , bindings lost when ajax called. can assist me fixing class="enlarge"
feature works again?
edited code:
function addbehaviour() { var $targets = $('.enlarge'); $targets.each(function (i) { var $target = $(this); var options = {}; if ($target.attr('data-enlargeto')) options.enlargeto = parsefloat($target.attr('data-enlargeto')); if ($target.attr('data-enlargeby')) options.enlargeby = parsefloat($target.attr('data-enlargeby')); if ($target.attr('data-enlargeduration')) options.duration = parseint($target.attr('data-enlargeduration')); $target.imageenlarge(options); }); var $triggers = $('a[rel^="enlarge["]'); $triggers.each(function (i) { var $trigger = $(this); var targetid = $trigger.attr('rel').match(/\[.+\]/)[0].replace(/[\[\]']/g, ''); //parse 'id' rel='enlarge[id]' $trigger.data('enlargeimageid', targetid); $trigger.click(function (e) { $('#' + $(this).data('enlargeimageid')).trigger('click.enlarge'); e.preventdefault(); }); }); } jquery("document").ready(function ($) { addbehaviour(); });
ajax:
<script> function showimage(str) { if (str.length == 0) { document.getelementbyid("image").innerhtml = ""; return; } else { var xmlhttp = new xmlhttprequest(); xmlhttp.onreadystatechange = function () { if (xmlhttp.readystate == 4 && xmlhttp.status == 200) { document.getelementbyid("image").innerhtml = xmlhttp.responsetext; addbehaviour(); } } xmlhttp.open("get", "info.php?q=" + str, true); xmlhttp.send(); } } </script>
answer:
commented out jquery.noconflict();
i suggest moving application of behaviour seperate function, , using on()
, off()
instead of click()
this:
function addbehaviour() { console.log( 'addbehaviour called' ); /* (... other code...) off() removes behaviour if present, on() adds it. way not applied multiple times: */ $trigger.off('click').on('click', function(e) { $('#' + $(this).data('enlargeimageid')).trigger('click.enlarge') e.preventdefault() });
call function 'addbehaviour' on document load:
jquery("document").ready(function($) { //....(your other on document ready code)... console.log( 'document ready' ); addbehaviour(); })
and call 'addbehaviour'every time after data arrived via ajax call can re-apply behaviour.
(assuming part load stuff ajax)
xmlhttp.onreadystatechange = function () { if (xmlhttp.readystate == 4 && xmlhttp.status == 200) { document.getelementbyid("image").innerhtml = xmlhttp.responsetext; // here: (after have manipulated dom) addbehaviour();
} }
Comments
Post a Comment