Imagine:
Where:
.outer
You can take a look at this jsfiddle that i made that illustrates the fix for your problem, you can use this code exactly as it does what you want.