updating HTML information through a Raphael.JS element - javascript

I'm trying to update the information of a series or circles that get created through a click event using Raphael.js along with some HTML tags. When they get created, the html generated keeps the information of the circle with the position of its X, Y and its radius, which can be dynamically changed when I move the circle around or change its size, this JSFiddle shows it more clearly:
http://jsfiddle.net/mauricioSanchez/L4mAL/
I have my event listeners
canvasHandler.mouseup(function (e) {
var mouseX = e.offsetX;
var mouseY = e.offsetY;
if (circlePickerSelector) {
makeCircle(mouseX, mouseY);
circlePickerSelector = false;
}
});
circlePicker.click(function () {
circlePickerSelector = !circlePickerSelector;
});
This is the main function that gets called in the first eventListener. Which creates the circle and the HTML elements for that
function makeCircle(mouseX, mouseY) {
//We call it before our circles are dragged so that their array is waiting to store the information
// addingArrays(circleCounter);
var radius;
var fill;
var circle = canvas.circle(mouseX, mouseY, 50).attr({
fill: "hsb(.8, 1, 1)",
stroke: "none",
opacity: .5,
});
// console.log(circles);
// We add an ID and a class to the circle
var ourCircle = $("circle").last();
ourCircle.attr("class", circleCounter);
// And then finally push it to our array of circles
circles.push(circle);
var handlerPos = [mouseX + 35, mouseY + 35];
var s = canvas.circle(handlerPos[0], handlerPos[1], 10).attr({
fill: "hsb(.8, .5, .5)",
stroke: "none",
opacity: .5
});
//We add an id and a class to our little circle.
s.node.id = sizerCounter;
var sizerClass = $('circle').last();
sizerClass.attr("class", "main-circle sizer");
var newSizerClass = $(".sizer");
// console.log(s);
s.hide();
//We now assign a handler for each little circle added and a main circle in order to hide them
var circleClass = $("." + String(circleCounter));
var sizerID = $("#" + String(sizerCounter));
circleClass.mouseenter(function () {
sizerID.toggle();
});
circleClass.mouseleave(function () {
sizerID.hide();
});
sizerID.mouseenter(function () {
$(this).toggle();
});
sizerID.mouseleave(function () {
$(this).hide();
});
// console.log(circleClass);
//We add some resizing and dragging properties
var start = function () {
//storing original coordinates
this.ox = this.attr("cx");
this.oy = this.attr("cy");
this.sizer.ox = this.sizer.attr("cx");
this.sizer.oy = this.sizer.attr("cy")
this.attr({
opacity: 1
});
this.sizer.attr({
opacity: 1
});
}, move = function (dx, dy) {
// move will be called with dx and dy
this.attr({
cx: this.ox + dx,
cy: this.oy + dy
});
this.sizer.attr({
cx: this.sizer.ox + dx,
cy: this.sizer.oy + dy
});
//This is the key function to change
updateModel(this.attrs.cx, this.attrs.cy, this.node.className.baseVal, this.attrs.r);
}, up = function () {
// restoring state
this.attr({
opacity: .5
});
this.sizer.attr({
opacity: .5
});
}, rstart = function () {
// storing original coordinates
this.ox = this.attr("cx");
this.oy = this.attr("cy");
this.big.or = this.big.attr("r");
}, rmove = function (dx, dy) {
// move will be called with dx and dy
this.attr({
cx: this.ox + dy,
cy: this.oy + dy
});
this.big.attr({
r: this.big.or + (dy < 0 ? -1 : 1) * Math.sqrt(2 * dy * dy)
});
updateModel(this.attrs.cx, this.attrs.cy, this.node.className.baseVal, this.attrs.r);
};
circle.drag(move, start, up);
circle.sizer = s;
s.drag(rmove, rstart);
s.big = circle;
//Here we create
var myCodeList = $(".code-list");
var htmlString = "<li class='" + circleCounter + "'> <span class='circle-color'> var color = <div class='circle-color-input' contentEditable autocorrect='off'> type a color</div> ; </span> <br> <span class='circle-radius'> This is a test </span> <br> <span class='circle'> This is a test </span> </li>";
myCodeList.append(htmlString);
updateList();
circleCounter++;
sizerCounter++;
}
Finally this two functions allow the html and the position of the circle to be updated:
function updateModel(x, y, _class, r) {
var len = circles.length;
for (var i = 0; i < len; i++) {
if (circles[i].node.className.baseVal == _class) {
circles[i].attrs.cx = x;
circles[i].attrs.cy = y;
circles[i].attrs.r = r;
}
}
updateList();
}
function updateList() {
//To change that one I have put a class or an id
var listItems = $('.code-list').find('li.' + circleCounter);
// console.log(listItems);
var len = circles.length;
for (var i = 0; i < circles.length; i++) {
//We create one reference. This makes looking for one element more effective. Unless we need to search for a particular element
var currentItem = circles[i];
var updateStringRadius = "var radius = " + parseInt(currentItem.attrs.r) + ";";
var updateStringCircle = "circle (" + currentItem.attrs.cx + " ," + currentItem.attrs.cy + ", radius)";
//This is the div Item for the particular div of each element
var divItem = $(listItems[i]);
var radiusItem = divItem.find("span.circle-radius");
var circleItem = divItem.find("span.circle");
// console.log(currentItem.attrs.cx);
radiusItem.text(updateStringRadius);
console.log($('.circle-radius').html());
circleItem.text(updateStringCircle);
// divItem.text(updateString);
// console.log(divItem);
}
}
If you take a look at the JSfiddle and create three circles for example. it will only update the information of the first one after a circle is created, but now when moved or when resized doesn't change.

