Changing background image on <body> element with jQuery when using ASP.NET master pages

If you have an ASP.NET master page defined as below which specifies a css class for the body element to generate a background image for the whole page, you might want to override the default background on specific pages.

One way to accomplish this is to use jQuery to replace the css class that is being applied to the <body> element.

The master page below declares 2 ContentPlaceHolder controls; the first (ID="head") exisist within the <head> element, the second (ID="MainContentPlaceHolder") exists within the main body of the page.


<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">
   
    <script type="text/javascript" src="jquery-1.3.2.js" ></script>
   
    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
   
</head>

<body class="defaultbodybackground">
    <form id="form1" runat="server">  
        <asp:ContentPlaceHolder ID="MainContentPlaceHolder" runat="server" />
    </form>
</body>

</html>

 

 
In one of our child pages we could add the following:


<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
 
    <script type="text/javascript">

           $(document).ready(function() {
               $("body").removeClass("defaultbodybackground");
               $("body").addClass("newbodybackground");
           })
        
        </script>
</asp:Content>


When the page is loaded, the above jQuery JavaScript runs and replaces the class "defaultbodybackground" with the page specific "newbodybackground".

A cool thing about jQuery is that you can have multiple $(document).ready() defined - for example you could also have some jQuery defined in the master page.

SHARE:

Add comment

Loading