Create jQuery Plugin
Create plugin - EasyProgramming.net
by Nazmus Nasir
HTML
<!-- Easy jQuery - Create Your Own jQuery Plugin #20 -->
<p>
Welcome to the 20th Easy jQuery Tutorial, part of <a href="http://www.easyprogramming.net">EasyProgramming.net</a>. Did you know that you can extend jQuery with your own plugins? Well, let's create our own jQuery plugin today!
</p>
<p>
Custom Plugin example:</p>
<pre>
$.fn.methodName = function(options) {
let settings = $.extend({
property1: value1,
property2: value2
}, options);
return this.css(settings);
}
</pre>
<p>
You can specify default properties as shown in the <code>settings</code> variable above. Then you can write a bit of JSON to assign values to properties, and then tie them back to <code>this</code>, which is the current context, and send it back. The <code>.css</code> method is just one example, you can do a lot more than this.
</p>
<h2>
Let's practice:
</h2>
<div id="result">
</div>
<br><br><br><br><br><br><br>
CSS
#heroesTable {
border: 1px solid #dddddd;
width: 100%;
margin-bottom: 20px;
}
JavaScript
let arr = ['hello', 'from', 'easy', 'programming', '.net'];
$.fn.listThis = function(listType) {
let l = $('<' + listType + '>');
this.each(function(i, item) {
$(l).append($('<li>').append(item));
});
return l;
}
$.fn.colorMyList = function(options) {
let settings = $.extend({
color: '#000',
fontSize: '16px',
textdecoration: 'underline'
}, options);
return this.css({
'color': settings.color,
'font-size': settings.fontSize,
'text-decoration': settings.textdecoration
});
}
$('#result').append($(arr).listThis('ul').colorMyList(
{
color: '#0000ff',
fontSize: '30px',
textDecoration: 'none'
}
));