0

Hello I'm trying to detect focusing the element using namespace. Here`s my working code:

(function($){
    searchBox = {
        element: $('div#block-search-form input[name=search_block_form]'),
        focus: function(){
            this.element.live('focusin',function(){
                console.log('in');
            });

            this.element.live('focusout', function(){
                console.log('out');
            });
        }
    }

    $(document).ready(function(){
        searchBox.focus();
    });
})(jQuery);

My question is how to make it without using the .live()?

EDIT

To make it work I had to make an element as a function and now everything works fine. When I haven't it hasn't have the correct context. My new code:

(function($){
    searchBox = {
        element: function(){return $('div#block-search-form input[name=search_block_form]')},
        init: function(){
            this.focus();
        },
        focus: function(){
            var that = this;

            that.element().on({
               'focusin': function(){
                    /*code*/
                },
                'focusout': function(){
                   /*code*/
                }
            }); 
        }
    }

    $(document).ready(function(){
        searchBox.init();
    });
})(jQuery);
Aviene
  • 1
  • 2

2 Answers2

0

Use

$(document).on("event", "element", function() {

instead of

this.element.live('focusin',function(){

Please see the following code sample:

(function($){
    searchBox = {
        element: $('div#block-search-form input[name=search_block_form]'),
        focus: function(){
            $(document).on("focusin", this.element, function () {
                console.log('in');
            });

            $(document).on("focusout", this.element, function () {
                console.log('out');
            });
        }
    }

    $(document).ready(function(){
        searchBox.focus();
    });
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="block-search-form">
  <input name="search_block_form" />
  
</div>
Julien Ambos
  • 2,010
  • 16
  • 29
0

jQuery.live is deprecated start with 1.7 version , and after 1.9 live method has been removed. You can use instead jQuery.on

(function($){
    searchBox = {
        element: $('div#block-search-form input[name="search_block_form"]'),
        focus: function(){
            this.element.on("focusin", function () {
                console.log('in');
            });

            this.element.on("focusout",  function () {
                console.log('out');
            });
        }
    }

    $(document).ready(function(){
        searchBox.focus();
    });
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script>
<div id="block-search-form">
  <input name="search_block_form" />
  
</div>
Vladu Ionut
  • 8,075
  • 1
  • 19
  • 30