According to this answer I try to create a page where if the input field get focused than the height is scaled down small enough that the page will be not scrollable. If the input field lose the focus than everything is made back to the original state.

I tried this technique without events only entering the code through the console and it worked like a charm, but after I bind these to events, everything is ruined. I realized that after I click into the input field and the binded function executes, the input field immediately lose the focus. It logs the bind to the console, but doesn’t unwrap() and also doesn’t change the scrollLocked‘s value, so in the next click it wrap() the <div> again and there will be multiple ones.

My guess for this behavior is that after the focus the DOM isn’t created yet but it immediately blurs and it is executed so fast that it try to unwrap() a DOM element that isn’t exist yet. The only pitfall in this theory is that after the second or umpteen click there are a lot of height-helpers but it still doesn’t unwrap() any of them.

Live Demo


<input type="text" id="search-text">
<div id="spacer" style="height:1500px;"></div>


var scrollLocked = false;

$(document).on('focus', '#search-text', function(){
    if (!scrollLocked){
        scrollLocked = true;
            $('<div id="height-helper"/>').css({
                height: 300,
                overflow: 'hidden'

$(document).on('blur', '#search-text', function(){
    scrollLocked = false;

Why does the input field lose the focus immediately and why the blur’s function do not unwrap() even after multiple clicks? Is there a way to achieve what I described?