1

Within my software, I have a spread viewer which aligns pages next to each other. The number of pages can vary. Users can place notes on these pages. I want to be able to tell which page the note is being added to by comparing the x coordinate to the sum of the page widths.

For this example, let's say I have a 4 page spread. I build a js array widthArr[] which has these values: [297, 300, 305, 410]

So of course to following is true

widthArr[0] = 297 //page 1 width
widthArr[1] = 300 //page 2 width
widthArr[2] = 305 //page 3 width
widthArr[3] = 410 //page 4 width

So if the x coordinate is 400, then I will know that the note is being placed on Page 2.

Is there a way that I can dynamically loop through these pages and somehow check if x is greater than the width of all previous page widths?

I would need to check the following in this particular scenario:

Is x > (widthArr[0] + widthArr[1] + widthArr[2])? Then the user is adding a note to page 4.

Is x > (widthArr[0] + widthArr[1])? Then the user is adding a note to page 3.

Is x > widthArr[0]? Then the user is adding a note to page 2. If not, then the user is adding a note to page 1.

I was starting out with the following for loop.

var spreadPagesLength = 4;
var x = 400;
var i;
for (i = 0; i < spreadPagesLength; ++i) {

}

Any help is appreciated. Thanks so much.

1
  • This sounds like an X-Y problem. How do these pages get created or widths set? Surely can add identifiers to them at that point? Commented Aug 25, 2015 at 15:45

1 Answer 1

2

Keep a running total of widths you've seen so far, and break when the width exceeds x:

var widthArr = [297, 300, 305, 410];
var page = widthArr.length + 1;   // after the last page, as a default
var x = 400;
var totalWidth = 0;

for ( var i = 0; i < widthArr.length; ++i )
{
  totalWidth += widthArr[i];

  if (x < totalWidth)
  {
    page = i + 1;
    break;
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.