Thanks for editing your post!
Just to precise a bit more the previous answer, what you need to focus on is that part:
xOffset = mouseX-bx;
yOffset = mouseY-by;
It keeps track of the delta between the corner of the rectangle and the mouse position when you click on the rectangle so that when you move your mouse you can offset it back to that amount.