Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent element to lose CSS "focus" when changing browser tabs

The JSFiddle speaks for itself

  • Open this fiddle http://jsfiddle.net/NfRN5/
  • Click the input field
  • Change tabs on your browser
  • Come back to the fiddle - the width effect will run again =/

Is there a way to prevent this and make it steady when the user navigates away and comes back?

To view the problem in this thread, you will need to click the "Expand snippet" button. The small preview doesn't demonstrate the issue in question.

input.search-field {
  width: 100px;
  transition: all 1s ease-in-out;
}

input.search-field:focus {
  width: 300px;
}
<input type="search" class="search-field">
like image 829
Lucas Bustamante Avatar asked Nov 11 '22 19:11

Lucas Bustamante


1 Answers

In chat you mentioned you were trying to emulate Apple.com's search bar.

After peaking at their JS, I came up with this fiddle: http://jsfiddle.net/NfRN5/7/

The trick is to only blur the input in the 10ms following a mousedown, or some keypresses.

var $search = $('.search-field'), searchBlurable = false

$search
// Always focus when focused
.focus(function(e){
    $search.addClass('focused')
    searchBlurable = false
})

// Only blur after mouse or key events
.blur(function(e){
    if(searchBlurable){
        $search.removeClass('focused')
    }
})

// Set Blurable for tab/esc
.keydown(function(e){
    if(e.keyCode === 27 || e.keyCode === 9) { // esc || tab
        searchBlurable = true
        $search.blur()
    }
})

// Set Blurable for 10ms after a mousdown
$('html').mousedown(function(e){
    searchBlurable = true
    window.setTimeout(function () {
        searchBlurable = false
    }, 10)    
})
like image 122
whitehat101 Avatar answered Jan 04 '23 02:01

whitehat101