Modify the background color of the entire page when the main div is clicked

I am attempting to alter the background color of my entire page when the div with id main is clicked. You can view the code here:

$(document).ready(function() {

    var color = 1;
            
    $('#main').click(function(){
        if (color == 1)   {
            $(this).css("background-color", "green");
            color = 2;
        } else if (color == 2) {
            $(this).css("background-color", "black");
            color = 1;
        }                 
    });
});
#admin_div {
    position: absolute;
    width: 80%;
    height: 80%;
    border: 2px solid white;
    border-radius: 10px;
    background-color: #D9D9D9;
    z-index: 1;
}   

h1 { 
  margin-left: 15px; 
}

#main {
height: 100%;
width: 100%;
z-index: 0;
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<div id="main">
    <div id="admin_div">
    <h1>Admin Panel</h1>
  </div>
</div>

However, I have noticed that the background color also changes when clicking on elements other than main. This might be happening because everything is contained within the main div.

Answer №1

By clicking on the red color (target div), everything functions as expected.

http://jsfiddle.net/22m0to5o/1/

var color = 1;

$('#main').click(function (event) {

    if (event.target !== this) return;

    if (color == 1) 
    {
        $('body').css("background-color", "green");
        color = 2;
    } 
    if (color == 2) 
    {
        $('body').css("background-color", "black");
        color = 1;
    }

});

Answer №2

This JavaScript snippet may appear to be somewhat trivial, but it has the potential to serve a practical purpose. Without further ado, here is the code that will enable you to dynamically alter the background color of your webpage.

<script language="JavaScript">
<!--
function changeBGC(color){
document.bgColor = color;
}
//-->
</script>

In essence, simplicity is key.

Answer №3

To modify the background color of the entire page, simply update the jQuery code by replacing $(this) with $('body').

 <script>
$(document).ready
(
    function()
    {
        var bgColor = 1;

        $('#main').click
        (
            function()
            {
                if (bgColor == 1)
                {
                    $('body').css("background-color", "blue");
                    bgColor = 2;
                } 
                else if (bgColor == 2)
                {
                    $('body').css("background-color", "red");
                    bgColor = 1;  
                }

            }
        );

    }
);
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Detecting mistakes on the server end

Fetching data in JSON format from my server to display as a table. $('#queryFrom').ajaxForm({ dataType: 'json', beforeSubmit: showRequest, / ...

The array is present both before and after the res.json() call, however it appears empty in the response

When using Express to send a json response with res.json(), I am experiencing an issue where the value of records in the object sent via res.json() is empty. My code snippet looks like this: stats.activities(params).then(res => { processActivities ...

showing information from a table column

Utilizing the jQuery DataTables plugin with a JSF <h:dataTable>. The page contains 86 records. +++++++++++++++++++++++++++++++++++++ + SN. + Name + Email + +++++++++++++++++++++++++++++++++++++ + 1 + Name 1 + Email 1 + + ...

Enhancing leaflet popup functionality by incorporating ng-click into the onEachFeature function

After creating a map and connecting it with my geojson api, I encountered an issue when trying to link each marker popup with ng-click. Simply adding HTML like this did not work as expected: layer.bindPopup("<button ng-click='()'>+feature. ...

AngularJS form submission with and without page refresh

Looking to implement an AngularJS form directive where, if on /home page, redirect to /search/term and if already on /search page, submit without refreshing the page by simply changing the location. I am able to do both separately, but struggling to writ ...

Are the buttons appearing within a pop-up display?

I am having an issue with my Javascript popup buttons. Whenever the popup appears, the buttons that come after the one clicked appear on top of the popup container, and the previous buttons appear behind it. How can I ensure that the popup container displa ...

What could be causing the image file input to appear sideways or flipped?

I am currently working on a Vuejs component that allows users to select a file from their local system. Once the user selects an image, it is previewed in a div. However, I have noticed that some images appear 'flipped' sideways automatically, es ...

What could be causing the CSS and HTML connection to fail?

I am currently working with Flask on the Atom editor to build a website. Despite specifying the correct path for the CSS file in the link, every time I load the page, it appears without any styling. I have attempted changing the paths multiple times with n ...

Performing simultaneous document queries within a single API in MongoDB

I am currently working with an API written in typescript and attempting to execute parallel queries for the same document by using Promise.allSettled. However, I have noticed that it is performing poorly and seems to be running sequentially instead of in p ...

AJax and MVC: Elevating Your File Uploading Experience

I have come across numerous examples of file uploading, but most of them involve using forms or stand alone file uploads where only the file itself is passed. Currently, I have a page that sends data to a controller via Ajax. Now, I want to incorporate a ...

Differentiating between the simple and luxurious text editing features available in the TinyMce editor

I am currently utilizing the TinyMCE editor to enhance the appearance of a textarea field where users can input comments. My goal is to offer two options for users: one for plain text and the other for a rich text editing experience. When a user selects th ...

Disabled text selection in Internet Explorer

I am in need of making one HTML element (Label) unselectable for IE. I have tried using the following methods: Unselectable=on onselectreturn=false; Unfortunately, none of these solutions are working for me. For Firefox and Chrome, I've successful ...

VueJS: components unable to access global variables

I am currently in the process of transitioning my front-end to a gulp-based application. I seem to be encountering some issues with Vue.js as I am facing two errors: [Vue warn]: Property or method "params" is not defined on the instance but referenced dur ...

Struggling to find your way around the header on my website? Let me give

I'm looking to display certain links prominently at the top of a page, similar to this example: "home > page1 > link1 > article 1." Can someone advise on how to achieve this using HTML, PHP, or jQuery? ...

Simplifying JSON output using Spring MVC with JQuery JQGrid

Is there a way to generate JSON format that is compatible with JqGrid? Currently, my Spring Controller generates the following JSON output: { "records":"5", "total":"20", "page":"1" "rows":[ {"id":"1","cell":["1","john","smith"]}, ...

An Ajax GET request will not be able to locate the JSON file

I am having issues retrieving Key and Values from a JSON file using the function provided. Despite placing the 'datafile.json' in the same directory, the code fails to execute the alert(weblink) function, while the alert('test 1') works ...

R: Extracting data from web pages: The content appears to be formatted in XML but is not recognized as such; employing HTML

Working on scraping data from multiple years which are represented by different webpages. I have successfully extracted the 2019 data as expected, but encountering an error while attempting to preprocess the 2016 data in a similar manner. url19 <- &apos ...

The web method is not activated

My initial endeavor to call a server-side function from JavaScript is not yielding results as the webmethod is not being invoked. Within the aspx file, there is a bootstrap-styled button; upon clicking it, the objective is to append a new entry to the use ...

Link Google Map Marker Click Event with Dynamic Binding

I'm currently working on binding a click event to a link that is positioned outside the Google Map Canvas. The goal is to open an "infowindow" on a map marker when this link is clicked. While I know how to achieve this for a specific point, I need a d ...

Select Box in HTML now supports the addition of a Background Image, enhancing

Currently, I am trying to customize the select option box using HTML and CSS. My main goal is to incorporate a scroll feature into the option box. However, I have encountered an issue where the image of the checked box remains visible on the screen. Below ...