pass a random generated variable to setInterval - javascript

I have animated a dynamic created element with setInterval. When the element is clicked I want it to change to a random direction (left, right, up or down).
I think the problem is that I canĀ“t pass the randomly created direction into the setInterval function.
The html here....
<div id="klicker"></div>
The JavaScript here.....
var box = document.getElementById("klicker");
var x = 1;
var startp = 200;
box.onclick = function() {
var newdiv = document.createElement('div');
document.body.appendChild(newdiv);
newdiv.style.width = 200 + 'px';
newdiv.style.height = 200 + 'px';
newdiv.style.backgroundColor = 'grey';
newdiv.style.position = 'absolute';
newdiv.style.left = startp + "px";
newdiv.style.top = startp + "px";
newdiv.setAttribute('id', 'runner')
var run = document.getElementById('runner');
var dire = 'right';
run.onclick = function() {
var mov = function() {
randoms();
};
function randoms() {
alert('ddddd');
var rnd = (Math.random() * 4) + 1; //ranom number 1-4
var rnd_down = Math.floor(rnd); //make it en integer
/*--- make each number a uniqe direction---*/
if (rnd_down == 1) {
dire = 'right';
} else if (rnd_down == 2) {
dire = 'left';
} else if (rnd_down == 3) {
dire = 'up';
} else {
dire = 'down';
}
};
var moveit = setInterval(function() {
movefunc();
}, 50);
function movefunc() {
/*----each direction will make the div travel in diffrent directions--*/
if (dire = 'right') {
x = x + 1;
newdiv.style.left = x + 'px';
} else if (dire = 'left') {
x = x - 1;
newdiv.style.left = x + 'px';
} else if (dire = 'up') {
x = x - 1;
newdiv.style.top = x + 'px';
} else {
x = x + 1;
newdiv.style.top = x + 'px';
}
};
};
}

