Grab the x and y of the mouse and subtract the top left corner.

Now divide both coordinates by a book's width / shelve height to get Book/Shelve coordinates.

Finally, multiply y by the number of books per shelve, then add x to get a unique index i for every book.

No if/else required.