jquery - How to put JavaScript DOM elements in object and access them? -


i place of javascript dom element queries in object , access them throughout script. here's current design pattern i'm using , stick format if possible:

(function ($) {  example = {      basicexample : function () {          config : {             logo : $('#logo'),             footer : $('footer'),         },          example.config.logo.hover(function () {             $(this).addclass('example');         }, function () {             $(this).removeclass('example');         }); }  example.basicexample();  })(jquery); 

accessing logo dom element doesn't seem work this: example.config.logo

you did misplace config part - not in example object literal, inside basicexample function (where acted labelled block statement no-op expression statements inside, threw no error). instead, should be

(function ($) {     example = {         config : {             logo : $('#logo'),             footer : $('footer'),         },         basicexample : function () {             example.config.logo.hover(function () {                 $(this).addclass('example');             }, function () {                 $(this).removeclass('example');             });         }     };     example.basicexample(); })(jquery); 

however, need place initialisation dom-ready handler, otherwise might not find elements. either use

example = {     init : function($) {         example.config = {             logo : $('#logo'),             footer : $('footer'),         };         example.basicexample();     },     basicexample : function() {         this.config.logo.hover(function () {             jquery(this).addclass('example');         }, function () {             jquery(this).removeclass('example');         });     } }; jquery(example.init); 

or put in handler, without module pattern , basicexample function:

jquery(function ($) {     var config = {         logo : $('#logo'),         footer : $('footer'),     };     config.logo.hover(function () {         $(this).addclass('example');     }, function () {         $(this).removeclass('example');     }); }); 

Comments

Popular posts from this blog

blackberry 10 - how to add multiple markers on the google map just by url? -

php - guestbook returning database data to flash -

java - Using an Integer ArrayList in Android -