I figured it out. So the problem was in this function:
function updateList() {
//To change that one I have put a class or an id
var listItems = $('.code-list').find('li.' + circleCounter);
// console.log(listItems);
var len = circles.length;
for (var i = 0; i < circles.length; i++) {
//We create one reference. This makes looking for one element more effective. Unless we need to search for a particular element
var currentItem = circles[i];
var updateStringRadius = "var radius = " + parseInt(currentItem.attrs.r) + ";";
var updateStringCircle = "circle (" + currentItem.attrs.cx + " ," + currentItem.attrs.cy + ", radius)";
//This is the div Item for the particular div of each element
var divItem = $(listItems[i]);
var radiusItem = divItem.find("span.circle-radius");
var circleItem = divItem.find("span.circle");
// console.log(currentItem.attrs.cx);
radiusItem.text(updateStringRadius);
console.log($('.circle-radius').html());
circleItem.text(updateStringCircle);
// divItem.text(updateString);
// console.log(divItem);
}
}
I changed the way I was initiating the handler and finding its children for this:
function updateList(){
var len = circles.length;
for (var i = 0; i < circles.length; i++) {
var currentItem = circles[i];
var updateStringRadius = "var radius = " + parseInt(currentItem.attrs.r) + ";";
var updateStringCircle = "circle (" + currentItem.attrs.cx + " ," + currentItem.attrs.cy + ", radius)";
var divItem = $('.code-list').find('li.circle-' + (i+1))
var radiusItem = divItem.find("span.circle-radius");
var circleItem = divItem.find("span.circle");
radiusItem.text(updateStringRadius);
circleItem.text(updateStringCircle);
}
I wasn't iterating through the elements properly. I was also recommended that for best practices to change my class from class="1" to class="circle-1".
Here is the JSfiddle

Related

Display Absolute positioned images inside a div

i am trying to absolute position images at random positions inside a div. i'm not sure how to get the calculations right for 'top' and 'left' but the images on occasions display outside of the div. i want to also prevent the overlapping of the images.
Any ideas would help
(function() {
//array of links to the images
var images = ["http://via.placeholder.com/150/800",
"http://via.placeholder.com/150/080",
"http://via.placeholder.com/150/008",
"http://via.placeholder.com/150/880"
];
//function to calculate a random integer
var getRandomInt = function(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
//function to get a top and left value position for each image
var pos = function() {
var wrapWidth = document.getElementById("wrap");
wrapWidth = $("#wrap").width();
wrapHeight = $("#wrap").height();
// Image Position
var xPos = getRandomInt(0, wrapWidth - 150);
var yPos = getRandomInt(0, wrapHeight - 150);
return {
x: xPos + "px",
y: yPos + "px"
}
}
var displayImages = function(images) {
var elementArray = [];
for (var i = 0; i < images.length; i++) {
var src = images[i];
elementArray[i] = '<img class="imagePos" style="top:' + pos().x + '; left:' + pos().y + ' " src="' + src + ' "/>';
}
console.log(elementArray);
elementArray.forEach(function(element) {
console.log(element);
$("#wrap").append(element);
});
}
displayImages(images);
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="IntTree">
<div id="header">
<h1>Interactive Tree</h1>
</div>
<div id="wrap">
</div>
</div>
I'm assuming that you have some css resembling this:
img {
position: absolute;
width:150;
height:150;
}
Regarding your first issue, you appear to have your x and y assignments backwards in the bit where you're adding the elems to the array. Also, you're making 2 times as many calls to pos() as needed.
That line should be:
let position = pos();
elementArray[i] = '<img class="imagePos" style="top:'+position.y+'; left:'+position.x+' " src="'+src+' "/>';
For the second issue, you need to check for each image whether any of the corners overlap a different image. The easy way to achieve this by adding an array to track the positions you've already used, and comparing against the items in the array for subsequent position calculations.
(function (){
//array of links to the images
var images = ["http://via.placeholder.com/150/800",
"http://via.placeholder.com/150/080",
"http://via.placeholder.com/150/008",
"http://via.placeholder.com/150/880"
];
//function to calculate a random integer
var getRandomInt = function (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// array to track previous positions of images
var positions = [];
//function to get a top and left value position for each image
var pos = function (){
var wrapWidth = $("#wrap").width();
var wrapHeight = $("#wrap").height();
// Image Position
var xPos = getRandomInt(0, wrapWidth - 150);
var yPos = getRandomInt(0, wrapHeight - 150);
var overlapX = true;
var overlapY = true;
while(overlapX && overlapY) {
overlapX = false;
overlapY = false;
for(var i = 0; i < positions.length; i++) {
// check if x coord is inside previously placed image
if ( (xPos > positions[i].x && xPos < positions[i].x+150) ||
(xPos+150 > positions[i].x && (xPos+150) < positions[i].x+150) ){
overlapX = true;
}
// check if y coord is inside previously placed image
if( (yPos > positions[i].y && yPos < positions[i].y+150) ||
(yPos+150 > positions[i].y && yPos+150 < positions[i].y+150) ) {
overlapY = true;
}
}
if (overlapX) {
xPos = getRandomInt(0, wrapWidth - 150);
}
if (overlapY) {
yPos = getRandomInt(0, wrapHeight - 150);
}
}
positions.push({x:xPos,y:yPos});
return {
x: xPos + "px",
y: yPos + "px"
}
}
var displayImages = function(images){
var elementArray = [];
for (var i = 0; i < images.length; i++) {
var src = images[i];
let position = pos();
elementArray[i] = '<img class="imagePos" style="top:'+position.y+'; left:'+position.x+' " src="'+src+' "/>';
}
elementArray.forEach(function(element) {
$("#wrap").append(element);
});
}
displayImages(images);
})();

OnClick event not fired in javascript when attached to img

I'm new to JavaScript, so this may be basic...
I'm trying to create an image dynamically and add it a event listener for "onclick". I add this img to a div.
I create the img like this:
function createNewSmiley()
{
var newSmiley = document.createElement("img");
newSmiley.src = "./smiley.jpg";
newSmiley.alt = "Smiley Image";
newSmiley.style.width = "64px";
newSmiley.style.height = "64px";
return newSmiley;
}
And then I add it to the div like using like this:
function positionNewSmiley(parent, smiley, x, y)
{
var newSmiley = createNewSmiley();
newSmiley.style.top = y + "px";
newSmiley.style.left = x + "px";
parent.appendChild(newSmiley);
}
And this is my main function:
function main(smileyCount)
{
var myDiv = document.getElementById("myDiv");
for (var i = 0; i < smileyCount;i++)
{
var x = Math.floor((Math.random() * 500));
var y = Math.floor((Math.random() * 500));
var smiley = createNewSmiley();
smiley.onclick = smileyClicked;
positionNewSmiley(myDiv, smiley, x, y);
}
}
function smileyClicked(ev) {
alert("OK");
}
But the onclick event will not fire!
however, if I add the event listener to the div - it will.
What am I doing wrong?
As mentioned in the above comment you're creating new smiley in the positionNewSmiley when you've to position the passed smiley instead :
var smiley = createNewSmiley();
smiley.onclick = smileyClicked;
positionNewSmiley(myDiv, smiley, x, y);
_________________________^^^^^^
Just use it in the position function :
function positionNewSmiley(parent, smiley, x, y)
{
smiley.style.top = y + "px";
smiley.style.left = x + "px";
parent.appendChild(smiley);
}
Hope this helps.
function createNewSmiley()
{
var newSmiley = document.createElement("img");
newSmiley.src = "http://cfile24.uf.tistory.com/image/163BB51F4BF9DF7431AB10";
newSmiley.alt = "Smiley Image";
newSmiley.style.width = "64px";
newSmiley.style.height = "64px";
return newSmiley;
}
function positionNewSmiley(parent, smiley, x, y)
{
smiley.style.top = y + "px";
smiley.style.left = x + "px";
parent.appendChild(smiley);
}
function main(smileyCount)
{
var myDiv = document.getElementById("myDiv");
for (var i = 0; i < smileyCount;i++)
{
var x = Math.floor((Math.random() * 500));
var y = Math.floor((Math.random() * 500));
var smiley = createNewSmiley();
smiley.onclick = smileyClicked;
positionNewSmiley(myDiv, smiley, x, y);
}
}
function smileyClicked(ev) {
alert("OK");
}
main(6);
<div id='myDiv'></div>
if you add the on click within the create function it will work
function createNewSmiley()
{
var newSmiley = document.createElement("img");
newSmiley.src = "./smiley.jpg";
newSmiley.alt = "Smiley Image";
newSmiley.style.width = "64px";
newSmiley.style.height = "64px";
newSmiley.addEventListener("click", smileyClicked);
return newSmiley;
}

Cloudzoom and woocommerce attributes

I cannot get cloudzoom to work with my woocommerce site, every time I choose an attribute ie size the main image disappears, it is like cloudzoom is trying to force an attribute image. I am absolutely pants at javascript and looking through the file I cannot see where I need to edit or delete the code. Any help would be greatly appreciated, I don't need the atribute image function to work at all so just stripping out the code would suit me. Here is the code...
(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:3;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="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:2;"></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:1;position:absolute;width:%0px;height:%1px;opacity:0.4'></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:4;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 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.
$('#zoom-cb').attr('href', event.data.attr('href'));
$('#' + 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);

Move text up with javascript

So I need function like this one, -link- but just to move text up, not left. How to achieve this?
So, this is code that moves text left:
//Text fade
var bgcolor;
var fcolor;
var heading;
//Number of steps to fade
var steps;
var colors;
var color = 0;
var step = 1;
var interval1;
var interval2;
//fade: fader function
// Fade from backcolor to forecolor in specified number of steps
function fade(headingtext,backcolor,forecolor,numsteps) {
if (color == 0) {
steps = numsteps;
heading = "<font color='{COLOR}'>"+headingtext+"</strong></font>";
bgcolor = backcolor;
fcolor = forecolor;
colors = new Array(steps);
getFadeColors(bgcolor,fcolor,colors);
}
// insert fader color into message
var text_out = heading.replace("{COLOR}", colors[color]);
// write the message to the document
document.getElementById("fader").innerHTML = text_out;
// select next fader color
color += step;
if (color >= steps) clearInterval(interval1);
}
//getFadeColors: fills colors, using predefined Array, with color hex strings fading from ColorA to ColorB
//Note: Colors.length equals the number of steps to fade
function getFadeColors(ColorA, ColorB, Colors) {
len = Colors.length;
//Strip '#' from colors if present
if (ColorA.charAt(0)=='#') ColorA = ColorA.substring(1);
if (ColorB.charAt(0)=='#') ColorB = ColorB.substring(1);
//Substract red green and blue components from hex string
var r = HexToInt(ColorA.substring(0,2));
var g = HexToInt(ColorA.substring(2,4));
var b = HexToInt(ColorA.substring(4,6));
var r2 = HexToInt(ColorB.substring(0,2));
var g2 = HexToInt(ColorB.substring(2,4));
var b2 = HexToInt(ColorB.substring(4,6));
// calculate size of step for each color component
var rStep = Math.round((r2 - r) / len);
var gStep = Math.round((g2 - g) / len);
var bStep = Math.round((b2 - b) / len);
// fill Colors array with fader colors
for (i = 0; i < len-1; i++) {
Colors[i] = "#" + IntToHex(r) + IntToHex(g) + IntToHex(b);
r += rStep;
g += gStep;
b += bStep;
}
Colors[len-1] = ColorB; // make sure we finish exactly at ColorB
}
//IntToHex: converts integers between 0 - 255 into a two digit hex string.
function IntToHex(n) {
var result = n.toString(16);
if (result.length==1) result = "0"+result;
return result;
}
//HexToInt: converts two digit hex strings into integer.
function HexToInt(hex) {
return parseInt(hex, 16);
}
var startwidth = 0;
//scroll: Make the text scroll using the marginLeft element of the div container
function scroll(startw) {
if (startwidth == 0) {
startwidth=startw;
}
document.getElementById("fader").style.marginLeft = startwidth + "px";
if (startwidth > 1) {
startwidth -= 1;
} else {
clearInterval(interval2);
}
}
function fadeandscroll(txt,color1,color2,numsteps,fademilli,containerwidth,scrollmilli) {
interval1 = setInterval("fade('"+txt+"','"+color1+"','"+color2+"',"+numsteps+")",fademilli);
interval2 = setInterval("scroll("+containerwidth+")",scrollmilli);
}
Something like this seems to do what you want, but jQuery would have been easier.
Demo: Vertical Marquee Demo
window.document.addEventListener("DOMContentLoaded", function()
{
var elm = window.document.querySelectorAll("#display span")[0], height = elm.parentNode.offsetHeight;
elm.style.position = "relative";
elm.style.top = "0px";
var timer = setInterval(function()
{
var top = Number(elm.style.top.replace(/[^\d\-]/g, ''));
top = top > -height ? top - 1 : height;
elm.style.top = top + "px";
}, 50);
/*
* If you want to stop scrolling, call clearInterval(timer);
*
* Example set to stop when clicked.
*/
elm.addEventListener("click", function()
{
clearInterval(timer);
}, false);
}, false);

How to change arrow length for arrow overlay

The Issue
I am using the following example code to draw arrows on google map.
Here is the main overlay function that creates the svg files for the arrow.
// A small directable Arrow overlay for GMaps V3
// Bill Chadwick Feb 2012 after my previous V2 API version
// Free for any use as far as I am concerned
// Some public domain code VML/SVG utility code of Ben Appleton's is reused at the end of this file
var arrowOverlayMarkerCounter; //unique id counter for SVG arrow head markers
function ArrowOverlay(map, location, rotation, color, opacity, tooltip) {
this.map_ = map;
this.location_ = location;
this.rotation_ = rotation || 0.0;
var r = this.rotation_ + 90; //compass to math
this.dx_ = 20 * Math.cos(r * Math.PI / 180); //other end of arrow line to point
this.dy_ = 20 * Math.sin(r * Math.PI / 180);
this.color_ = color || "#0000FF";
this.opacity_ = opacity || 0.7;
this.tooltip_ = tooltip || "";
this.div_ = null;
this.setMap(map);
this.handle_ = null;//click event handler handle
if (arrowOverlayMarkerCounter == null)
arrowOverlayMarkerCounter = 0;
else
arrowOverlayMarkerCounter += 1;
this.svgId_ = "ArrowOverlay" + arrowOverlayMarkerCounter.toString();
}
ArrowOverlay.prototype = new google.maps.OverlayView();
ArrowOverlay.prototype.onAdd = function() {
// Create the DIV and set some basic attributes.
var div = document.createElement('DIV');
div.title = this.tooltip_;
div.style.cursor = "help";
var obj = this;
this.handle_ = google.maps.event.addDomListener(div, 'click', function() { google.maps.event.trigger(obj, "click") });
//set up arrow invariants
if (supportsVML()) {
var l = createVmlElement('v:line', div);
l.strokeweight = "3px";
l.strokecolor = this.color_;
l.style.position = 'absolute';
var s = createVmlElement("v:stroke", l);
s.opacity = this.opacity_;
s.startarrow = "classic"; // or "block", "open" etc see VML spec
this.vmlLine_ = l;
}
else {
// make a 40x40 pixel space centered on the arrow
var svgNS = "http://www.w3.org/2000/svg";
var svgRoot = document.createElementNS(svgNS, "svg");
svgRoot.setAttribute("width", 40);
svgRoot.setAttribute("height", 40);
svgRoot.setAttribute("stroke", this.color_);
svgRoot.setAttribute("fill", this.color_);
svgRoot.setAttribute("stroke-opacity", this.opacity_);
svgRoot.setAttribute("fill-opacity", this.opacity_);
div.appendChild(svgRoot);
var svgNode = document.createElementNS(svgNS, "line");
svgNode.setAttribute("stroke-width", 3);
svgNode.setAttribute("x1", 20);
svgNode.setAttribute("y1", 20);
svgNode.setAttribute("x2", 20 + this.dx_);
svgNode.setAttribute("y2", 20 + this.dy_);
//make a solid arrow head, can't share these, as in SVG1.1 they can't get color from the referencing object, only their parent
//a bit more involved than the VML
if (this.rotation_ >= 0) {
var svgM = document.createElementNS(svgNS, "marker");
svgM.id = this.svgId_;
svgM.setAttribute("viewBox", "0 0 10 10");
svgM.setAttribute("refX", 0);
svgM.setAttribute("refY", 5);
svgM.setAttribute("markerWidth", 4);
svgM.setAttribute("markerHeight", 3);
svgM.setAttribute("orient", "auto");
var svgPath = document.createElementNS(svgNS, "path"); //could share this with 'def' and 'use' but hardly worth it
svgPath.setAttribute("d", "M 10 0 L 0 5 L 10 10 z");
svgM.appendChild(svgPath);
svgRoot.appendChild(svgM);
svgNode.setAttribute("marker-start", "url(#" + this.svgId_ + ")");
}
svgRoot.appendChild(svgNode);
this.svgRoot_ = svgRoot;
this.svgNode_ = svgNode;
}
// Set the overlay's div_ property to this DIV
this.div_ = div;
var panes = this.getPanes();
panes.overlayImage.appendChild(this.div_);
}
ArrowOverlay.prototype.draw = function() {
var overlayProjection = this.getProjection();
var p = overlayProjection.fromLatLngToDivPixel(this.location_);
var div = this.div_;
if (!div)
return;
if (!div.style)
return;
// Calculate the DIV coordinates of the ref point of our arrow
var x2 = p.x + this.dx_;
var y2 = p.y + this.dy_;
if (supportsVML()) {
this.vmlLine_.from = p.x + "px, " + p.y + "px";
this.vmlLine_.to = x2 + "px, " + y2 + "px";
}
else {
this.svgRoot_.setAttribute("style", "position:absolute; top:" + (p.y - 20) + "px; left:" + (p.x - 20) + "px");
}
}
ArrowOverlay.prototype.onRemove = function() {
if (this.handle_ != null) {
google.maps.eventclear.removeListener(this.handle_);
}
this.div_.parentNode.removeChild(this.div_);
}
ArrowOverlay.prototype.setVisible = function(v) {
if (v)
this.show();
else
this.hide();
}
ArrowOverlay.prototype.getVisible = function(v) {
if (this.div_) {
return (this.div_.style.display == "");
}
return false;
}
ArrowOverlay.prototype.hide = function() {
if (this.div_) {
this.div_.style.display = "none";
}
}
ArrowOverlay.prototype.show = function() {
if (this.div_) {
this.div_.style.display = "";
}
}
ArrowOverlay.prototype.setPosition = function(l) {
this.location_ = l;
this.draw();
}
ArrowOverlay.prototype.getPosition = function() {
return this.location_;
}
ArrowOverlay.prototype.setHeading = function(h) {
this.rotation_ = h || 0.0;
var r = this.rotation_ + 90; //compass to math
this.dx_ = 20 * Math.cos(r * Math.PI / 180); //other end of arrow line to point
this.dy_ = 20 * Math.sin(r * Math.PI / 180);
if (!supportsVML()) {
this.svgNode_.setAttribute("x2", 20 + this.dx_);
this.svgNode_.setAttribute("y2", 20 + this.dy_);
}
this.draw();
}
ArrowOverlay.prototype.getHeading = function() {
return this.rotation_;
}
ArrowOverlay.prototype.setTooltip = function(t) {
this.tooltip_ = t;
}
ArrowOverlay.prototype.getTooltip = function() {
return this.tooltip_;
}
ArrowOverlay.prototype.toggle = function() {
if (this.div_) {
if (this.div_.style.visibility == "hidden") {
this.show();
} else {
this.hide();
}
}
}
ArrowOverlay.prototype.fromDivPixelToLatLng = function(x, y) {
var overlayProjection = this.getProjection();
return overlayProjection.fromDivPixelToLatLng(new google.maps.Point(x, y));
}
ArrowOverlay.prototype.fromLatLngToContainerPixel = function(p) {
var overlayProjection = this.getProjection();
return overlayProjection.fromLatLngToContainerPixel(p);
}
// SVG utils from here http://appleton-static.appspot.com/static/simple_poly.js
// by Ben Appleton of Google
var SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
function supportsSVG() {
return document.implementation.hasFeature(
'http://www.w3.org/TR/SVG11/feature#Shape',
'1.1');
}
// VML utils from here http://appleton-static.appspot.com/static/simple_poly.js
// by Ben Appleton of Google
var VML_NAMESPACE = 'urn:schemas-microsoft-com:vml';
function createVmlElement(tagName, parent) {
var element = document.createElement(tagName);
parent.appendChild(element);
element.style['behavior'] = 'url(#default#VML)';
return element;
}
function supportsVML() {
if (supportsVML.result_ == null) {
if (!maybeCreateVmlNamespace()) {
return supportsVML.result_ = false;
}
// Create some VML. Its 'adj' property will be an object only when VML
// is enabled.
var div = document.createElement('DIV');
document.body.appendChild(div);
div.innerHtml = '<v:shape id="vml_flag1" adj="1" />';
var child = div.firstChild;
if (child) child.style['behavior'] = 'url(#default#VML)';
supportsVML.result_ = !child || (typeof child['adj'] == 'object');
div.parentNode.removeChild(div);
}
return supportsVML.result_;
}
function maybeCreateVmlNamespace() {
var hasVmlNamespace = false;
if (document.namespaces) {
for (var x = 0; x < document.namespaces.length; x++) {
var ns = document.namespaces(x);
if (ns.name == 'v') {
if (ns.urn == VML_NAMESPACE) {
hasVmlNamespace = true;
} else {
throw new Error('document namespace v: is required for VML ' +
'but has been reserved for ' + ns.urn);
}
}
}
if (!hasVmlNamespace) {
// Import namespace
hasVmlNamespace = true;
document.namespaces.add('v', VML_NAMESPACE);
}
}
return hasVmlNamespace;
}
Question
I can not figure out how to change the length of those arrow? Can I somehow add a length parameter to the function ArrowOverlay?
I would do something like this (scale also works with x, y):
<svg>
<g id="idG" transform="scale(1, 1)">
..your arrow
</g>
</svg>
document.getElementById("idG").setAttribute("transform", "scale(" + horizontalScale + "," + verticalScale + ")");
Example: http://k8.no-ip.org/stackoverflow/13540341.htm

Categories