How can i pass a new value to public method updateText to update the content inside the element?
Currently when i pass a new string to updateText method upon clicking the button i get only method name as an argument and not the passed string.
(function ($) {
var pluginName = 'testPlugin';
var defaults = {
elementText: 'Default element text',
elementColor: '#fff'
};
function Test (element, options) {
this.options = $.extend({}, defaults, options);
this.$element = $(element);
if (this[options]) {
return this[options].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof options === 'object' || !options) {
return this.init.apply(this, arguments);
}
}
// Main methods
Test.prototype = {
init: function () {
this.$element.text(this.options.elementText);
this.$element.css('color', this.options.elementColor);
},
updateText: function (newText) {
this.$element.text(newText);
}
};
// Create new instances
$.fn[pluginName] = function (options) {
return this.each(function () {
$.data(this, 'plugin_' + pluginName, new Test(this, options));
});
}
// Init
$('.d-1').testPlugin({
elementText: 'First element',
elementColor: 'red'
})
$('.d-2').testPlugin({
elementText: 'Second element',
elementColor: 'green'
})
$('.d-3').testPlugin({
elementText: 'Third element',
elementColor: 'blue'
})
$('#textChanger').on('click', function() {
$('.d-3').testPlugin('updateText', 'Third element updated text')
})
})(jQuery);
body {
font-family: Arial, Helvetica, sans-serif;
}
button {
margin-top: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="d-1"></div>
<div class="d-2"></div>
<div class="d-3"></div>
<button id="textChanger">Change text for 3rd element</button>