Javascript to view image in a new window from a thumbnail? - javascript

This code allows me to click on a thumbnail and see the original in a new window.
Clicking outside of the window does an autoclose.
So far so good.
However if the image is larger than the screen resolution I have to doubleclick on the Title Bar and then right click and "view image" to make it full screen. How can I change the code to prevent the image going off the screen?
<script language="JavaScript" type="text/javascript">
PositionX = 10;
PositionY = 10;
defaultWidth = 600;
defaultHeight = 400;
var AutoClose = true;
function popImage(imageURL,imageTitle){
var imgWin = window.open('','_blank','scrollbars=no,resizable=1,width='+defaultWidth+',height='+defaultHeight+',left='+PositionX+',top='+PositionY);
if( !imgWin ) { return true; } //popup blockers should not cause errors
imgWin.document.write('<html><head><title>'+imageTitle+'<\/title><script type="text\/javascript">\n'+
'function resizeWinTo() {\n'+
'if( !document.images.length ) { document.images[0] = document.layers[0].images[0]; }'+
'var oH = document.images[0].height, oW = document.images[0].width;\n'+
'if( !oH || window.doneAlready ) { return; }\n'+ //in case images are disabled
'window.doneAlready = true;\n'+ //for Safari and Opera
'var x = window; x.resizeTo( oW + 200, oH + 200 );\n'+
'var myW = 0, myH = 0, d = x.document.documentElement, b = x.document.body;\n'+
'if( x.innerWidth ) { myW = x.innerWidth; myH = x.innerHeight; }\n'+
'else if( d && d.clientWidth ) { myW = d.clientWidth; myH = d.clientHeight; }\n'+
'else if( b && b.clientWidth ) { myW = b.clientWidth; myH = b.clientHeight; }\n'+
'if( window.opera && !document.childNodes ) { myW += 16; }\n'+
'x.resizeTo( oW = oW + ( ( oW + 200 ) - myW ), oH = oH + ( (oH + 200 ) - myH ) );\n'+
'var scW = screen.availWidth ? screen.availWidth : screen.width;\n'+
'var scH = screen.availHeight ? screen.availHeight : screen.height;\n'+
'if( !window.opera ) { x.moveTo(Math.round((scW-oW)/2),Math.round((scH-oH)/2)); }\n'+
'}\n'+
'<\/script>'+
'<\/head><body onload="resizeWinTo();"'+(AutoClose?' onblur="self.close();"':'')+'>'+
(document.layers?('<layer left="0" top="0">'):('<div style="position:absolute;left:0px;top:0px;display:table;">'))+
'<img src='+imageURL+' alt="Loading image ..." title="" onload="resizeWinTo();">'+
(document.layers?'<\/layer>':'<\/div>')+'<\/body><\/html>');
imgWin.document.close();
if( imgWin.focus ) { imgWin.focus(); }
return false;
}
</script>
<a href="./mypic.jpg" onclick="return popImage(this.href,'Magnify');">
<img src="./mythumb.jpg" width="500" height="333" border="0"></a>

Related

Drag and Drop Javascript Puzzle

I'm trying to revive some old code I have which is a jigsaw puzzle. It loads images (puzzle pieces) from a folder, randomly places them around the page, and then you drag and drop onto the board. This used to work, but when I tried to use it today, it just throws errors (see below).
HTML:
<body onload="init();" onmousemove="initDrag();" onmouseup="mousePress=false;">
<div id="main">
<div id="inside">
<img src="holder.gif" style="position:absolute; left:500; top:500;" />
</div>
</div>
<div style="position:absolute;top:10px;left:600px;display:none;">
</div>
<p id="pText" class="congrats" style="position:absolute; top:410px; left:475px;"></p>
<p style="position:absolute; top:20px; left:750px;" class="links">hard puzzle | home</p>
</body>
Javascript:
// ARRAY FOR PLACEMENT OF IMAGES: [down, over]
var place = new Array([51,300],[51,432],[51,569],[51,707],[112,300],[112,432],[112,569],[112,707],[199,300],[199,432],[199,569],[199,707],[286,300],[286,432],[286,569],[286,707]);
var displayed = new Array();
var mousePress = false;
var pieces = place.length;
var placed = new Array();
var moveObject;
function init() {
var append = "";
for ( i=0; i<pieces; i++ )
{
append+= '<div onDrag="return false;" unselectable=on id="puzzle" name="puzzle" class="puzzleMain"><img src="img/us/img' + i + '.gif" onmousedown="mousePress=true;moveObject=' + i + ';if(document.all) {offsetX=window.event.offsetX;offsetY=window.event.offsetY;}" onmouseup="mousePress=false;doplace(' + i + ');"></div>';
displayed[i] = 0;
placed[i]=0;
}
document.getElementById("main").innerHTML += append;
document.images[i].onload = rndmImg;
}
function rndmImg() {
x=855;y=50;
do {
do {
displayNext = Math.floor( Math.random()* pieces );
} while( displayed[displayNext] );
document.getElementsByName("puzzle")[displayNext].style.top = y;
document.getElementsByName("puzzle")[displayNext].style.left = x;
document.getElementsByName("puzzle")[displayNext].style.visibility="visible";
displayed[displayNext]=1;
x += document.images[displayNext].width;
if( x >= 900 ) {
y += document.images[displayNext].height;
if ( y>=300 ) { x=0 } else { x=851 }
}
} while(!allDisplayed());
}
function allDisplayed() {
for( z=0; z<displayed.length; z++ ) if( !displayed[z] ) return false;
return true;
}
function lower() {
for( p=0;p<document.getElementsByName("puzzle").length;p++ )
document.getElementsByName("puzzle")[p].style.zIndex = 1;
document.getElementsByName("puzzle")[moveObject].style.zIndex=5;
}
function initDrag(e) {
if(!mousePress)return;
if( document.getElementById("inside").innerHTML != "" ) document.getElementById("inside").innerHTML = "";
lower();
if(document.all) {
mouseX = window.event.clientX - (offsetX);
mouseY = window.event.clientY - (offsetY);
} else {
mouseX = e.clientX - 50;
mouseY = e.clientY - 50;
}
document.getElementsByName("puzzle")[moveObject].style.top=mouseY;
document.getElementsByName("puzzle")[moveObject].style.left=mouseX;
return false;
}
function doplace(index) {
w = document.images[index].width;
h = document.images[index].height;
t = parseInt(document.getElementsByName("puzzle")[index].style.top);
l = parseInt(document.getElementsByName("puzzle")[index].style.left);
if ( ( l >= place[index][1]-(w/2) && l <= place[index][1]+(w/2) ) && ( t >= place[index][0]-(h/2) && t <= place[index][0] + (h/2) ) )
{
document.getElementsByName("puzzle")[index].style.top = place[index][0];
document.getElementsByName("puzzle")[index].style.left = place[index][1];
placed[index] = 1;
if(isComplete())
pText.innerHTML = "Puzzle is complete!";
}
}
function generateArray()
{
append="var place = new Array(";
for( i=0; i<document.getElementsByName("puzzle").length; i++ )
{
t = document.getElementsByName("puzzle")[i].style.pixelTop;
l = document.getElementsByName("puzzle")[i].style.pixelLeft;
append+="[" + t + "," + l + "],";
}
document.forms[0].mArray.value = append;
}
function isComplete()
{
for( q=0;q<placed.length;q++ ) if( !placed[q] )return false;
return true;
}
The error I mostly get is: Uncaught TypeError: Cannot read property 'clientX' of undefined
at initDrag (easy.html:70)
at HTMLBodyElement.onmousemove (easy.html:116)
I have a JSFiddle here. Can anyone shed some light on what the issue might be?
In your code you have onmousemove="initDrag();" so if document.all is falsy then mouseX = e.clientX - 50 would throw a Cannot read property 'clientX' of undefined because you call initDrag() without any argument on mouse move.
Now adays you neither should use document.all nor window.event, both are relicts.

