jquery.event.drag - Run script for every X pixels dragged - javascript

I am using jquery.event.drag.js in a project I am creating, and I am trying to figure out a way to run a script for every X amount of pixels I have dragged. I am using only the X axis for this. Here is some code I have right now.
$('body').drag(function( ev, dd ){
var newcell = currentCell;
var dragOffset = Math.floor(dd.offsetX / 100);
if (dragOffset >= 1) {
alert("Dragged 100px");
}
newcell += dragOffset;
$('#info').html(dragOffset + " | " + dd.offsetX);
updateStack(newcell, magnifyMode);
});
This works, however, since this script runs for every pixel dragged, this runs the alert after 100px dragged, but from then on it runs for every pixel I drag it after that. I'm looking for a way to only run it for every 100px I drag it. Any ideas?

have an outside variable tracking when you last did the alert:
var chunkedOffset = 0;
$('body').drag(function( ev, dd ){
var newcell = currentCell;
var dragOffset = dd.offsetX / 100;
if (dragOffset > chunkedOffset) {
chunkedOffset = dragOffset;
alert("Dragged 100px");
}
newcell += dragOffset;
$('#info').html(dragOffset + " | " + dd.offsetX);
updateStack(newcell, magnifyMode);
});

I'm not entirely familiar with drag.js, but, you could just use modulus division to make sure its every 100px.
x % 100 - will be 0 if divisible by 100, so
if(dd.offsetX % 100 == 0)
{
alert("Dragged 100px");
}

Related

Insert calculated values into different DOM elements

I have a working formula that calculates PMT based on the interest rates, I see that it's working because the output in the console.log is correct. My question is, how can I take the results in the console.log and place each amount into it's own div?
For example, the first div is 4.125%, I want to display the dollar amount in the div right after it, then for the 3.125%, I want to display the dollar amount right after it and so on
Here is what I have http://jsfiddle.net/yecDj/19/
var p = 1000;
var thirtyYear = parseFloat(-Math.abs(360)); /*30 YR term in months*/
for (var i = 1; i < 5; i++) {
var costPerThousand = "$" + (p * ((parseFloat(document.getElementById('rate' + i).innerHTML) / 100 / 12) / (1 - (Math.pow((1 + (parseFloat(document.getElementById('rate' + i).innerHTML) / 100 / 12)), thirtyYear))))).toFixed(2);
console.log(costPerThousand);
}
I'm looking to do this in javascript only
Replace your console.log with:
document.querySelector('#rate' + i).textContent = costPerThousand;
querySelector
textContent
Fiddle

Display images according to number set from interval

