Get up to 80 % extra points for free! More info:

Lesson 9 - Styling in jQuery

In the previous lesson, Selectors in jQuery, part three, we finished the selectors in jQuery. In today's tutorial of the most popular JavaScript library, we'll focus on styling.

Creating the page

It's probably not a surprise that we're going to create an HTML and JS files first as always.

JS

We'll insert the basic structure to the JS file:

$(function() {
    // The code here is executed not before the page is loaded
});

HTML

Let's place the following code into the HTML file:

<ul>
    <li>Apophis</li>
    <li>Anubis</li>
    <li>Ba'al</li>
    <li>Sokar</li>
    <li>Ti</li>
    <li>Ra</li>
</ul>

And we'll also add styles:

body {
    background: #e5e5e5;
    color: #3d3d3d;
    margin: 0px;
}

* {
    margin: 0px;
    padding: 0px;
    text-decoration: none;
    list-style-type: none;
    border: 0px;
}

ul {
    float: left;
    padding: 10px 20px;
    text-align: center;
}

ul li {
    background : #CACACA;
    color      : #444;
    width      : 100px;
    border     : 2px solid #A6A6A6;
    margin     : 10px 0;
    padding    : 5px 10px;
    font-family: 'Open Sans';
    font-size  : 18px;
    text-align: left;
}

This is how our page looks like:

Your page
localhost

In jQuery, we can style anything using several methods.

css()

The css() method sets or gets CSS element properties. For example, if we want to find out what the text color is, we pass just the name of this property - color. If we want to change this property, we pass a second argument, which will be the new value of the property.

Property names are the same as in CSS. We can also use the camelCase notation as well. Thus, both background-color and backgroundColor will work.

Example #1

Let's try to style the bottom and top borders of the items, using both notations:

$("ul li").css("borderTop", "2px solid red");
$("ul li").css("border-bottom", "2px solid blue");

The result:

Your page
localhost

Since the jQuery method returns a jQuery object again, we can also chain the methods and write everything as a one-liner:

$("ul li").css("borderTop", "2px solid red").css("border-bottom", "2px solid blue");

Example #2

If we wanted to set multiple styles at the same time, a JSON object can be useful. We can pass it as a method argument. Let's show the example above using a JSON object. This approach is much more practical and we don't have to write the css() method so many times.

$("ul li").css({
    "borderTop" : "2px solid red",
    "border-bottom" : "2px solid blue"
});

The result:

Your page
localhost

A JSON object can, of course, be created earlier and passed as a variable.

let myStyle = {
    "borderTop" : "2px solid red",
    "border-bottom" : "2px solid blue"
}
$("ul li").css(myStyle);

Example #3

Okay, but what can we do if we want to get the values of multiple properties? We can use arrays for this purpose. We can simply pass an array of the property names we want to get the values of as the css() method argument. For example, if we were interested in the width, color, and border properties, we could get the values of them all them by writing:

let styles = $(this).css(["width", "color", "border"]);

Examiner

Let's create a sample element examiner. It'll print these properties of an element we clicked on. We'll add div#messages at the end of the body.

<div id="messages"></div>

We'll also create an array of text messages which we'll print at the end.

let messages = ["This item has these styles:"];
let styles = $(this).css(["width", "color", "border"]);

The styles variable contains an object in the form of property: "value". Now, we'll use the $.each() method to get the property names and values, one by one. We'll pass the 'styles' variable and an anonymous function as the parameters. The anonymous function will have two parameters - property and value.

We'll push the property name and its value separated by : to our messages.

$.each(styles, function(property, value) {
    messages.push( property + " : " + value );
});

Now we have a complete array of messages, we just have to print it. We'll join the array items to a single string using the join() method. We'll use the <br> elements as separators to display individual style messages on separate lines.

$("*").on("click", function(e) {
    let messages = ["This item has these styles:"];
    let styles = $(this).css(["width", "color", "border"]);
    $.each(styles, function(property, value) {
        messages.push(property + " : " + value );
    });
    let message = messages.join("<br>");
    $("#messages").html(message);
    e.stopPropagation();
});

The live demo:

Your page
localhost

Our function will work for all the elements on the page. We used the e.stopPropagation() event method, which stops the propagation of the click event to other underlying elements. If we didn't do that, 3 clicks would be triggered:

  • 1st on <li>,
  • 2nd on <ul>
  • 3rd on <body>

And we'd always see the information about <body> only.

width() and height()

Using jQuery, we can also change the width and height of elements. These functions don't change the CSS properties but set inline styles directly to the element, meaning they'll be written to the style="" attribute. If we want to get the width or height, we don't pass any arguments. If we want to change this value, we pass a new value as the argument.

Example #4

Let's try changing the width using the previous example. We'll add the following code at the end of the anonymous function:

$(this).width($(this).width() + 10);

The live demo:

Your page
localhost

We can see that when we click on an element, its width increases by 10px.

innerWidth() and innerHeight()

These methods include padding to the width and height, apart from that they work the same as the previous ones.

Example #5

Let's make sure there's a difference between the width() and innerWidth() methods.

We'll log the individual dimensions to the console.

let messages = [];
messages.push("width: " + $("ul li").width());
messages.push("inner width: " + $("ul li").innerWidth());
let message = messages.join("<br>");
$("#messages").html(message);

The result:

Your page
localhost

Now we can really see the difference here.

outerWidth() and outerHeight()

These methods calculate the element dimensions including padding, margin, and border. The methods work the same way as the previous ones.

Example #6

Let's try to log the values returned by all three methods to the console. Our padding is set to 10px on each side, there's no margin, and the border is 2px on each side.

An example:

let messages = [];
messages.push("width: " + $("ul li").width());
messages.push("inner width: " + $("ul li").innerWidth());
messages.push("outer width: " + $("ul li").outerWidth());
let message = messages.join("<br>");
$("#messages").html(message);

The result:

Your page
localhost

We can see that the result is correct.

offset() a position()

This pair of methods is used to detect the position of an element in the document. There's a little difference between them. The offset() method returns the position relative to the beginning of the body element, whereas position() returns the position relative to the beginning of the parent element. The value is returned as an object with the top and left properties.

Example #7

Let's style "ul li" so that margin-top is e.g. 50px, so we can see the difference.

$("ul li").css("marginTop", 50);

$("ul li").on("click",function() {
    let messages = [];
    messages.push("offset left: " + $(this).offset().left + ", top: " + $(this).offset().top);
    messages.push("position left: " + $(this).position().left + ", top: " + $(this).position().top);
    let message = messages.join("<br>");
    $("#messages").html(message);
});

The live demo:

Your page
localhost

Notice that the first item is 60px apart from the beginning of the body. The offset() was calculated as 10px margin from <ul> and 50px margin from <li>. The position of the item is 10px from <ul>, this value will be returned by the position() method.


 

Did you have a problem with anything? Download the sample application below and compare it with your project, you will find the error easily.

Download

By downloading the following file, you agree to the license terms

Downloaded 2x (1.95 kB)
Application includes source codes in language JavaScript

 

Previous article
Selectors in jQuery, part three
All articles in this section
jQuery Basics
Article has been written for you by Honza Bittner
Avatar
User rating:
2 votes
Everything is possible.
Activities