Write a simple jQuery plugin to highlight elements

Description: Create a plugin highlight() which sets a yellow background by default, and accepts a color option.

Hint:

  • Add it to $.fn, use $.extend() and return this.each().

HTML of the page

<p class="a">First</p>
<p class="b">Second</p>

Solution

(function ($) {
  $.fn.highlight = function (options) {
    var settings = $.extend({ color: 'yellow' }, options);

    return this.each(function () {
      $(this).css('background-color', settings.color);
    });
  };
})(jQuery);

$('.a').highlight();
$('.b').highlight({ color: 'lightblue' }).addClass('done');
HTML after the code runs

<p class="a" style="background-color: yellow;">First</p>
<p class="b done" style="background-color: lightblue;">Second</p>

How it works

  • The defaults and the user options are merged with $.extend().
  • The plugin returns the jQuery object, so .addClass('done') still works after it.

Read jQuery Plugins.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.