Frustratingly, Apple bluetooth peripherals can only be paired with one Mac. If a device is already paired with a different Mac, they will not even show as pairing options on a different Mac. This makes it appear as if they are not working, but in fact, they are working as designed.
If you have your mouse and keyboard paired with your iMac, and then attached the Macbook to your iMac screen via Thunderbolt, the mouse and keyboard will NOT be available to your Macbook. This is because they are already paired with your iMac. Additionally, in order for your iMac screen to support the Macbook, the iMac is actually running, even though the screen does not show the iMac (its being used to support your Macbook).
If your iMac is running, if you take out the batteries of your mouse and keyboard, they will reconnect to the iMac when they power back up. To prevent this, you must click on the Bluetooth icon in your iMac menu bar, and disconnect the mouse and keyboard, then set both in pairing mode so that they can be identified by your Macbook. And you must do this in reverse if you want your iMac to use them again. Every.Single.Time.
Obviously, this ease of use feature works against you here. My suggestion is to get dedicated mouse and keyboard for the iMac and Macbook, perhaps even wired devices for the iMac or a Magic Mouse for the iMac and a TrackPad for the MacBook.
But for a simpler solution (at the time of this writing), look beyond Apple. Logitech solves this issue with their 'Easy-Switch' devices, that allows simple bluetooth switching. The Logitech K811 keyboard will switch from one Mac to another, and even an iPad with a click of a button. The newer K480 does as well, and is more of a desktop keyboard. Likewise, their Ultrathin Touch Mouse T630 has similar switching capability.