Hello all,
In order to get me started writing my own plugins I decided to follow ch.11 of the 'Learning Jquery 1.3' from Karl Swedberg and Jonathan Chaffer. However I got stuck very early with the following piece of code (p.346):
html:
<style>
.this{color:red}
.that{color:blue;}
.target{font-weight:bold}
</style>
<ul>
<li class="this">Lorem ipsum dolor sit amet</li>
<li>Consectetur adipisicing elit</li>
<li>Sed do eiusmod tempor incididunt ut labore</li>
<li>Magna aliqua</li>
<li class="that">Ut enim ad minim veniam</li>
<li>Quis nostrud exercitation ullamco</li>
<li>Laboris nisi ut aliquip ex ea commodo</li>
<li class="that">Duis aute irure dolor</li>
</ul>
<input type="button" value="Swap classes" id="swap" />
javascript:
$(document).ready(function() {
$('#swap').click(function() {
$('li').swapClass('this', 'that');
return false;
});
});
jQuery.fn.swapClass = function(class1, class2) {
if (this.hasClass(class1)) {
this.removeClass(class1).addClass(class2);
}
else if (this.hasClass(class2)) {
this.removeClass(class2).addClass(class1);
}
};
I just can't get my head round what is actually happening here:
for example why is the class2 applied to all 'li' if there is at least one element originally with the class1 (but then class1 is applied to all if there are no 'li' with class2).
I made a few tests but I just don't seem to be able to understand how the
this keyword works in that example and that's clearly crucial if I want to be able to write some good plugins myself.
Any help very welcomed.
Thanks a lot.