jQuery

jQuery CSS Background Image Example

In this example, we’ll learn how to use jQuery to add CSS properties to HTML elements and specifically how to add backgrounds like colors or images using the .css() method.

The .css() method is a convenient way to get a computed style property from the first matched element, especially in light of the different ways browsers access most of those properties (the getComputedStyle() method in standards-based browsers versus the currentStyle and runtimeStyle properties in Internet Explorer) and the different terms browsers use for certain properties.

For example, Internet Explorer’s DOM implementation refers to the float property as styleFloat, while W3C standards-compliant browsers refer to it as cssFloat. For consistency, you can simply use “float“, and jQuery will translate it to the correct value for each browser.
 

1. Basic Setup

1.1 Initial Document Setup

To begin, create a new HTML document and add the following sections and links:

<!DOCTYPE html>
<html>
<head>
	<title>jQuery CSS Background Image Example</title>
</head>
<body>
<!-- STYLE SECTION  -->

<!-- HTML SECTION  -->

<!-- JAVASCRIPT SECTION  -->
<script src="jquery-1.11.3.min.js"></script>

<script type="text/javascript">
// our jQuery code goes here
</script>

</body>
</html>

1.2 Understanding the .css() method

.css( propertyName ) – Get the computed style properties for the first element in the set of matched elements.
propertyName will be a string containing the name of a CSS property. Look at the following example:

<!-- HTML SECTION  -->
<span class="result"> </span>  <!-- show the computed results here -->
<div class="content">Click to show two of my css properties.</div>
<!-- STYLE SECTION  -->
<style type="text/css">
.content {
    width: 20em;
    height: 10em;
    margin: 1em;
    background-color: #FB2A59;
    text-align: center;
    line-height: 10em;
    color: white;
    border-radius: 0.5em;
}
</style>
<!-- JAVASCRIPT SECTION  -->
<script src="jquery-1.11.3.min.js"></script>

<script type="text/javascript">
    $(function (){
        $('.content').click(function(){ /*results will be shown on click*/
            var width = $(this).css("width");   /*store the width in a variable*/
            var height = $(this).css("height"); /*store the height in a variable*/
            /*concatinate several properties and attach them to some other element*/
            $('.result').html("Width: " + width + "<br>" + "Height: " + height);
        });
    })
</script>
Using .css() - Single Property
Using .css() – Single Property

But you can use the .css() method with multiple properties inside: .css( propertyNames ) where propertyNames would represent an array of one or more CSS properties. Modifying the example above, we’d get:

<!-- JAVASCRIPT SECTION  -->
<script src="jquery-1.11.3.min.js"></script>

<script type="text/javascript">
    $(function (){
        var html = [ "The clicked div has the following styles:" ];
        $('.content').click(function(){ /*results will be shown on click*/
            /*store the css properties array in a variable*/
            var properties = $(this).css(["width", "height", "background-color", "color"]);
            /*concatinate several properties and attach them to some other element*/
              $.each( properties, function( prop, value ) {
                html.push( prop + ": " + value );
              });
              $( ".result" ).html( html.join( "
" ) ); }); }) </script>
Using .css() - Multiple Properties
Using .css() – Multiple Properties

2. Background Image using .css()

Now let’s try to add a background color and then a background image in a content box. The easiest way to do this is to refer to the element you want to give a background color and then use .css('background-color', '#eee') like so:

<!-- JAVASCRIPT SECTION  -->
<script type="text/javascript">
    $(function (){
        $('.content').css('background-color', '#51326F');
    })
</script>
jQuery Background Image
jQuery Background Image

In a similar manner, we can use the syntax .css('background-image', 'url(image.jpg)') to add a background image like so:

<!-- JAVASCRIPT SECTION  -->
<script type="text/javascript">
    $(function (){
        $('.content').css('background-image', 'url(bg.jpg)');
    })
</script>
jQuery Background Image
jQuery Background Image

You can choose to show the background image we just set with jQuery only on click. You can do that like this:

<!-- JAVASCRIPT SECTION  -->
<script type="text/javascript">
    $('.content1').click(function(){
            $(this).css('background-image','url(bg1.jpg)');
            $(this).find('p').hide();
            $(this).html("Nice Job, User!");
    });
</script>

The result would be:

Trigger Background Image on Click
Trigger Background Image on Click

3. Conclusion

To conclude, changing the background of an element with jQuery becomes really useful and necessary when you want to trigger these events on certain actions taken by the user or when you want to create functions to manipulate the background for some reason like animation ect. At all times, keep in mind the basic syntax of .css() method as it is an essential jQuery method to be used to set or change CSS properties.

4. Download

Download
You can download the full source code of this example here: jQuery CSS Background Image

Fabio Cimo

Fabio is a passionate student in web tehnologies including front-end (HTML/CSS) and web design. He likes exploring as much as possible about the world wide web and how it can be more productive for us all. Currently he studies Computer Engineering, at the same time he works as a freelancer on both web programming and graphic design.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button