i try to display from svg ,layers according to numbers set from an interval.I have 2 random numbers (left and right) set to display from interval (10,99) both.That works good,but, i need to display layer 1(banane1) from svg if left || right belongs to interval (10,20) , then if left || right belongs to interval (20,30) to display layer 2(banane2) from svg and so on untill left || right belongs to interval (90,99) to display layer 9(banane9). There are 9 intervals and 9 layers from svg to display. Code i wrote looks like :
FIDDLE: http://jsfiddle.net/r68Bg/
for(var i = 0; i < 2; i++){
panouri = document.getElementById('panou' + i);
svgDoc = panouri.contentDocument;
}
where panou0 and panou1 are 2 svg that has layers 2 numbers where i display later random numbers set from intervals and 9 layers each with different content which must be displayed according to random numbers.
function randomIntFromInterval(min,max)
{
return Math.floor(Math.random()*(max-min+1)+min);
};
function conditions(){
left = randomIntFromInterval(10,99);
right = randomIntFromInterval(10,99);
for(var i = 0; i < 2; i++){
ecuations.push(left, right);
randoms = document.getElementById("panou" + i).contentDocument;
numere = randoms.getElementById("number");
numere.textContent = ecuations[i];
}
};
where i add into my svg (panou0 and panou1) randoms numbers from set intervals.
function setBananeState(state)
{
for(var i = 1; i < 10; i++){
svgItem = svgDoc.getElementById("banane" + i);
svgItem.setAttribute("display", "none");
svgItem = svgDoc.getElementById(state);
svgItem.setAttribute("display", "inline");
}
};
function getBanane(){
if(left || right >= 30 && left || right <= 40){
bananeState = "banane3";
setBananeState(bananeState);
}
};
Here i have all layers from svgs which contains bananas to display according to random number given and a function getBanane() which has condition to display layer1 (banane1 by id from svg) if random number is from interval (10,20).Unfortunately this doesnt work...and i must have 8 more condition to display layers from svg if random numbers are from different interval
This isn't going to work:
if(left || right == randomIntFromInterval(10,20)){
What you are doing here is a ORing left with right which will give you a boolean which you are then comparing to randomIntFromInterval. I think what you are trying to do is this:
var interval = randomIntFromInterval(10,20);
if (left == interval || right == interval) {
EDIT: Okay you changed your question. So now this:
if(left || right >= 30 && left || right <= 40){
Is not right, you can't write an if statement like that in javascript, or in most (probably all) programming languages. You can't say "if a or b is greater than x", like you would in normal English speech because it's ambiguous. You have to explicitly say "if (a is greater than x) or (b is greater than x)". So your if statement above needs to become:
if ((left >= 30 || right >=30) && (left <= 40 || right <= 40)) {
Although I'm not sure this is exactly what you want either. Because here if left==0 and right==41, then this statement would be true. I think you want either left or right to be in the interval, so your best check would be:
if ((left >= 30 && left <= 40) || (right >= 30 && right <= 40)) {

JQuery Algorithm for changing DIV offset if still in view

hopefully you may be able to assist.
My example code:
http://jsfiddle.net/RevengerTT/YZtyj/1/
I'm trying to work out an algorithm which will capture the offset().left and work out if it has moved the DIV "stretchflex" out of the view state.
I'm really struggling to get my head around this (started JQuery coding today after watching a quick video).
I've worked in three variables I think should give me the values I need, but the issue I'm having is that var z = $("#stretchflex").width() doesn't represent the "actual" width of the DIV, but the visible width of it.
Can anyone see where I'm going wrong?
$("#SFPanLeft").click(function () {
var x = $("#SFHolder").width()
var y = $("#stretchflex").offset().left
var z = $("#stretchflex").width()
$("#x").html("X : " + x.toString());
$("#y").html("Y : " + y.toString());
$("#z").html("Z : " + z.toString());
if (x > (z + y)) { /* <----This is the bit which doesn't work */
var left = $("#stretchflex").offset().left
left -= 176
$("#stretchflex").css({
left: left + 'px'
});
};
});
Many thanks for your help in advance - can't think how many times I've found the answers I need by searching this site :)
Think I've sorted this.
Just in case anyone finds this...
$("#SFPanLeft").click(function () {
var x = $("#SFHolder").width();
var y = $("#stretchflex").offset().left;
var z = $("#stretchflex").get(0).scrollWidth; /* using scrollWidth fixes */
$("#x").html("X : " + x.toString());
$("#y").html("Y : " + y.toString());
$("#z").html("Z : " + z.toString());
if (x < (z + y)) { /* updated algorithm */
var left = $("#stretchflex").offset().left
left -= 176
$("#stretchflex").css({
left: left + 'px'
});
};
});

jQuery - make div get wider every second

First of all, I have to warn you, my English is not so good...
OK, here is my problem: I have a progress bar that gets wider every second based on percents.
Every second I want to add 1.67 / [max] percent.
[max] = 100% (how many minutes it'll take).
(if [max] = 10 - the progress bar will take 10 minutes)
My code WORKS, but only if the number (after dividing) is bigger than 0.3 (something like that).
So it means that if the progress bar will take 1 minute ([max] = 1) the code will work, because the number is 1.67 after dividing.
But if I make max to be 15 minutes, it wont work - WHY?!
This is my code: (I added some comments to make it easier)
<script>
function updateProgress() {
/*Get Progress Width (in percents)*/ var progress = ( 100 * parseFloat($('#arena_bar').css('width')) / parseFloat($('#arena_bar').parent().css('width')) );
var corrent = progress;
var max = 1; // one minute
var add = 1.67 / max;
if (progress < 100) {
corrent += add;
$("#arena_bar").css("width", corrent + "%");
setTimeout(updateProgress, 1000); // update every second
}
}
updateProgress();
</script>
Please Help !
The problem is that you're not making the width grow enough for the percentage to change in CSS, so it stays constant (at least that's what it looks like). The thing is, you don't really need all that.
Here's a js fiddle of your code, changed to work. I changed the time delay to make it run faster, you can change it back to 1000ms if you want.
And the code:
HTML:
<div style="width:400px; background-color:black">
<div id="arena_bar" style="background-color:navy; width:10px"> </div>
</div>
JS:
/*Get Progress Width (in percents)*/ var corrent = ( 100 * parseFloat($('#arena_bar').css('width')) / parseFloat($('#arena_bar').parent().css('width')) );
function updateProgress() {
var max = 15; // one minute
var add = 1.67 / max;
if (corrent < 100) {
corrent += add;
$("#arena_bar").css("width", corrent + "%");
setTimeout(updateProgress, 50); // update every second
}
}
updateProgress();
For the record, jQuery is not setting your computed widths as real percentage values, it sets them using pixel values.
In this example you can see your written widths and the read ones.
function updateProgress() {
var progress = (parseInt($('#arena_bar').css('width')) / parseInt($('#arena_bar').parent().css('width')))*100;
$('.progress').text('Read: ' + progress + ' %');
var max = 1;
var add = 1.67 / max;
if (progress < 100) {
progress += add;
$('.debug').html('Written: ' + progress + ' %');
$("#arena_bar").css("width", progress + "%");
setTimeout(updateProgress, 1000); // update every second
}
}
updateProgress();
http://jsfiddle.net/9PjqZ/1/
As you can see there is a difference to the values when you read them in the next function call. There are no problems when the difference between written and read values is above an unknown limit. When they come too close to each other your idea won't work anymore.
You need to save the current percentage outside the css and only write to css but not read from css.

Use jquery to dynamically number table columns diagonally

Hi there fellow coders,
I'm looking to find a way to fill a pre-built dynamic blank table with numbering (and colouring if possible) like so:
As you can see the numbering is ascending order diagonally. I know there's probably some way to calculate the number based on the tables td index but can't quite figure out how to do that for every column diagonally. Any help would be appreciated.
Update: Ok back from my Holidays. Thanks to all you clever people for your replies. As I'm sure you've all had to experience the pain in the neck clients can be, I've been told the spec has changed(again). This being the case I've had to put the grid/matrix into a database and output using a pivot table. Every square has to be customizable color-wise.
Nothing is going to waste though I have learnt quite a few nifty new javascript/jquery tricks from your responses I didn't know about before, so thanks, and I'll be sure to pay it forward :)
Here's what I came up with in the end.
Given you said "colouring if possible" I'll provide an example solution that doesn't do colours quite the way you want (it does it in a way that I found easier to code and more attractive to look at) but which does handle all the numbering correctly for varying table sizes.
The function below assumes the table already exists; in this demo I've included code that generates a table to whatever size you specify and then calls the function below to do the numbering and colours.
function numberDiagonally(tableId) {
var rows = document.getElementById(tableId).rows,
numRows = rows.length,
numCols = rows[0].cells.length,
sq = numRows + numCols - 1,
d, x, y,
i = 1,
dc,
c = -1,
colors = ["green","yellow","orange","red"];
diagonalLoop:
for (d = 0; d < sq; d++) {
dc = "diagonal" + d;
for (y = d, x = 0; y >= 0; y--, x++) {
if (x === numCols)
continue diagonalLoop;
if (y < numRows)
$(rows[y].cells[x]).html(i++).addClass(dc);
}
}
for (d = 0; d < sq; d++)
$(".diagonal" + d).css("background-color", colors[c=(c+1)%colors.length]);
}
Demo: http://jsfiddle.net/7NZt3/2
The general idea I came up with was to imagine a square twice as big as whichever of the x and y dimensions is bigger and then use a loop to create diagonals from the left edge of that bounding square going up and to the right - i.e., in the order you want the numbers. EDIT: Why twice as big as longer side? Because that's the first thing that came into my head when I started coding it and it worked (note that the variable i that holds the numbers that get displayed is not incremented for the imaginary cells). Now that I've had time to think, I realise that my sq variable can be set precisely to one less than the number of rows plus the columns - a number that ends up rather smaller for non-square tables. Code above and fiddle updated accordingly.
Note that the background colours could be set directly in the first loop, but instead I opted to assign classes and set the loops for each class later. Seemed like a good idea at the time because it meant individual diagonals could be easily selected in jQuery with a single class selector.
Explaining exactly how the rest works is left as an exercise for the reader...
UPDATE - this version does the colouring more like you asked for: http://jsfiddle.net/7NZt3/1/ (in my opinion not as pretty, but each to his own).
This fiddle populates an existing table with numbers and colors. It is not limited to being a 5x5 table. I didn't understand the logic of 15 being orange rather than yellow, so I simply grouped the diagonal cells into color regions.
// we're assuming the table exists
var $table = $('table'),
// cache the rows for quicker access
$rows = $table.find('tr'),
// determine number of rows
_rows = $rows.length,
// determine number of cells per row
_cols = $rows.first().children().length,
// determine total number of cells
max = _rows * _cols,
// current diagonal offset (for coloring)
d = 1,
// current row
r = 0,
// current cell
c = 0;
for (var i=1; i <= max; i++) {
// identify and fill the cell we're targeting
$rows.eq(r).children().eq(c)
.addClass('d' + d)
.text(i);
if (i < max/2) {
// in the first half we make a "line-break" by
// moving one row down and resetting to first cell
if (!r) {
r = c + 1;
c = 0;
d++;
continue;
}
} else {
// in the second half our "line-break" changes to
// moving to the last row and one cell to the right
if (c + 1 == _cols) {
c = 1 + r;
r = _rows -1;
d++;
continue;
}
}
r--;
c++;
}
Here's a jsFiddle that does what you asked for - http://jsfiddle.net/jaspermogg/MzNr8/8/
I took the liberty of making it a little bit user-customisable; it's interesting to see how long it takes the browser to render a 1000x1000 table using this method :-D
Assuming that each cell has an id of [column]x[row], here are teh codez for how to fill in the numbers of a square table of side length sidelength.
//populate the cells with numbers according to the spec
function nums(){
var xpos = 0
var ypos = 0
var cellval = 1
for(i=0;i<2*sidelength;i++){
if(i >= sidelength){
ypos = sidelength - 1
xpos = 1 + i - sidelength
$('td#' + xpos + 'x' + ypos).text(cellval)
cellval = cellval + 1
while(xpos + 1 < sidelength){
ypos = ypos-1
xpos = xpos+1
$('td#' + xpos + 'x' + ypos).text(cellval)
cellval = cellval + 1
}
} else {
ypos = i
xpos = 0
$('td#' + xpos + 'x' + ypos).text(cellval)
cellval = cellval + 1
while(!(ypos-1 < 0)){
ypos = ypos-1
xpos = xpos+1
$('td#' + xpos + 'x' + ypos).text(cellval)
cellval = cellval + 1
}
}
}
}
And here they are for how to colour the bugger.
// color the cells according to the spec
function cols(){
if(+$('td#0x0').text() === 99){
return false
} else {
$('td').each(function(index, element){
if(+$(this).text() > 22)
{
$(this).attr("bgcolor", "red")
}
if(+$(this).text() <= 22)
{
$(this).attr("bgcolor", "orange")
}
if(+$(this).text() <= 14)
{
$(this).attr("bgcolor", "yellow")
}
if(+$(this).text() <= 6)
{
$(this).attr("bgcolor", "green")
}
})
}
}
Enjoy, eh? :-)

Categories