(Basics) How to access things from another function?
Hey Guys,
i want to create a Plugin:
If you call it like this:
- $('#box').myPlugin({color: '#12345', size: 4});
the Plugin have to append a new div with a text:
- (function($){
- $.fn.myPlugin = function(options) {
- var defaults = {
- color: '#ff0000',
- size: 3
- };
-
- var options = $.extend(defaults, options);
- return this.each(function() {
- $(this).after('<div><p id="test">Hello World!</p></div>');
- $('#test').css('color',options.color);
- });
- }
- })(jQuery);
That works fine for me, but now i want to do something like that:
- $('#box').myPlugin('alert_it');
To do that, ive changed the Plugin Code like that:
- (function($){
- $.fn.myPlugin = function(options) {
- var defaults = {
- color: '#ff0000',
- size: 3
- };
- if(typeof(options) === 'string' && options === 'alert_it') {
- alert_it();
- return false;
- }
- var options = $.extend(defaults, options);
- return this.each(function() {
- $(this).after('<div><p id="test">Hello World!</p></div>');
- $('#test').css('color',options.color);
- });
- }
- })(jQuery);
- function alert_it() {
- alert('Your chosen color was '+options.color);
- }
But these would'nt work, i don't know how to access the options :(