Time for action – initializing menu items
Next we will initialize the Color menu to set the background color of each item to the color it represents. We could do that in CSS but it would be cumbersome. Instead we are going to write a JavaScript method to set them all with just a little bit of code:
function initColorMenu() { $("#color-menu li").each(function(i, e) { $(e).css("background-color", $(e).data("value")); }); }
This gets all of the color menu items and iterates over them using the jQuery each()
method. For each item it sets the background color using the jQuery css()
method to the value of the data-value
custom attribute, which is a CSS color name. Just like that we have a menu of colors.
We want to do something similar for the width menu's items, except we will set the bottom border to the width in the data-value
custom attribute to give the user some idea of how big the line will be:
function initWidthMenu() { $("#width-menu li").each(function(i, e) { ...