function movefunc() {
/*----each direction will make the div travel in diffrent directions--*/
if (dire = 'right') {
x = x + 1;
newdiv.style.left = x + 'px';
} else if (dire = 'left') {
x = x - 1;
newdiv.style.left = x + 'px';
} else if (dire = 'up') {
x = x - 1;
newdiv.style.top = x + 'px';
} else {
x = x + 1;
newdiv.style.top = x + 'px';
}
};
Rookie mistake :) ( even though it's one of the most common error in programming, see #4 ) In your condition, you should use == and not = ( which is meant for assignation, == is made for comparison ). I'd even suggest you to use === which will also compare the types. ( 1 == '1' will return true while 1 === '1' will return false cause 1 is an integer type, and '1' is a char type )

Related

dynamically positioning and animating images in JavaScript

I'm trying to animate an image dynamically by assigning a slope and a starting position randomly. I don't understand why my image is not appearing and when I take the comments off the animate function my code won't run. Everything works properly except the animate functions at the bottom. Any help will be graciously accepted!
//Generate the table for the game
function createTable(difficulty, mineArray)
{
document.getElementById("buttons").style.visibility="hidden";
var time = 0.00;
var row = 0;
var size = 0;
var Lives = 0;
var column = 0;
var input = "";
var completion = 0;
var minesLeft = 0;
if(difficulty == 0)
{
Lives = 5;
size = 600;
row = 30;
column = 20;
}
else if (difficulty == 1)
{
Lives = 3;
size = 600;
row = 30;
column = 20;
}
else if (difficulty == 2)
{
Lives = 5;
size = 1000;
row = 40;
column = 25;
}
else if (difficulty == 3)
{
Lives = 3
size = 1000;
row = 40;
column = 25;
}
for (var i = 0; i < size; i++)
{
if (mineArray[i] == 9)
{
minesLeft = minesLeft + 1;
}
}
//Header
var head = document.getElementById("header").style.width = "100%"
document.getElementById("lives").innerHTML = "Lives: " + Lives;
document.getElementById("title").innerHTML = "Minesweeper Bullet Hell";
document.getElementById("time").innerHTML = "Time: " + time;
document.getElementById("footer").innerHTML = "Mines Left: " + minesLeft;
var name = document.getElementById("Name");
document.getElementById("names").innerHTML = "Welcome " + name.value;
//Main div (where the game is played)
var main = document.getElementById("main");
main.style.width = "100%"
main.style.height = "100%"
//Table
var div = document.getElementById("Table");
div.style.position = "absolute";
div.style.left = "5%";
div.style.top = "5%";
div.style.right = "5%";
div.style.verticalAlign = "true";
if(difficulty == 1 || difficulty == 0)
{
div.style.height = "900";
div.style.width = "600";
}
if(difficulty == 1 || difficulty == 0)
{
div.style.height = "1000";
div.style.width = "625";
}
div.style.zIndex="1";
//Iterate through columns
while(completion < size)
{
for (var i = 0; i < column; i++)
{
var tr = document.createElement('tr');
//Iterate through rows
for(var j = 0; j < row; j++)
{
var place = completion;
var td = document.createElement('td');
//For smaller minefield
if (size == 600)
{
td.style.width = "30";
td.style.height = "auto";
td.style.color = "blue";
//Add an image
var img = document.createElement('img');
img.src = "grey square.png";
img.style.display = "block";
img.style.height = "30";
img.style.width = "30";
td.appendChild(img);
}
//For larger minefield
else
{
td.style.width = "25";
td.style.height = "auto";
td.style.color = "blue";
//Add an image
var img = document.createElement('img');
img.src = "grey square.png";
img.style.display = "block";
img.style.height = "25";
img.style.width = "25";
td.appendChild(img);
}
//If it is a mine
if (mineArray[completion] == 9)
{
td.style.backgroundColor = "grey";
td.style.color = "red";
}
td.style.border = "1px solid #666666"
td.style.textAlign = "center"
tr.appendChild(td);
completion++;
}
//Think about adding an event listener instead of overlaying buttons?
main.appendChild(tr);
}
var cells = document.getElementsByTagName("td");
for (var j = 0; i < row; j++)
{
cells[j].addEventListener("click", function () {
//show number
var thiscol = this.cellIndex;
var thisrow = this.parentNode.rowIndex;
console.log("Clicked at " + thisrow + thiscol);
var cell = main.rows[thisrow].cells[thiscol];
cell.innerHTML = mineArray[(thisrow * row) + thiscol];
})
}
}
setTimeout(function(){bullets()}, 100);
}
function bullets()
{
//randomly generate bullets including starting positions, direction, and trajectory
//Generate starting position
//Generate starting edge
var xpos;
var ypos;
var bullets;
var slopes
var edge = (Math.floor(Math.random() * 4) + 1)
var bullet = document.createElement('img')
var screen = docuemnt.getElementById("bullets");
bullet.src = "blank.png"
bullet.style.position = "relative"
switch (edge)
{
//left edge
case 1:
bullet.style.left = 20 + "px";
ypos = (Math.floor(Math.random() * 100) + 1);
bullet.style.top = ypos + "px";
bullet.id = "left";
break;
//top edge
case 2:
bullet.style.top = 20 + "px";
xpos = (Math.floor(Math.random() * 100) + 1);
bullet.style.right = xpos + "px";
bullet.id = "top"
break;
//right edge
case 3:
bullet.style.right = 20 + "px";
ypos = (Math.floor(Math.random() * 100) + 1);
bullet.style.top = ypos+ "px";
bullet.id = "right";
break;
//bottom edge
case 4:
bullet.style.bottom = 20 + "px";
xpos = (Math.floor(Math.random() * 100) + 1);
bullet.style.right = xpos + "px";
bullet.id = "bottom";
break;
}
//Get the slope
var xslope = (Math.floor(Math.random() * 20) + 5);
var yslope = (Math.floor(Math.random() * 20) + 5);
bullets.append(bullet);
slopes.append(xpos);
slopes.append(ypos);
screen.appendChild(bullet);
//startAnimation(slopes, bullets);
}
/*
function startAnimation(var slopes, var bullets)
{
var j = 0;
var posy;
var posx;
var id;
for(i = 0; i < bullets.size(); i++)
{
while(j < (j+2))
{
id = bullets(i).id;
switch(id)
{
case "left":
posx = bullets(i).style.left;
posy = bullets(i).style.top;
bullets(i).style.left = posx + slopes(j);
bullets(i).style.top = posy + slopes(j+1);
break;
case "top":
posx = bullets(i).style.left;
posy = bullets(i).style.top;
bullets(i).style.left = posx + slopes(j);
bullets(i).style.top = posy + slopes(j+1);
break;
case "right":
posx = bullets(i).style.right;
posy = bullets(i).style.top;
bullets(i).style.right = posx + slopes(j);
bullets(i).style.top = posy + slopes(j+1);
break;
case "bottom":
posx = bullets(i).style.left;
posy = bullets(i).style.bottom;
bullets(i).style.left = posx + slopes(j);
bullets(i).style.bottom = posy + slopes(j+1);
break;
}
j += 2;
}
}
}*/
Looks like there could be a few things making startAnimation stop your script. Here's a few changes to try out:
In your startAnimation function declaration try removing the var keyword before the parameters. So you'd have:
function startAnimation(slopes, bullets) {
Within the for loop, use the .length property to check the array length rather than .size() (see: Array.size() vs Array.length)
The while loop is creating an infinite loop, because the condition (j < (j+2)) will always be true, since it's checking the current value of j. It might be easier to swap this out with a for loop.
Next, within the function, replace the parentheses with square brackets for accessing array indexes (replace bullets(i) with bullets[i] and slopes(j) with slopes[j]. By using parentheses, the JavaScript interpreter is attempting to call these variables as functions. Since you already have a function called bullets I'd recommend renaming either the function or your local variable / parameter to avoid the complexity of dealing with variable name conflicts and scope (more info: What is the scope of variables in JavaScript? )

jqplotToImageCanvas not working in chrome version 47.0 and firefox 41.0.1

I have multiple charts generated by PHPChart but when i use from print option to print the chart in pdf, and png in chrome it is not working for bar chart types but work for line chart, but if there is one bar chart it works, in Firefox it is not working for vertical bar chart but work for horizontal bar chart.
all type of charts are generated dynamically using database data there is no difference in case of html wrapper tags.
when i click on export button browser hung up.
The javascript code:
function getImageData(obj, type, title)
{
var str;
imgtype = type;
if (type == 'jpg-pdf')
{
imgtype = 'jpg';
type = 'pdf';
}
var imgCanvas = $('#'+obj).jqplotToImageCanvas();
if (imgCanvas) {
str = imgCanvas.toDataURL("image/"+imgtype);
}
else {
str = null;
}
$('#pngdata').val(str);
$('#imgtype').val(type);
$('#imgtitle').val(title);
$('#imgform').submit();
}
and the jqplot function
$.fn.jqplotToImageCanvas = function(options) {
options = options || {};
var x_offset = (options.x_offset == null) ? 0 : options.x_offset;
var y_offset = (options.y_offset == null) ? 0 : options.y_offset;
var backgroundColor = (options.backgroundColor == null) ? 'rgb(255,255,255)' : options.backgroundColor;
if ($(this).width() == 0 || $(this).height() == 0) {
return null;
}
// excanvas and hence IE < 9 do not support toDataURL and cannot export images.
if ($.jqplot.use_excanvas) {
return null;
}
var newCanvas = document.createElement("canvas");
var h = $(this).outerHeight(true);
var w = $(this).outerWidth(true);
var offs = $(this).offset();
var plotleft = offs.left;
var plottop = offs.top;
var transx = 0, transy = 0;
// have to check if any elements are hanging outside of plot area before rendering,
// since changing width of canvas will erase canvas.
var clses = ['jqplot-table-legend', 'jqplot-xaxis-tick', 'jqplot-x2axis-tick', 'jqplot-yaxis-tick', 'jqplot-y2axis-tick', 'jqplot-y3axis-tick',
'jqplot-y4axis-tick', 'jqplot-y5axis-tick', 'jqplot-y6axis-tick', 'jqplot-y7axis-tick', 'jqplot-y8axis-tick', 'jqplot-y9axis-tick',
'jqplot-xaxis-label', 'jqplot-x2axis-label', 'jqplot-yaxis-label', 'jqplot-y2axis-label', 'jqplot-y3axis-label', 'jqplot-y4axis-label',
'jqplot-y5axis-label', 'jqplot-y6axis-label', 'jqplot-y7axis-label', 'jqplot-y8axis-label', 'jqplot-y9axis-label' ];
var temptop, templeft, tempbottom, tempright;
for (var i = 0, j = clses.length; i < j; i++) {
$(this).find('.'+clses[i]).each(function() {
temptop = $(this).offset().top - plottop;
templeft = $(this).offset().left - plotleft;
tempright = templeft + $(this).outerWidth(true) + transx;
tempbottom = temptop + $(this).outerHeight(true) + transy;
if (templeft < -transx) {
w = w - transx - templeft;
transx = -templeft;
}
if (temptop < -transy) {
h = h - transy - temptop;
transy = - temptop;
}
if (tempright > w) {
w = tempright;
}
if (tempbottom > h) {
h = tempbottom;
}
});
}
newCanvas.width = w + Number(x_offset);
newCanvas.height = h + Number(y_offset);
var newContext = newCanvas.getContext("2d");
newContext.save();
newContext.fillStyle = backgroundColor;
newContext.fillRect(0,0, newCanvas.width, newCanvas.height);
newContext.restore();
newContext.translate(transx, transy);
newContext.textAlign = 'left';
newContext.textBaseline = 'top';
function getLineheight(el) {
var lineheight = parseInt($(el).css('line-height'), 10);
if (isNaN(lineheight)) {
lineheight = parseInt($(el).css('font-size'), 10) * 1.2;
}
return lineheight;
}
function writeWrappedText (el, context, text, left, top, canvasWidth) {
var lineheight = getLineheight(el);
var tagwidth = $(el).innerWidth();
var tagheight = $(el).innerHeight();
var words = text.split(/\s+/);
var wl = words.length;
var w = '';
var breaks = [];
var temptop = top;
var templeft = left;
for (var i=0; i<wl; i++) {
w += words[i];
if (context.measureText(w).width > tagwidth && w.length > words[i].length) {
breaks.push(i);
w = '';
i--;
}
}
if (breaks.length === 0) {
// center text if necessary
if ($(el).css('textAlign') === 'center') {
templeft = left + (canvasWidth - context.measureText(w).width)/2 - transx;
}
context.fillText(text, templeft, top);
}
else {
w = words.slice(0, breaks[0]).join(' ');
// center text if necessary
if ($(el).css('textAlign') === 'center') {
templeft = left + (canvasWidth - context.measureText(w).width)/2 - transx;
}
context.fillText(w, templeft, temptop);
temptop += lineheight;
for (var i=1, l=breaks.length; i<l; i++) {
w = words.slice(breaks[i-1], breaks[i]).join(' ');
// center text if necessary
if ($(el).css('textAlign') === 'center') {
templeft = left + (canvasWidth - context.measureText(w).width)/2 - transx;
}
context.fillText(w, templeft, temptop);
temptop += lineheight;
}
w = words.slice(breaks[i-1], words.length).join(' ');
// center text if necessary
if ($(el).css('textAlign') === 'center') {
templeft = left + (canvasWidth - context.measureText(w).width)/2 - transx;
}
context.fillText(w, templeft, temptop);
}
}
function _jqpToImage(el, x_offset, y_offset) {
var tagname = el.tagName.toLowerCase();
var p = $(el).position();
var css = window.getComputedStyle ? window.getComputedStyle(el, "") : el.currentStyle; // for IE < 9
var left = x_offset + p.left + parseInt(css.marginLeft, 10) + parseInt(css.borderLeftWidth, 10) + parseInt(css.paddingLeft, 10);
var top = y_offset + p.top + parseInt(css.marginTop, 10) + parseInt(css.borderTopWidth, 10)+ parseInt(css.paddingTop, 10);
var w = newCanvas.width;
// var left = x_offset + p.left + $(el).css('marginLeft') + $(el).css('borderLeftWidth')
// somehow in here, for divs within divs, the width of the inner div should be used instead of the canvas.
if ((tagname == 'div' || tagname == 'span') && !$(el).hasClass('jqplot-highlighter-tooltip')) {
$(el).children().each(function() {
_jqpToImage(this, left, top);
});
var text = $(el).jqplotChildText();
if (text) {
newContext.font = $(el).jqplotGetComputedFontStyle();
newContext.fillStyle = $(el).css('color');
writeWrappedText(el, newContext, text, left, top, w);
}
}
// handle the standard table legend
else if (tagname === 'table' && $(el).hasClass('jqplot-table-legend')) {
newContext.strokeStyle = $(el).css('border-top-color');
newContext.fillStyle = $(el).css('background-color');
newContext.fillRect(left, top, $(el).innerWidth(), $(el).innerHeight());
if (parseInt($(el).css('border-top-width'), 10) > 0) {
newContext.strokeRect(left, top, $(el).innerWidth(), $(el).innerHeight());
}
// find all the swatches
$(el).find('div.jqplot-table-legend-swatch-outline').each(function() {
// get the first div and stroke it
var elem = $(this);
newContext.strokeStyle = elem.css('border-top-color');
var l = left + elem.position().left;
var t = top + elem.position().top;
newContext.strokeRect(l, t, elem.innerWidth(), elem.innerHeight());
// now fill the swatch
l += parseInt(elem.css('padding-left'), 10);
t += parseInt(elem.css('padding-top'), 10);
var h = elem.innerHeight() - 2 * parseInt(elem.css('padding-top'), 10);
var w = elem.innerWidth() - 2 * parseInt(elem.css('padding-left'), 10);
var swatch = elem.children('div.jqplot-table-legend-swatch');
newContext.fillStyle = swatch.css('background-color');
newContext.fillRect(l, t, w, h);
});
// now add text
$(el).find('td.jqplot-table-legend-label').each(function(){
var elem = $(this);
var l = left + elem.position().left;
var t = top + elem.position().top + parseInt(elem.css('padding-top'), 10);
newContext.font = elem.jqplotGetComputedFontStyle();
newContext.fillStyle = elem.css('color');
writeWrappedText(elem, newContext, elem.text(), l, t, w);
});
var elem = null;
}
else if (tagname == 'canvas') {
newContext.drawImage(el, left, top);
}
}
$(this).children().each(function() {
_jqpToImage(this, x_offset, y_offset);
});
return newCanvas;
};
kindly help me.

Add links to images in array

I'm trying to add links to the images in my JS array so that, when clicked, they direct you to a info page.
I tried to use the following code but the images won't show.
var WorkArray = new Array(['work/01.png',"http://www.stackoverflow.com"],
['work/02.png',"http://www.stackoverflow.com"],
['work/03.png',"http://www.stackoverflow.com"],
['work/04.png',"http://www.stackoverflow.com"]);
If I remove the links the images do show.
I'm using a variation of this code: http://bouncingdvdlogo.com/
Here is my full code:
var width = 400;
var height = 400;
var swoosh = 4;
var stopafter=0; //set time in seconds before image disappears. Use 0 for never
var maxswoosh = 50;
var xMax;
var yMax;
var xPos = 0;
var yPos = 0;
var xDir = 'right';
var yDir = 'down';
var screenSavouring = true;
var tempswoosh;
var newXDir;
var newYDir;
function setupShit() {
if (document.all) {
xMax = document.body.clientWidth
yMax = document.body.clientHeight
document.all("work").style.visibility = "visible";
}
else if (document.layers||document.getElementById) {
xMax = window.innerWidth-0;
yMax = window.innerHeight;
if (document.getElementById)
document.getElementById("work").style.visibility="visible"
else
document.layers["work"].visibility = "show";
}
setTimeout('moveIt()',500);
}
function moveIt() {
if (screenSavouring == true) {
calculatePosition();
if (document.all) {
document.all("work").style.left = xPos + document.body.scrollLeft;
document.all("work").style.top = yPos + document.body.scrollTop;
}
else if (document.layers) {
document.layers["work"].left = xPos + pageXOffset;
document.layers["work"].top = yPos + pageYOffset;
}
else if (document.getElementById) {
document.getElementById("work").style.left = xPos + pageXOffset;
document.getElementById("work").style.top = yPos + pageYOffset;
}
doit=setTimeout('moveIt()',30);
}
}
function calculatePosition() {
if (xDir == "right") {
if (xPos > (xMax - width - swoosh)) {
xDir = "left";
cC();
}
}
else if (xDir == "left") {
if (xPos < (0 + swoosh)) {
xDir = "right";
cC();
}
}
if (yDir == "down") {
if (yPos > (yMax - height - swoosh)) {
yDir = "up";
cC();
}
}
else if (yDir == "up") {
if (yPos < (0 + swoosh)) {
yDir = "down";
cC();
}
}
if (xDir == "right") {
xPos = xPos + swoosh;
}
else if (xDir == "left") {
xPos = xPos - swoosh;
}
else {
xPos = xPos;
}
if (yDir == "down") {
yPos = yPos + swoosh;
}
else if (yDir == "up") {
yPos = yPos - swoosh;
}
else {
yPos = yPos;
}
}
if (document.all||document.layers||document.getElementById){
window.onload = setupShit;
window.onresize = new Function("window.location.reload()");
}
var WorkArray = new Array(['work/01.png',"http://www.stackoverflow.com", "Your text goes here"],
['work/02.png',"http://www.stackoverflow.com", "Your text goes here"],
['work/03.png',"http://www.stackoverflow.com", "Your text goes here"],
['work/04.png',"http://www.stackoverflow.com", "Your text goes here"]);
var nelements = WorkArray.length;
preload_image_object = new Image();
var i = 0;
for(i=0; i<=nelements; i++) {
preload_image_object.src = WorkArray[i];
}
var currentImage = 0
function cC() {
currentImage = (currentImage + 1) % WorkArray.length;
document.getElementById("work").style.backgroundImage="url('"+WorkArray[currentImage]+"')";
}
Thanks!
Try replacing your for loop with below
for(i=0; i<nelements; i++) {
preload_image_object.src = WorkArray[i][0];
}
Also Replace function cC() with below:
function cC() {
var nelements = WorkArray.length;
var rdmnum = Math.floor(Math.random() * nelements);
var currentImage = rdmnum++;
if (currentImage == nelements) {
rdmnum = Math.floor(Math.random() * nelements);
}
currentImage = (currentImage + 1) % WorkArray.length;
document.getElementById("work").style.backgroundImage = "url('" + WorkArray[currentImage][0] + "')";
}

Gradual Increase/Decrease javascript 2 elements

I'm trying to gradually increase the elements of 2 id's in javascript using a Interval.
I'm passing two id's for the elements. I'm trying write conditionals so that depending on the position the width of the elements gradually increase in the direction dependent of the position.
if the passed element position is smaller than the oldPosition I want the the left element to decrease and the right element to increase gradually. And the opposite if the passed element position is bigger than the oldPosition.
Note this, is an extension of my old problem which was fixed :) (Javascript gradual width increase)
Heres what ive got
function grow(elementL, elementR, elementText, position)
{
window.loopTimer = setInterval(function() {
growInner(elementL, elementR, position);
/* fadeOut(elementText); */
}, 25);
}
var oldPosition = 0;
function growInner(elementL, elementR, position)
{
var htL = parseInt(document.getElementById(elementL).style.width,10);
var htR = parseInt(document.getElementById(elementR).style.width,10);
var movementL =0;
var movementR =0;
if(position < oldPosition)
{
movementL = htL + 10;
movementR = htR - 10;
}
if(position > oldPosition)
{
movementL = htL - 10;
movementR = htR + 10;
}
if(position == 1 && htL < 600 || rtL > 250){
document.getElementById(elementL).style.width = movementL + 'px';
document.getElementById(elementR).style.width = movementR + 'px';
oldPosition = position;
}
else if(position == 2 && htL < 550 || rtL > 300){
document.getElementById(elementL).style.width = movementL + 'px';
document.getElementById(elementR).style.width = movementR + 'px';
oldPosition = position;
}
else if(position == 3 && htL < 300 || rtL > 550){
document.getElementById(elementL).style.width = movementL + 'px';
document.getElementById(elementR).style.width = movementR + 'px';
oldPosition = position;
}
else if(position == 4 && htL < 250 || rtL > 600){
document.getElementById(elementL).style.width = movementL + 'px';
document.getElementById(elementR).style.width = movementR + 'px';
oldPosition = position;
}
else{
clearInterval(loopTimer);
return false;
}
}
My previous code position conditionals were not correctly taking into account the width growth direction in terms of the position clicked. I reduced the variable documnentGet calls and added some security with the boolean returns so that it couldn't start another timer until the previous one had stopped.
I have a jsFiddle link for it but I cannot seem to get it working.
http://jsfiddle.net/2mRsG/3/
function moveStart(elementL, elementR, position)
{
var moveTimer = setInterval(function() {
if (!movingProcess(elementL, elementR, position)) {
clearInterval(moveTimer);
}
}, 20);
}
var oldPos = 1;
function movingProcess(elementL, elementR, position) {
moving = true;
var htL = parseInt(document.getElementById(elementL).style.width,10);
var htR = parseInt(document.getElementById(elementR).style.width,10);
var left = document.getElementById(elementL);
var right = document.getElementById(elementR);
if(position==1){
var movementL = htL + 5;
var movementR = htR - 5;
left.style.width = movementL + 'px';
right.style.width = movementR + 'px';
if (movementL >= 600 && position==1)
{
oldPos = 1;
moving = false;
return false;
}
}
else if(position==2 && oldPos > 2){
var movementL = htL + 5;
var movementR = htR - 5;
left.style.width = movementL + 'px';
right.style.width = movementR + 'px';
if (movementL >= 500)
{
oldPos = 2;
moving = false;
return false;
}
}
else if(position==2 && oldPos == 1){
var movementL = htL - 5;
var movementR = htR + 5;
left.style.width = movementL + 'px';
right.style.width = movementR + 'px';
if (movementR >= 300)
{
oldPos = 2;
moving = false;
return false;
}
}
else if(position==3 && oldPos < 3){
var movementL = htL - 5;
var movementR = htR + 5;
left.style.width = movementL + 'px';
right.style.width = movementR + 'px';
if (movementR >= 500)
{
oldPos = 3;
moving = false;
return false;
}
}
else if(position==3 && oldPos ==4){
var movementL = htL + 5;
var movementR = htR - 5;
left.style.width = movementL + 'px';
right.style.width = movementR + 'px';
if (movementL >= 300)
{
oldPos = 3;
moving = false;
return false;
}
}
else if(position==4){
var movementL = htL - 5;
var movementR = htR + 5;
left.style.width = movementL + 'px';
right.style.width = movementR + 'px';
if (movementR >= 600)
{
oldPos = 4;
moving = false;
return false;
}
}
return true;
}

Javascript tooltip positioning

I have integrated a tooltip on my website.
I am facing an issue as to the positioning from the top.
Below is the script that I have used.
var tooltip = function () {
var id = 'tt';
var top = 12;
var left = 3;
var maxw = 300;
var speed = 10;
var timer = 20;
var endalpha = 95;
var alpha = 0;
var tt, t, c, b, h;
var ie = document.all ? true : false;
return {
show: function (v, w) {
//debugger
if (tt == null) {
tt = document.createElement('div');
tt.setAttribute('id', id);
t = document.createElement('div');
t.setAttribute('id', id + 'top');
c = document.createElement('div');
c.setAttribute('id', id + 'cont');
b = document.createElement('div');
b.setAttribute('id', id + 'bot');
tt.appendChild(t);
tt.appendChild(c);
tt.appendChild(b);
document.body.appendChild(tt);
tt.style.opacity = 0;
tt.style.filter = 'alpha(opacity=0)';
document.onmousemove = this.pos;
}
tt.style.display = 'block';
var imagethemefolder;
if (window.theForm.ctl00$ddlSiteSkin) {
imagethemefolder = window.theForm.ctl00$ddlSiteSkin.value;
}
else {
imagethemefolder = window.parent.theForm.ctl00$ddlSiteSkin.value;
}
if (v == 'Save') {
v = '<img src="../Styles/Themes/' + imagethemefolder + '/Images/saveTooltip.png" class="ttImgPlacement" alt="" /><b class="ttTitle">Save</b><span class="ttContent">Select this option to Save the Records in database</span></strong>'
}
c.innerHTML = v;
//tt.style.width = w ? w + 'px' : 'auto';
if (!w && ie) {
t.style.display = 'none';
b.style.display = 'none';
//tt.style.width = tt.offsetWidth;
t.style.display = 'block';
b.style.display = 'block';
}
//if (tt.offsetWidth > maxw) {
tt.style.width = maxw + 'px'
//}
h = parseInt(tt.offsetHeight) + top;
clearInterval(tt.timer);
tt.timer = setInterval(function () { tooltip.fade(1) }, timer);
},
pos: function (e) {
//debugger
var u = ie ? event.clientY + document.documentElement.scrollTop : e.pageY;
var l = ie ? event.clientX + document.documentElement.scrollLeft : e.pageX;
if (ie) {
if ((event.screenY - event.offsetY) > 100) {
var ci = Math.ceil(event.screenY - event.offsetY);
if (GetRadWindow()) {
//var height = document.parentWindow.GetRadWindow().get_height()
ci = 60;
}
var restval = ci % 100;
restval = restval.roundTo(10) / 20;
if (restval >= 1) {
restval = restval - 1;
}
ci = ci.roundToLess(100);
tt.style.top = (ci + (20 * restval)) + 'px';
}
else {
tt.style.top = 50 + 'px';
}
}
else if (navigator.userAgent.indexOf('Firefox') != -1) {
//debugger
if ((e.screenY - e.layerY) > 100) {
var ci = Math.ceil(e.screenY - e.layerY);
if (GetRadWindow()) {
ci = 60;
}
var restval = ci % 100;
restval = restval.roundTo(10) / 20;
if (restval >= 1) {
restval = restval - 1;
}
ci = ci.roundToLess(100);
tt.style.top = (ci + (20 * restval)) + 'px';
}
else {
tt.style.top = 50 + 'px';
}
}
else {
if ((e.screenY) > 100) {
//debugger
var ci = Math.ceil(e.screenY);
if (GetRadWindow()) {
//debugger
ci = 80;
}
var restval = ci % 100;
restval = restval.roundTo(10) / 20;
if (restval >= 2) {
restval = restval - 2;
}
ci = ci.roundToLess(100);
tt.style.top = (ci + (20 * restval)) + 'px';
}
else {
tt.style.top = 50 + 'px';
}
}
//tt.style.top = ie ? (event.screenY - event.offsetY - top) + 'px' : (e.screenY - (e.layerY - top + 5)) + 'px';
if (l > (document.documentElement.offsetWidth - 305)) {
tt.style.left = (l + left - 300) + 'px';
}
else {
tt.style.left = (l + left) + 'px';
}
},
fade: function (d) {
var a = alpha;
if ((a != endalpha && d == 1) || (a != 0 && d == -1)) {
var i = speed;
if (endalpha - a < speed && d == 1) {
i = endalpha - a;
} else if (alpha < speed && d == -1) {
i = a;
}
alpha = a + (i * d);
tt.style.opacity = alpha * .01;
tt.style.filter = 'alpha(opacity=' + alpha + ')';
} else {
clearInterval(tt.timer);
if (d == -1) { tt.style.display = 'none' }
}
},
hide: function () {
clearInterval(tt.timer);
tt.timer = setInterval(function () { tooltip.fade(-1) }, timer);
}
};} ();
I have made lot of permutations and combinations to this and have made it work almost fine.
The only issue is that the top positioning is not displaying properly in browsers.
I am struck only for that part.
You can use the following script.
<script type="text/javascript">
$(document).ready(function() {
$('#id').qtip({
content: 'New Request Alt+N',
position: {
corner: {
target: 'topRight',
tooltip: 'bottomLeft'
}
},
show: 'mouseover',
hide: 'mouseout',
style: {
background: '#A2D959',
color: 'black',`enter code here`
textAlign: 'center',
border: {
radius: 4,
color: '#A2D959'
},
tip: 'bottomLeft'
}
});
});
</script>
for more details :
http://codersshop.blogspot.in/2013/06/tooltip-implementation-you-can-download.html

Categories