When either your castle, one of your provinces or the fortification of your alliance is attacked or raided and you failed to defend it, you can take revenge. In that case it will not matter whether the target is outside your attack range or not.
You will need to go to the map and choose the targeted castle. The revenge option will appear instead of the "Conquer" option. The timer shown indicates how much time you have left to take revenge. When you're attacking out of revenge, your rage will fuel the attack and defense strengths of your units, buffing their strength for that attack.
The revenge option will disappear as soon as you either took revenge (no matter if successful or not!) or another player conquered the target in the meantime. You cannot take revenge on a castle inhabited by a different player from the one you were battling before.