Canvas Greek google fonts not rendering correctly

I assume that this is a bug but if any of you know any work around please let me know.
First of all, the fonts are loaded 101%.
I load Google fonts synchronously
I check with interval to make sure that the font is loaded.
I convert a string into an image (with the below function) by using canvas with success (when
I use English characters)
After rendering a couple English characters I try to render a Greek
word but canvas fall backs to browsers default font.
Firefox doesn't have any issue at all, it works great. The issue is
with Chrome.
Bellow is the function that creates a ribbon-label background image on the top left corner from a given string (PS: this function return imageData that are being merged with other imageData later on):
ImageProcessor.prototype.createLabelImageData = function ( str, size, font, color, backgroundColor, shadowColor, shadowOffsetX, shadowOffsetY, shadowBlur, width, height ) {
this.canvas.width = width || this.settings.width;
this.canvas.height = height || this.settings.height;
this.ctx.clearRect( 0, 0, this.canvas.width, this.canvas.height );
this.ctx.font = "Bold " + ( size || 64 ) + "px " + ( font || "Arial" );
this.ctx.textAlign = "center";
this.ctx.textBaseline = "middle";
var labelHeight = ( size || 64 ) + ( ( size || 64 ) / 4 );
var labelTop = this.canvas.height / 2 - labelHeight / 2;
var labelWidth = this.canvas.width;
var strLen = this.ctx.measureText( str + " " ).width;
var side = Math.sqrt( ( strLen * strLen ) / 2 );
var distance = Math.sqrt( ( side * side ) - ( ( strLen / 2 ) * ( strLen / 2 ) ) );
this.ctx.save();
this.ctx.rotate( -Math.PI / 4 );
this.ctx.translate( -this.canvas.width / 2, -this.canvas.height / 2 + distance );
this.ctx.fillStyle = ( backgroundColor || '#f00' );
this.ctx.beginPath();
this.ctx.moveTo( 0, labelTop );
this.ctx.lineTo( labelWidth, labelTop );
this.ctx.lineTo( labelWidth, labelTop + labelHeight );
this.ctx.lineTo( 0, labelTop + labelHeight );
this.ctx.closePath();
this.ctx.fill();
if ( shadowColor ) {
this.ctx.shadowColor = shadowColor;
this.ctx.shadowOffsetX = ( shadowOffsetX || 0 );
this.ctx.shadowOffsetY = ( shadowOffsetY || 0 );
this.ctx.shadowBlur = ( shadowBlur || size || 64 );
}
this.ctx.fillStyle = ( color || "#fff" );
this.ctx.fillText( str, this.canvas.width / 2, this.canvas.height / 2 );
this.ctx.restore();
var imageData = this.ctx.getImageData( 0, 0, this.canvas.width, this.canvas.height );
this.canvas.width = this.settings.width;
this.canvas.height = this.settings.height;
return imageData;
};
Well after some testing, trial and error and many many hours of reading...
I found out that it doesn't matter if the font has been downloaded when you want to use it in canvas. What worked for me before anything else and any check was to create n*2 div elements (n the number of fonts loaded) and position them outside of the view-port. n*2 because in some I added font-weight:bold.
Bottom line is that the exact font you wish to use in canvas must be:
Preloaded
Create a dummy dom element with innerHTML text of all language
variations (latin & greek in my case).
Keep in mid that you have to create extra elements for the bold variation of the font.
Here is the code that I'm currently using to preload fonts and make sure they are available in canvas.
Vise.prototype.initializeFonts = function ( settings, globalCallback ) {
var that = this; // reference to parent class
/********************************************
********************************************
**
**
** Default settings
**
**
********************************************
********************************************/
var defaults = {
interval: 100,
timeout: 10000,
families: [
'Open+Sans+Condensed:300,300italic,700:latin,greek',
'Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800:latin,greek',
'Roboto+Condensed:300italic,400italic,700italic,400,700,300:latin,greek',
'Roboto:400,100,100italic,300,300italic,400italic,500,500italic,700,700italic,900,900italic:latin,greek'
]
};
// initialization
this.fonts = new Fonts( $.extend( true, defaults, settings ) );
this.fonts.onload = globalCallback;
this.fonts.load();
};
/********************************************
********************************************
**
**
** Fonts class
**
**
********************************************
********************************************/
function Fonts( settings ) {
this.settings = settings;
this.success = [];
this.fail = [];
this.interval = null;
this.elapsedTime = this.settings.interval;
this.fontDetective = new Detector();
}
Fonts.prototype.load = function () {
WebFont.load( {
google: {
families: this.settings.families
}
} );
for ( var i in this.settings.families ) {
var el, elBold;
var familyStr = this.settings.families[ i ];
var family = familyStr.split( ':' )[ 0 ].replace( /[+]/gi, ' ' );
el = document.createElement( "div" );
el.innerHTML = "Font loader Φόρτωμα γραμματοσειράς";
el.style.fontFamily = family;
el.style.color = "#f00";
el.style.position = "fixed";
el.style.zIndex = 9999;
el.style.left = "9999px";
document.body.appendChild( el );
elBold = document.createElement( "div" );
elBold.innerHTML = "Font loader Φόρτωμα γραμματοσειράς";
elBold.style.fontFamily = family;
elBold.style.fontWeight = "bold";
elBold.style.color = "#f00";
elBold.style.position = "fixed";
elBold.style.zIndex = 9999;
elBold.style.left = "9999px";
document.body.appendChild( elBold );
}
this.interval = setInterval( this.areLoaded.bind( this ), this.settings.interval );
};
Fonts.prototype.areLoaded = function () {
for ( var i in this.settings.families ) {
var familyStr = this.settings.families[ i ];
var family = familyStr.split( ':' )[ 0 ].replace( /[+]/gi, ' ' );
var successIdx, failIdx;
if ( this.fontDetective.detect( family ) ) {
successIdx = this.success.indexOf( family );
failIdx = this.fail.indexOf( family );
if ( successIdx === -1 ) {
this.success.push( family );
console.log( "[" + family + "] was successfully loaded." );
}
if ( failIdx > -1 ) {
this.fail.splice( failIdx, 1 );
}
} else {
successIdx = this.success.indexOf( family );
failIdx = this.fail.indexOf( family );
if ( successIdx > -1 ) {
this.success.splice( successIdx, 1 );
}
if ( failIdx === -1 ) {
this.fail.push( family );
}
}
}
if ( this.elapsedTime >= this.settings.timeout ) {
clearInterval( this.interval );
var err = new Error( "Unable to load fonts: " + this.fail.toString() );
this.onload( err, null );
return;
}
if ( this.success.length === this.settings.families.length ) {
clearInterval( this.interval );
this.onload( null, null );
return;
}
this.elapsedTime += this.settings.interval;
};
This is what worked for me in case someone else has the same issue on chrome.
PS: Take a look at fontdetect.js which I use in my code.

How to add a zoom effect in opencart product page?

