jQuery is probably the most popular JavaScript library. There is a reason for it – the community loves it, because it is quite understandable and useful. Today I have decided to come up with a solution of a homework from SoftUni, in one of their JavaScript courses.
The task is simple – you have a predefined list of animals and you should select a class of them and a color. Once you are ready, then the corresponding animals are colored in the color, which you have asked for.
It is not exactly science fiction, but there are three tricky parts in the task.
- The usage of e.preventDefault() in order not to refresh the page;
- The fact that the color is taken from the OS pallete and transferred to number automatically;
- The idea to use the “.” + the class value for the change.
The js code is just 6 lines, and the magic is done in two of them. Really basic, but important stuff. Here comes the js code:
1 2 3 4 5 6 |
$(document).ready(function () { $('#my_color').change(function(e){ $('.' + $('#my_class').val()).css('background-color', $('#my_color').val()); e.preventDefault(); }); })(); |
The whole app 🙂 is present in GitHub here.
Enjoy it! 😀