Access a jQuery Object saved in a variable

0

I need to access the jQuery Object that is saved as a editor parameter and I do not know how to do it. Can someone explain to me what I'm doing wrong?

(function ($) {

    var test = {

    config: {
        editor: $( "#wp-content-wrap" )
    },

    init: function(){
        test.add_button();
        test.enable();
        test.load_events();
    },

    enable: function(){ },
    disable: function(){ },
    load_events: function(){ },

    add_button: function(){
        test.config.editor.before(
            '<div class="builder-tools">' +
            '<a id="switch-button" ' +
            'href="javascript:void(0);">' +
            'Activar' +
            '</a>' +
            '</div>')
    }
};

    $(document).ready(function () {
        test.init();
    });
})(jQuery);
    
asked by Infobuscador 29.05.2016 в 14:56
source

1 answer

2

What happens here is that the $("#wp-content-wrap") statement is executed when the .js is loaded. This may happen BEFORE the page is finished loading, so it can not be found and has an invalid value when you invoke add_buttons .

To solve it you can move the initialization of that variable inside the init() method since this method is invoked on document ready the element should be loaded in the DOM.

Something like that, as you can see the button is inserted between the title and the envelope:

(function($) {

  var test = {

    config: {},

    init: function() {
      // mueves aqui la inicializacion. 
      test.config.editor =  $("#wp-content-wrap");
      test.add_button();
      test.enable();
      test.load_events();
    },

    enable: function() {},
    disable: function() {},
    load_events: function() {},

    add_button: function() {
      test.config.editor.before(
        '<div class="builder-tools">' +
        '<a id="switch-button" ' +
        'href="javascript:void(0);">' +
        'Activar' +
        '</a>' +
        '</div>')
    }
  };

  $(document).ready(function() {
    test.init();
  });
  
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>titulo</h1>
<div id="wp-content-wrap">
ENVOLTURA
</div>
    
answered by 29.05.2016 / 16:45
source