I am trying to make theme for opencart, I need add zoom effect in the product page and also user can also adjust their setting as per their need. but the zoomer is not working
I added one javascript file in the js folder the codes are:
//////////////////////////////////////////////////////////////////////////////////
// Cloud Zoom V1.0.2
// (c) 2010 by R Cecco. <http://www.professorcloud.com>
// MIT License
//
// Please retain this copyright header in all versions of the software
//////////////////////////////////////////////////////////////////////////////////
(function ($) {
$(document).ready(function () {
$('.product-zoom, .product-zoom-gallery').ProductZoom();
});
function format(str) {
for (var i = 1; i < arguments.length; i++) {
str = str.replace('%' + (i - 1), arguments[i]);
}
return str;
}
function ProductZoom(jWin, opts) {
var sImg = $('img', jWin);
var img1;
var img2;
var zoomDiv = null;
var $mouseTrap = null;
var lens = null;
var $tint = null;
var softFocus = null;
var $ie6Fix = null;
var zoomImage;
var controlTimer = 0;
var cw, ch;
var destU = 0;
var destV = 0;
var currV = 0;
var currU = 0;
var filesLoaded = 0;
var mx,
my;
var ctx = this, zw;
// Display an image loading message. This message gets deleted when the images have loaded and the zoom init function is called.
// We add a small delay before the message is displayed to avoid the message flicking on then off again virtually immediately if the
// images load really fast, e.g. from the cache.
//var ctx = this;
setTimeout(function () {
// <img src="/images/loading.gif"/>
if ($mouseTrap === null) {
var w = jWin.width();
jWin.parent().append(format('<div style="width:%0px;position:absolute;top:75%;left:%1px;text-align:center" class="product-zoom-loading" >Loading...</div>', w / 3, (w / 2) - (w / 6))).find(':last').css('opacity', 0.5);
}
}, 200);
var ie6FixRemove = function () {
if ($ie6Fix !== null) {
$ie6Fix.remove();
$ie6Fix = null;
}
};
// Removes cursor, tint layer, blur layer etc.
this.removeBits = function () {
//$mouseTrap.unbind();
if (lens) {
lens.remove();
lens = null;
}
if ($tint) {
$tint.remove();
$tint = null;
}
if (softFocus) {
softFocus.remove();
softFocus = null;
}
ie6FixRemove();
$('.product-zoom-loading', jWin.parent()).remove();
};
this.destroy = function () {
jWin.data('zoom', null);
if ($mouseTrap) {
$mouseTrap.unbind();
$mouseTrap.remove();
$mouseTrap = null;
}
if (zoomDiv) {
zoomDiv.remove();
zoomDiv = null;
}
//ie6FixRemove();
this.removeBits();
// DON'T FORGET TO REMOVE JQUERY 'DATA' VALUES
};
// This is called when the zoom window has faded out so it can be removed.
this.fadedOut = function () {
if (zoomDiv) {
zoomDiv.remove();
zoomDiv = null;
}
this.removeBits();
//ie6FixRemove();
};
this.controlLoop = function () {
if (lens) {
var x = (mx - sImg.offset().left - (cw * 0.5)) >> 0;
var y = (my - sImg.offset().top - (ch * 0.5)) >> 0;
if (x < 0) {
x = 0;
}
else if (x > (sImg.outerWidth() - cw)) {
x = (sImg.outerWidth() - cw);
}
if (y < 0) {
y = 0;
}
else if (y > (sImg.outerHeight() - ch)) {
y = (sImg.outerHeight() - ch);
}
lens.css({
left: x,
top: y
});
lens.css('background-position', (-x) + 'px ' + (-y) + 'px');
destU = (((x) / sImg.outerWidth()) * zoomImage.width) >> 0;
destV = (((y) / sImg.outerHeight()) * zoomImage.height) >> 0;
currU += (destU - currU) / opts.smoothMove;
currV += (destV - currV) / opts.smoothMove;
zoomDiv.css('background-position', (-(currU >> 0) + 'px ') + (-(currV >> 0) + 'px'));
}
controlTimer = setTimeout(function () {
ctx.controlLoop();
}, 30);
};
this.init2 = function (img, id) {
filesLoaded++;
//console.log(img.src + ' ' + id + ' ' + img.width);
if (id === 1) {
zoomImage = img;
}
//this.images[id] = img;
if (filesLoaded === 2) {
this.init();
}
};
/* Init function start. */
this.init = function () {
// Remove loading message (if present);
$('.product-zoom-loading', jWin.parent()).remove();
/* Add a box (mouseTrap) over the small image to trap mouse events.
It has priority over zoom window to avoid issues with inner zoom.
We need the dummy background image as IE does not trap mouse events on
transparent parts of a div.
*/
$mouseTrap = jWin.parent().append(format("<div class='mousetrap' style='background-image:url(\".\");z-index:199;position:absolute;width:%0px;height:%1px;left:%2px;top:%3px;\'></div>", sImg.outerWidth(), sImg.outerHeight(), 0, 0)).find(':last');
//////////////////////////////////////////////////////////////////////
/* Do as little as possible in mousemove event to prevent slowdown. */
$mouseTrap.bind('mousemove', this, function (event) {
// Just update the mouse position
mx = event.pageX;
my = event.pageY;
});
//////////////////////////////////////////////////////////////////////
$mouseTrap.bind('mouseleave', this, function (event) {
clearTimeout(controlTimer);
//event.data.removeBits();
if(lens) { lens.fadeOut(299); }
if($tint) { $tint.fadeOut(299); }
if(softFocus) { softFocus.fadeOut(299); }
zoomDiv.fadeOut(300, function () {
ctx.fadedOut();
});
return false;
});
//////////////////////////////////////////////////////////////////////
$mouseTrap.bind('mouseenter', this, function (event) {
mx = event.pageX;
my = event.pageY;
zw = event.data;
if (zoomDiv) {
zoomDiv.stop(true, false);
zoomDiv.remove();
}
var xPos = opts.adjustX,
yPos = opts.adjustY;
var siw = sImg.outerWidth();
var sih = sImg.outerHeight();
var w = opts.zoomWidth;
var h = opts.zoomHeight;
if (opts.zoomWidth == 'auto') {
w = siw;
}
if (opts.zoomHeight == 'auto') {
h = sih;
}
//$('#info').text( xPos + ' ' + yPos + ' ' + siw + ' ' + sih );
var appendTo = jWin.parent(); // attach to the wrapper
switch (opts.position) {
case 'top':
yPos -= h; // + opts.adjustY;
break;
case 'right':
xPos += siw; // + opts.adjustX;
break;
case 'bottom':
yPos += sih; // + opts.adjustY;
break;
case 'left':
xPos -= w; // + opts.adjustX;
break;
case 'inside':
w = siw;
h = sih;
break;
// All other values, try and find an id in the dom to attach to.
default:
appendTo = $('#' + opts.position);
// If dom element doesn't exit, just use 'right' position as default.
if (!appendTo.length) {
appendTo = jWin;
xPos += siw; //+ opts.adjustX;
yPos += sih; // + opts.adjustY;
} else {
w = appendTo.innerWidth();
h = appendTo.innerHeight();
}
}
zoomDiv = appendTo.append(format('<div id="product-zoom-big" class="product-zoom-big" style="display:none;position:absolute;left:%0px;top:-5px;width:395px;height:310px;background-image:url(\'%4\');z-index:99;"></div>', xPos, yPos, w, h, zoomImage.src)).find(':last');
// Add the title from title tag.
if (sImg.attr('title') && opts.showTitle) {
zoomDiv.append(format('<div class="product-zoom-title">%0</div>', sImg.attr('title'))).find(':last').css('opacity', opts.titleOpacity);
}
// Fix ie6 select elements wrong z-index bug. Placing an iFrame over the select element solves the issue...
if ($.browser.msie && $.browser.version < 7) {
$ie6Fix = $('<iframe frameborder="0" src="#"></iframe>').css({
position: "absolute",
left: xPos,
top: yPos,
zIndex: 99,
width: w,
height: h
}).insertBefore(zoomDiv);
}
zoomDiv.fadeIn(500);
if (lens) {
lens.remove();
lens = null;
} /* Work out size of cursor */
cw = (sImg.outerWidth() / zoomImage.width) * zoomDiv.width();
ch = (sImg.outerHeight() / zoomImage.height) * zoomDiv.height();
// Attach mouse, initially invisible to prevent first frame glitch
lens = jWin.append(format("<div class = 'product-zoom-lens' style='display:none;z-index:98;position:absolute;width:%0px;height:%1px;'></div>", cw, ch)).find(':last');
$mouseTrap.css('cursor', lens.css('cursor'));
var noTrans = false;
// Init tint layer if needed. (Not relevant if using inside mode)
if (opts.tint) {
lens.css('background', 'url("' + sImg.attr('src') + '")');
$tint = jWin.append(format('<div style="display:none;position:absolute; left:0px; top:0px; width:%0px; height:%1px; background-color:%2;" />', sImg.outerWidth(), sImg.outerHeight(), opts.tint)).find(':last');
$tint.css('opacity', opts.tintOpacity);
noTrans = true;
$tint.fadeIn(500);
}
if (opts.softFocus) {
lens.css('background', 'url("' + sImg.attr('src') + '")');
softFocus = jWin.append(format('<div style="position:absolute;display:none;top:2px; left:2px; width:%0px; height:%1px;" />', sImg.outerWidth() - 2, sImg.outerHeight() - 2, opts.tint)).find(':last');
softFocus.css('background', 'url("' + sImg.attr('src') + '")');
softFocus.css('opacity', 0.5);
noTrans = true;
softFocus.fadeIn(500);
}
if (!noTrans) {
lens.css('opacity', opts.lensOpacity);
}
if ( opts.position !== 'inside' ) { lens.fadeIn(500); }
// Start processing.
zw.controlLoop();
return; // Don't return false here otherwise opera will not detect change of the mouse pointer type.
});
};
img1 = new Image();
$(img1).load(function () {
ctx.init2(this, 0);
});
img1.src = sImg.attr('src');
img2 = new Image();
$(img2).load(function () {
ctx.init2(this, 1);
});
img2.src = jWin.attr('href');
}
$.fn.ProductZoom = function (options) {
// IE6 background image flicker fix
try {
document.execCommand("BackgroundImageCache", false, true);
} catch (e) {}
this.each(function () {
var relOpts, opts;
// Hmm...eval...slap on wrist.
eval('var a = {' + $(this).attr('rel') + '}');
relOpts = a;
if ($(this).is('.product-zoom')) {
$(this).css({
'position': 'relative',
'display': 'block'
});
$('img', $(this)).css({
'display': 'block'
});
// Wrap an outer div around the link so we can attach things without them becoming part of the link.
// But not if wrap already exists.
if ($(this).parent().attr('id') != 'wrap') {
$(this).wrap('<div id="wrap" style="top:0px;z-index:199;position:relative;"></div>');
}
opts = $.extend({}, $.fn.ProductZoom.defaults, options);
opts = $.extend({}, opts, relOpts);
$(this).data('zoom', new ProductZoom($(this), opts));
} else if ($(this).is('.product-zoom-gallery')) {
opts = $.extend({}, relOpts, options);
$(this).data('relOpts', opts);
$(this).bind('click', $(this), function (event) {
var data = event.data.data('relOpts');
// Destroy the previous zoom
$('#' + data.useZoom).data('zoom').destroy();
// Change the biglink to point to the new big image.
$('#' + data.useZoom).attr('href', event.data.attr('href'));
// Change the small image to point to the new small image.
$('#' + data.useZoom + ' img').attr('src', event.data.data('relOpts').smallImage);
// Init a new zoom with the new images.
$('#' + event.data.data('relOpts').useZoom).ProductZoom();
return false;
});
}
});
return this;
};
$.fn.ProductZoom.defaults = {
zoomWidth: 'auto',
zoomHeight: 'auto',
position: 'right',
tint: false,
tintOpacity: 0.5,
lensOpacity: 0.5,
softFocus: false,
smoothMove: 3,
showTitle: true,
titleOpacity: 0.5,
adjustX: 0,
adjustY: 0
};
})(jQuery);
and then added few codes in the product.tpl file
<script type="text/javascript" src="catalog/view/theme/mytheme/js/product-zoom.js"></script>
<div class="product-info">
<?php if ($thumb || $images) { ?>
<div class="left">
<?php if ($thumb) { ?>
<div class="image"><img src="<?php echo $thumb; ?>" title="<?php echo $heading_title; ?>" alt="<?php echo $heading_title; ?>" id="image" /></div>
<?php } ?>
<?php if ($images) { ?>
<div class="image-additional">
<img src="<?php echo $thumb1; ?>" alt="<?php echo $heading_title; ?>" title="<?php echo $heading_title; ?>"/>
<?php foreach ($images as $image) { ?>
<img src="<?php echo $image['thumb1']; ?>" title="<?php echo $heading_title; ?>" alt="<?php echo $heading_title; ?>" />
<?php } ?>
</div>
<?php } ?>
</div>
Try this
Add this js file
//////////////////////////////////////////////////////////////////////////////////
// Cloud Zoom V1.0.2
// (c) 2010 by R Cecco. <http://www.professorcloud.com>
// MIT License
//
// Please retain this copyright header in all versions of the software
//////////////////////////////////////////////////////////////////////////////////
(function ($) {
$(document).ready(function () {
$('.cloud-zoom, .cloud-zoom-gallery').CloudZoom();
});
function format(str) {
for (var i = 1; i < arguments.length; i++) {
str = str.replace('%' + (i - 1), arguments[i]);
}
return str;
}
function CloudZoom(jWin, opts) {
var sImg = $('img', jWin);
var img1;
var img2;
var zoomDiv = null;
var $mouseTrap = null;
var lens = null;
var $tint = null;
var softFocus = null;
var $ie6Fix = null;
var zoomImage;
var controlTimer = 0;
var cw, ch;
var destU = 0;
var destV = 0;
var currV = 0;
var currU = 0;
var filesLoaded = 0;
var mx,
my;
var ctx = this, zw;
// Display an image loading message. This message gets deleted when the images have loaded and the zoom init function is called.
// We add a small delay before the message is displayed to avoid the message flicking on then off again virtually immediately if the
// images load really fast, e.g. from the cache.
//var ctx = this;
setTimeout(function () {
// <img src="/images/loading.gif"/>
if ($mouseTrap === null) {
var w = jWin.width();
jWin.parent().append(format('<div style="width:%0px;position:absolute;top:75%;left:%1px;text-align:center" class="cloud-zoom-loading" >Loading...</div>', w / 3, (w / 2) - (w / 6))).find(':last').css('opacity', 0.5);
}
}, 200);
var ie6FixRemove = function () {
if ($ie6Fix !== null) {
$ie6Fix.remove();
$ie6Fix = null;
}
};
// Removes cursor, tint layer, blur layer etc.
this.removeBits = function () {
//$mouseTrap.unbind();
if (lens) {
lens.remove();
lens = null;
}
if ($tint) {
$tint.remove();
$tint = null;
}
if (softFocus) {
softFocus.remove();
softFocus = null;
}
ie6FixRemove();
$('.cloud-zoom-loading', jWin.parent()).remove();
};
this.destroy = function () {
jWin.data('zoom', null);
if ($mouseTrap) {
$mouseTrap.unbind();
$mouseTrap.remove();
$mouseTrap = null;
}
if (zoomDiv) {
zoomDiv.remove();
zoomDiv = null;
}
//ie6FixRemove();
this.removeBits();
// DON'T FORGET TO REMOVE JQUERY 'DATA' VALUES
};
// This is called when the zoom window has faded out so it can be removed.
this.fadedOut = function () {
if (zoomDiv) {
zoomDiv.remove();
zoomDiv = null;
}
this.removeBits();
//ie6FixRemove();
};
this.controlLoop = function () {
if (lens) {
var x = (mx - sImg.offset().left - (cw * 0.5)) >> 0;
var y = (my - sImg.offset().top - (ch * 0.5)) >> 0;
if (x < 0) {
x = 0;
}
else if (x > (sImg.outerWidth() - cw)) {
x = (sImg.outerWidth() - cw);
}
if (y < 0) {
y = 0;
}
else if (y > (sImg.outerHeight() - ch)) {
y = (sImg.outerHeight() - ch);
}
lens.css({
left: x,
top: y
});
lens.css('background-position', (-x) + 'px ' + (-y) + 'px');
destU = (((x) / sImg.outerWidth()) * zoomImage.width) >> 0;
destV = (((y) / sImg.outerHeight()) * zoomImage.height) >> 0;
currU += (destU - currU) / opts.smoothMove;
currV += (destV - currV) / opts.smoothMove;
zoomDiv.css('background-position', (-(currU >> 0) + 'px ') + (-(currV >> 0) + 'px'));
}
controlTimer = setTimeout(function () {
ctx.controlLoop();
}, 30);
};
this.init2 = function (img, id) {
filesLoaded++;
//console.log(img.src + ' ' + id + ' ' + img.width);
if (id === 1) {
zoomImage = img;
}
//this.images[id] = img;
if (filesLoaded === 2) {
this.init();
}
};
/* Init function start. */
this.init = function () {
// Remove loading message (if present);
$('.cloud-zoom-loading', jWin.parent()).remove();
/* Add a box (mouseTrap) over the small image to trap mouse events.
It has priority over zoom window to avoid issues with inner zoom.
We need the dummy background image as IE does not trap mouse events on
transparent parts of a div.
*/
$mouseTrap = jWin.parent().append(format("<div class='mousetrap' style='background-image:url(\".\");z-index:999;position:absolute;width:%0px;height:%1px;left:%2px;top:%3px;\'></div>", sImg.outerWidth(), sImg.outerHeight(), 0, 0)).find(':last');
//////////////////////////////////////////////////////////////////////
/* Do as little as possible in mousemove event to prevent slowdown. */
$mouseTrap.bind('mousemove', this, function (event) {
// Just update the mouse position
mx = event.pageX;
my = event.pageY;
});
//////////////////////////////////////////////////////////////////////
$mouseTrap.bind('mouseleave', this, function (event) {
$('#zoomer').fadeIn(50);
clearTimeout(controlTimer);
//event.data.removeBits();
if(lens) { lens.fadeOut(299); }
if($tint) { $tint.fadeOut(299); }
if(softFocus) { softFocus.fadeOut(299); }
zoomDiv.fadeOut(300, function () {
ctx.fadedOut();
});
return false;
});
//////////////////////////////////////////////////////////////////////
$mouseTrap.bind('mouseenter', this, function (event) {
$('#zoomer').fadeOut(50);
mx = event.pageX;
my = event.pageY;
zw = event.data;
if (zoomDiv) {
zoomDiv.stop(true, false);
zoomDiv.remove();
}
var xPos = opts.adjustX,
yPos = opts.adjustY;
var siw = sImg.outerWidth();
var sih = sImg.outerHeight();
var w = opts.zoomWidth;
var h = opts.zoomHeight;
if (opts.zoomWidth == 'auto') {
w = siw;
}
if (opts.zoomHeight == 'auto') {
h = sih;
}
//$('#info').text( xPos + ' ' + yPos + ' ' + siw + ' ' + sih );
var appendTo = jWin.parent(); // attach to the wrapper
switch (opts.position) {
case 'top':
yPos -= h; // + opts.adjustY;
break;
case 'right':
xPos += siw; // + opts.adjustX;
break;
case 'bottom':
yPos += sih; // + opts.adjustY;
break;
case 'left':
xPos -= w; // + opts.adjustX;
break;
case 'inside':
w = siw;
h = sih;
break;
// All other values, try and find an id in the dom to attach to.
default:
appendTo = $('#' + opts.position);
// If dom element doesn't exit, just use 'right' position as default.
if (!appendTo.length) {
appendTo = jWin;
xPos += siw; //+ opts.adjustX;
yPos += sih; // + opts.adjustY;
} else {
w = appendTo.innerWidth();
h = appendTo.innerHeight();
}
}
zoomDiv = appendTo.append(format('<div id="cloud-zoom-big" class="cloud-zoom-big" style="display:none;position:absolute;left:%0px;top:%1px;width:%2px;height:%3px;background-image:url(\'%4\');z-index:99;"></div>', xPos, yPos, w, h, zoomImage.src)).find(':last');
// Add the title from title tag.
if (sImg.attr('title') && opts.showTitle) {
zoomDiv.append(format('<div class="cloud-zoom-title">%0</div>', sImg.attr('title'))).find(':last').css('opacity', opts.titleOpacity);
}
// Fix ie6 select elements wrong z-index bug. Placing an iFrame over the select element solves the issue...
if ($.browser.msie && $.browser.version < 7) {
$ie6Fix = $('<iframe frameborder="0" src="#"></iframe>').css({
position: "absolute",
left: xPos,
top: yPos,
zIndex: 99,
width: w,
height: h
}).insertBefore(zoomDiv);
}
zoomDiv.fadeIn(500);
if (lens) {
lens.remove();
lens = null;
} /* Work out size of cursor */
cw = (sImg.outerWidth() / zoomImage.width) * zoomDiv.width();
ch = (sImg.outerHeight() / zoomImage.height) * zoomDiv.height();
// Attach mouse, initially invisible to prevent first frame glitch
lens = jWin.append(format("<div class = 'cloud-zoom-lens' style='display:none;z-index:98;position:absolute;width:%0px;height:%1px;'></div>", cw, ch)).find(':last');
$mouseTrap.css('cursor', lens.css('cursor'));
var noTrans = false;
// Init tint layer if needed. (Not relevant if using inside mode)
if (opts.tint) {
lens.css('background', 'url("' + sImg.attr('src') + '")');
$tint = jWin.append(format('<div style="display:none;position:absolute; left:0px; top:0px; width:%0px; height:%1px; background-color:%2;" />', sImg.outerWidth(), sImg.outerHeight(), opts.tint)).find(':last');
$tint.css('opacity', opts.tintOpacity);
noTrans = true;
$tint.fadeIn(500);
}
if (opts.softFocus) {
lens.css('background', 'url("' + sImg.attr('src') + '")');
softFocus = jWin.append(format('<div style="position:absolute;display:none;top:2px; left:2px; width:%0px; height:%1px;" />', sImg.outerWidth() - 2, sImg.outerHeight() - 2, opts.tint)).find(':last');
softFocus.css('background', 'url("' + sImg.attr('src') + '")');
softFocus.css('opacity', 0.5);
noTrans = true;
softFocus.fadeIn(500);
}
if (!noTrans) {
lens.css('opacity', opts.lensOpacity);
}
if ( opts.position !== 'inside' ) { lens.fadeIn(500); }
// Start processing.
zw.controlLoop();
return; // Don't return false here otherwise opera will not detect change of the mouse pointer type.
});
};
img1 = new Image();
$(img1).load(function () {
ctx.init2(this, 0);
});
img1.src = sImg.attr('src');
img2 = new Image();
$(img2).load(function () {
ctx.init2(this, 1);
});
img2.src = jWin.attr('href');
}
$.fn.CloudZoom = function (options) {
// IE6 background image flicker fix
try {
document.execCommand("BackgroundImageCache", false, true);
} catch (e) {}
this.each(function () {
var relOpts, opts;
// Hmm...eval...slap on wrist.
eval('var a = {' + $(this).attr('rel') + '}');
relOpts = a;
if ($(this).is('.cloud-zoom')) {
$(this).css({
'position': 'relative',
'display': 'block'
});
$('img', $(this)).css({
'display': 'block'
});
// Wrap an outer div around the link so we can attach things without them becoming part of the link.
// But not if wrap already exists.
if ($(this).parent().attr('id') != 'wrap') {
$(this).wrap('<div id="wrap" style="top:0px;z-index:1000;position:relative;"></div>');
}
opts = $.extend({}, $.fn.CloudZoom.defaults, options);
opts = $.extend({}, opts, relOpts);
$(this).data('zoom', new CloudZoom($(this), opts));
} else if ($(this).is('.cloud-zoom-gallery')) {
opts = $.extend({}, relOpts, options);
$(this).data('relOpts', opts);
$(this).bind('click', $(this), function (event) {
var data = event.data.data('relOpts');
// Destroy the previous zoom
$('#' + data.useZoom).data('zoom').destroy();
// Change the biglink to point to the new big image.
$('#' + data.useZoom).attr('href', event.data.attr('href'));
// Change the ZOOM link to point to the new big image.
$('#zoomer').attr('href', event.data.attr('href'));
// Change the small image to point to the new small image.
$('#' + data.useZoom + ' img').attr('src', event.data.data('relOpts').smallImage);
// Init a new zoom with the new images.
$('#' + event.data.data('relOpts').useZoom).CloudZoom();
return false;
});
}
});
return this;
};
$.fn.CloudZoom.defaults = {
zoomWidth: 'auto',
zoomHeight: 'auto',
position: 'right',
tint: false,
tintOpacity: 0.5,
lensOpacity: 0.5,
softFocus: false,
smoothMove: 3,
showTitle: false,
titleOpacity: 0.5,
adjustX: 0,
adjustY: 0
};
})(jQuery);
add in the product.tpl file
<script type="text/javascript" src="catalog/view/theme/mytheme/js/product-zoom.js"></script>
<div class="product-info">
<?php if ($thumb || $images) { ?>
<div class="left">
<?php if ($thumb) { ?>
<div class="image"><img src="<?php echo $thumb; ?>" title="<?php echo $heading_title; ?>" alt="<?php echo $heading_title; ?>" id="image" /><span id="zoom-image"><i class="zoom_bttn"></i> Zoom</span></div>
<?php } ?>
<?php if ($images) { ?>
<div class="image-additional">
<img src="<?php echo $thumb; ?>" title="<?php echo $heading_title; ?>" alt="<?php echo $heading_title; ?>" />
<?php foreach ($images as $image) { ?>
<img src="<?php echo $image['thumb']; ?>" width="62" title="<?php echo $heading_title; ?>" alt="<?php echo $heading_title; ?>" />
<?php } ?>
</div>
<?php } ?>
</div>
<?php } ?>

Finding closest anchor href via scrollOffset

I have a UIWebView with an HTML page completely loaded. The UIWebView has a frame of 320 x 480 and scrolls horizontally. I can get the current offset a user is currently at. I would like to find the closest anchor using the XY offset so I can "jump to" that anchors position. Is this at all possible? Can someone point me to a resource in Javascript for doing this?
<a id="p-1">Text Text Text Text Text Text Text Text Text<a id="p-2">Text Text Text Text Text Text Text Text Text ...
Update
My super sad JS code:
function posForElement(e)
{
var totalOffsetY = 0;
do
{
totalOffsetY += e.offsetTop;
} while(e = e.offsetParent)
return totalOffsetY;
}
function getClosestAnchor(locationX, locationY)
{
var a = document.getElementsByTagName('a');
var currentAnchor;
for (var idx = 0; idx < a.length; ++idx)
{
if(a[idx].getAttribute('id') && a[idx+1])
{
if(posForElement(a[idx]) <= locationX && locationX <= posForElement(a[idx+1]))
{
currentAnchor = a[idx];
break;
}
else
{
currentAnchor = a[0];
}
}
}
return currentAnchor.getAttribute('id');
}
Objective-C
float pageOffset = 320.0f;
NSString *path = [[NSBundle mainBundle] pathForResource:#"GetAnchorPos" ofType:#"js"];
NSString *jsCode = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
[webView stringByEvaluatingJavaScriptFromString:jsCode];
NSString *execute = [NSString stringWithFormat:#"getClosestAnchor('%f', '0')", pageOffset];
NSString *anchorID = [webView stringByEvaluatingJavaScriptFromString:execute];
[UPDATE] I rewrote the code to match all the anchors that have an id, and simplified the comparison of the norm of the vectors in my sortByDistance function.
Check my attempt on jsFiddle (the previous one was here ).
The javascript part :
// findPos : courtesy of #ppk - see http://www.quirksmode.org/js/findpos.html
var findPos = function(obj) {
var curleft = 0,
curtop = 0;
if (obj.offsetParent) {
curleft = obj.offsetLeft;
curtop = obj.offsetTop;
while ((obj = obj.offsetParent)) {
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
}
}
return [curleft, curtop];
};
var findClosestAnchor = function (anchors) {
var sortByDistance = function(element1, element2) {
var pos1 = findPos( element1 ),
pos2 = findPos( element2 );
// vect1 & vect2 represent 2d vectors going from the top left extremity of each element to the point positionned at the scrolled offset of the window
var vect1 = [
window.scrollX - pos1[0],
window.scrollY - pos1[1]
],
vect2 = [
window.scrollX - pos2[0],
window.scrollY - pos2[1]
];
// we compare the length of the vectors using only the sum of their components squared
// no need to find the magnitude of each (this was inspired by Mageek’s answer)
var sqDist1 = vect1[0] * vect1[0] + vect1[1] * vect1[1],
sqDist2 = vect2[0] * vect2[0] + vect2[1] * vect2[1];
if ( sqDist1 < sqDist2 ) return -1;
else if ( sqDist1 > sqDist2 ) return 1;
else return 0;
};
// Convert the nodelist to an array, then returns the first item of the elements sorted by distance
return Array.prototype.slice.call( anchors ).sort( sortByDistance )[0];
};
You can retrieve and cache the anchors like so when the dom is ready : var anchors = document.body.querySelectorAll('a[id]');
I’ve not tested it on a smartphone yet but I don’t see any reasons why it wouldn’t work.
Here is why I used the var foo = function() {}; form (more javascript patterns).
The return Array.prototype.slice.call( anchors ).sort( sortByDistance )[0]; line is actually a bit tricky.
document.body.querySelectorAll('a['id']') returns me a NodeList with all the anchors that have the attribute "id" in the body of the current page.
Sadly, a NodeList object does not have a "sort" method, and it is not possible to use the sort method of the Array prototype, as it is with some other methods, such as filter or map (NodeList.prototype.sort = Array.prototype.sort would have been really nice).
This article explains better that I could why I used Array.prototype.slice.call to turn my NodeList into an array.
And finally, I used the Array.prototype.sort method (along with a custom sortByDistance function) to compare each element of the NodeList with each other, and I only return the first item, which is the closest one.
To find the position of the elements that use fixed positionning, it is possible to use this updated version of findPos : http://www.greywyvern.com/?post=331.
My answer may not be the more efficient (drdigit’s must be more than mine) but I preferred simplicity over efficiency, and I think it’s the easiest one to maintain.
[YET ANOTHER UPDATE]
Here is a heavily modified version of findPos that works with webkit css columns (with no gaps):
// Also adapted from PPK - this guy is everywhere ! - check http://www.quirksmode.org/dom/getstyles.html
var getStyle = function(el,styleProp)
{
if (el.currentStyle)
var y = el.currentStyle[styleProp];
else if (window.getComputedStyle)
var y = document.defaultView.getComputedStyle(el,null).getPropertyValue(styleProp);
return y;
}
// findPos : original by #ppk - see http://www.quirksmode.org/js/findpos.html
// made recursive and transformed to returns the corect position when css columns are used
var findPos = function( obj, childCoords ) {
if ( typeof childCoords == 'undefined' ) {
childCoords = [0, 0];
}
var parentColumnWidth,
parentHeight;
var curleft, curtop;
if( obj.offsetParent && ( parentColumnWidth = parseInt( getStyle( obj.offsetParent, '-webkit-column-width' ) ) ) ) {
parentHeight = parseInt( getStyle( obj.offsetParent, 'height' ) );
curtop = obj.offsetTop;
column = Math.ceil( curtop / parentHeight );
curleft = ( ( column - 1 ) * parentColumnWidth ) + ( obj.offsetLeft % parentColumnWidth );
curtop %= parentHeight;
}
else {
curleft = obj.offsetLeft;
curtop = obj.offsetTop;
}
curleft += childCoords[0];
curtop += childCoords[1];
if( obj.offsetParent ) {
var coords = findPos( obj.offsetParent, [curleft, curtop] );
curleft = coords[0];
curtop = coords[1];
}
return [curleft, curtop];
}
I found a way to make it, without using scrollOffset. It's a bit complicated so if you have any question to understand it just comment.
HTML :
<body>
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<a />Text Text Text Text Text Text Text Text Text
<br /><br /><br /><br /><br />
<a />Text Text Text Text Text Text Text Text Text
</body>
CSS :
body
{
height:3000px;
}
JS :
var tempY;
function getClosestAnchor(e)
{
if((window.event?event.keyCode:e.which)!=97)return;
var allAnchors=document.getElementsByTagName("a");
var allDiff=[];
for(var a=0;a<allAnchors.length;a++)allDiff[a]=margeY(allAnchors[a])-tempY;
var smallest=allDiff[0];
for(var a=1;a<allDiff.length;a++)
{
if(Math.abs(smallest)>Math.abs(allDiff[a]))
{
smallest=allDiff[a];
}
}
window.scrollBy(0,smallest);
}
function margeY(obj)
{
var posY=0;
if(!obj.offsetParent)return;
do posY+=obj.offsetTop;
while(obj=obj.offsetParent);
return posY;
}
function update(e)
{
if(e.pageY)tempY=e.pageY;
else tempY=e.clientY+(document.documentElement.scrollTop||document.body.scrollTop)-document.documentElement.clientTop;
}
window.onkeypress=getClosestAnchor;
window.onmousemove=update;
Here is a fiddle demonstration : http://jsfiddle.net/jswuC/
Bonus : You don't have to specify an id to all the anchors.
Phew! I finished!
JS :
var x=0,y=0;//Here are the given X and Y, you can change them
var idClosest;//Id of the nearest anchor
var smallestIndex;
var couplesXY=[];
var allAnchors;
var html=document.getElementsByTagName("html")[0];
html.style.width="3000px";//You can change 3000, it's to make the possibility of horizontal scroll
html.style.height="3000px";//Here too
function random(min,max)
{
var nb=min+(max+1-min)*Math.random();
return Math.floor(nb);
}
function left(obj)//A remixed function of this site http://www.quirksmode.org/js/findpos.html
{
if(obj.style.position=="absolute")return parseInt(obj.style.left);
var posX=0;
if(!obj.offsetParent)return;
do posX+=obj.offsetLeft;
while(obj=obj.offsetParent);
return posX;
}
function top(obj)
{
if(obj.style.position=="absolute")return parseInt(obj.style.top);
var posY=0;
if(!obj.offsetParent)return;
do posY+=obj.offsetTop;
while(obj=obj.offsetParent);
return posY;
}
function generateRandomAnchors()//Just for the exemple, you can delete the function if you have already anchors
{
for(var a=0;a<50;a++)//You can change 50
{
var anchor=document.createElement("a");
anchor.style.position="absolute";
anchor.style.width=random(0,100)+"px";//You can change 100
anchor.style.height=random(0,100)+"px";//You can change 100
anchor.style.left=random(0,3000-parseInt(anchor.style.width))+"px";//If you changed 3000 from
anchor.style.top=random(0,3000-parseInt(anchor.style.height))+"px";//the top, change it here
anchor.style.backgroundColor="black";
anchor.id="Anchor"+a;
document.body.appendChild(anchor);
}
}
function getAllAnchors()
{
allAnchors=document.getElementsByTagName("a");
for(var a=0;a<allAnchors.length;a++)
{
couplesXY[a]=[];
couplesXY[a][0]=left(allAnchors[a]);
couplesXY[a][1]=top(allAnchors[a]);
}
}
function findClosestAnchor()
{
var distances=[];
for(var a=0;a<couplesXY.length;a++)distances.push(Math.pow((x-couplesXY[a][0]),2)+Math.pow((y-couplesXY[a][1]),2));//Math formula to get the distance from A to B (http://euler.ac-versailles.fr/baseeuler/lexique/notion.jsp?id=122). I removed the square root not to slow down the calculations
var smallest=distances[0];
smallestIndex=0;
for(var a=1;a<distances.length;a++)if(smallest>distances[a])
{
smallest=distances[a];
smallestIndex=a;
}
idClosest=allAnchors[smallestIndex].id;
alert(idClosest);
}
function jumpToIt()
{
window.scrollTo(couplesXY[smallestIndex][0],couplesXY[smallestIndex][1]);
allAnchors[smallestIndex].style.backgroundColor="red";//Color it to see it
}
generateRandomAnchors();
getAllAnchors();
findClosestAnchor();
jumpToIt();
Fiddle : http://jsfiddle.net/W8LBs/2
PS : If you open this fiddle on a smartphone, it doesn't work (I don't know why) but if you copy this code in a sample on a smartphone, it works (but you must specify the <html> and the <body> section).
This answer has not received enough attention.
Complete sample, fast (binary search) with caching for positions.
Fixed height and width, id of the closest anchor and scrollto
<!DOCTYPE html>
<html lang="en">
<head>
<meta>
<title>Offset 2</title>
<style>
body { font-family:helvetica,arial; font-size:12px; }
</style>
<script>
var ui = reqX = reqY = null, etop = eleft = 0, ref, cache;
function createAnchors()
{
if (!ui)
{
ui = document.getElementById('UIWebView');
reqX = document.getElementById('reqX');
reqY = document.getElementById('reqY');
var h=[], i=0;
while (i < 1000)
h.push('<a>fake anchor ... ',i,'</a> <a href=#>text for anchor <b>',(i++),'</b></a> ');
ui.innerHTML = '<div style="padding:10px;width:700px">' + h.join('') + '</div>';
cache = [];
ref = Array.prototype.slice.call(ui.getElementsByTagName('a'));
i = ref.length;
while (--i >= 0)
if (ref[i].href.length == 0)
ref.splice(i,1);
}
}
function pos(i)
{
if (!cache[i])
{
etop = eleft = 0;
var e=ref[i];
if (e.offsetParent)
{
do
{
etop += e.offsetTop;
eleft += e.offsetLeft;
} while ((e = e.offsetParent) && e != ui)
}
cache[i] = [etop, eleft];
}
else
{
etop = cache[i][0];
eleft = cache[i][1];
}
}
function find()
{
createAnchors();
if (!/^\d+$/.test(reqX.value))
{
alert ('I need a number for X');
return;
}
if (!/^\d+$/.test(reqY.value))
{
alert ('I need a number for Y');
return;
}
var
x = reqX.value,
y = reqY.value,
low = 0,
hi = ref.length + 1,
med,
limit = (ui.scrollHeight > ui.offsetHeight) ? ui.scrollHeight - ui.offsetHeight : ui.offsetHeight - ui.scrollHeight;
if (y > limit)
y = limit;
if (x > ui.scrollWidth)
x = (ui.scrollWidth > ui.offsetWidth) ? ui.scrollWidth : ui.offsetWidth;
while (low < hi)
{
med = (low + ((hi - low) >> 1));
pos(med);
if (etop == y)
{
low = med;
break;
}
if (etop < y)
low = med + 1;
else
hi = med - 1;
}
var ctop = etop;
if (eleft != x)
{
if (eleft > x)
while (low > 0)
{
pos(--low);
if (etop < ctop || eleft < x)
{
pos(++low);
break;
}
}
else
{
hi = ref.length;
while (low < hi)
{
pos(++low);
if (etop > ctop || eleft > x)
{
pos(--low);
break;
}
}
}
}
ui.scrollTop = etop - ui.offsetTop;
ui.scrollLeft = eleft - ui.offsetLeft;
ref[low].style.backgroundColor = '#ff0';
alert(
'Requested position: ' + x + ', ' + y +
'\nScrollTo position: ' + ui.scrollLeft + ', '+ ui.scrollTop +
'\nClosest anchor id: ' + low
);
}
</script>
</head>
<body>
<div id=UIWebView style="width:320px;height:480px;overflow:auto;border:solid 1px #000"></div>
<label for="req">X: <input id=reqX type=text size=5 maxlength=5 value=200></label>
<label for="req">Y: <input id=reqY type=text size=5 maxlength=5 value=300></label>
<input type=button value="Find closest anchor" onclick="find()">
</body>
</html>

Image upload popup in ckeditor is not woking in Google chrome

When I click browse server in ckeditor the image browser popup doesnt appear.I am facing problem only in Google Chrome.I am using 18.0.1025.152 m verion of Google Chrome
I have made changes in ckeditor/plugins/popup/plugin.js
try
{
// Chrome 18 is problematic, but it's not really needed here (#8855).
var ua = navigator.userAgent.toLowerCase();
if ( ua.indexOf('chrome/18' ) == -1 )
{
popupWindow.moveTo( left, top );
popupWindow.resizeTo( width, height );
}
popupWindow.focus();
popupWindow.location.href = url;
}
catch ( e )
{
popupWindow = window.open( url, null, options, true );
}
I followed this link enter link description here
But I am unable to resolve the issue.Can anyone help
If you edit the source files you have to repackage them again. It's much simpler to update to CKEditor 3.6.3 and get all the other bug fixes.
I am using opencart 1.5.1.3 ckeditor. I edit the /admin/view/javascript/ckeditor/ckeditor.js and re-align the javascript code with http://jsbeautifier.org/
I have tried with the patch from ckeditor community and little modifications. It works!
http://dev.ckeditor.com/ticket/8855
So if anyone has face the similar issue like me in opencart you can try with below changes.
+++ b/v1.5.1.3/admin/view/javascript/ckeditor/ckeditor.js
## -9190,8 +9190,21 ## For licensing, see LICENSE.html or http://ckeditor.com/license
var s = window.open('', null, p, true);
if (!s) return false;
try {
- s.moveTo(r, q);
- s.resizeTo(n, o);
+ // s.moveTo(r, q);
+ // s.resizeTo(n, o);
+ // Chrome 18 is problematic, but it's not really needed here (#8855).
+ var ua = navigator.userAgent.toLowerCase();
+ var useResize = true;
+ if (ua.indexOf('chrome') > -1) {
+ var chromeVersion = ua.replace(/^.*chrome\/([\d]+).*$/i, '$1')
+ if(chromeVersion >= 18) {
+ useResize = false;
+ }
+ }
+ if (useResize) {
+ s.moveTo( r, q );
+ s.resizeTo( n, o );
+ }
s.focus();
s.location.href = m;
} catch (t) {
I'm using the CKEditor 3.6.2 that comes bundled with primefaces-extensions, so upgrading is not that easy. But executing the following fix against the page also worked. I pasted it in the config file, to be sure that it is fired after the CKEDITOR variable is initialized.
CKEDITOR.editor.prototype['popup'] = function( url, width, height, options ) {
width = width || '80%';
height = height || '70%';
if ( typeof width == 'string' && width.length > 1 && width.substr( width.length - 1, 1 ) == '%' )
width = parseInt( window.screen.width * parseInt( width, 10 ) / 100, 10 );
if ( typeof height == 'string' && height.length > 1 && height.substr( height.length - 1, 1 ) == '%' )
height = parseInt( window.screen.height * parseInt( height, 10 ) / 100, 10 );
if ( width < 640 )
width = 640;
if ( height < 420 )
height = 420;
var top = parseInt( ( window.screen.height - height ) / 2, 10 ),
left = parseInt( ( window.screen.width - width ) / 2, 10 );
options = ( options || 'location=no,menubar=no,toolbar=no,dependent=yes,minimizable=no,modal=yes,alwaysRaised=yes,resizable=yes,scrollbars=yes' ) +
',width=' + width +
',height=' + height +
',top=' + top +
',left=' + left;
var popupWindow = window.open( '', null, options, true );
// Blocked by a popup blocker.
if ( !popupWindow )
return false;
try
{
// Chrome 18 is problematic, but it's not really needed here (#8855).
var ua = navigator.userAgent.toLowerCase();
if ( ua.indexOf( ' chrome/18' ) == -1 )
{
popupWindow.moveTo( left, top );
popupWindow.resizeTo( width, height );
}
popupWindow.focus();
popupWindow.location.href = url;
}
catch ( e )
{
popupWindow = window.open( url, null, options, true );
}
return true;
}
$(document).ready(
function() {
setContentHeight();
makeInstructionsTogglable();
window.onbeforeunload = function() {
if (editor.isDirty()) {
return "Are you sure you want to navigate away? You have unsaved changes."
}
};
}
);
$(window).resize(function() {
setContentHeight();
});

Categories

Resources