Fade image and background using Jquery on click event

I've been browsing various sources and utilizing different techniques I've come across (primarily on this platform) to guide me in my progress so far. However, I fear that I may have unintentionally backed myself into a corner by choosing an incorrect path early on. Essentially, my goal is to create a light switch effect. Upon loading, the page background is black with an image featuring a black background within a frame (there is some subtle light glare/glow present, which explains the need for the image). When the switch is clicked, it changes the background color to white and replaces the image with another one having a white background. The transition works smoothly, but I would like to incorporate a fade effect to make it more gradual, akin to a light gradually turning on/off. Given the method I employed earlier, I am uncertain if achieving this will prove more challenging than anticipated.

After researching, I discovered that fading backgrounds without containers can be tricky. I am unsure of how to proceed with my current setup. I am open to any suggestions, even if it means reworking certain aspects using alternative methods. I have included some commented out code snippets to showcase previous attempts. As I am relatively new to jQuery, I acknowledge that certain elements may appear flawed.

Fiddle link provided below. The images used are placeholders but effectively demonstrate the concept: http://jsfiddle.net/timtim123/7wh4B/

HTML:

<body id="bodyback">

    <img id="out" src="rhino.png" width="527" height="376" border="0" />
    <img id="frame" src="frame.png" width="589" height="377" border="0" />
    <img id="paper" src="paper.png" width="142" height="214" border="0" usemap="#links" />


<img src="background.png" id="backimg"/>
<img src="background2.png" id="backimg" style='display:none;'/>


<div id="lightswitch">
<img src="switchdark.png" width="46" height="275" border="0" alt="Make it light" />
</div>

CSS:

#bodyback   {
        background-color:black;}

#backimg 
        {
        position:absolute;
        top: 0px;
        left: 0px;
        z-index: 2;
        }
#backimg2 
        {
        position:absolute;
        top: 0px;
        left: 0px;
        z-index: 2;
        }
#lightswitch
        {
        top: 0px;
        left: 900px;
        position:absolute;  
        z-index: 7;
        }

JS:

 $("#lightswitch").click(function() {

        var src = $('#backimg').attr('src');

        //change background image and color to white
        if(src == 'background.png') {
    //      $("#backimg").fadeTo('slow', 0.3, function()
    //      $(this).attr("src","background2.png"),
            $("#backimg").attr("src","background2.png"),
            $("#bodyback").css("background-color","white");

        //change background image and color back
        } else if(src == "background2.png") {
            $("#backimg").attr("src","background.png"); 
            $("#bodyback").css("background-color","black");
        }
    }); 

Answer №1

If you're considering a jQuery plug-in for a simple option, here's one to check out

One potential choice is the jQuery UI color animation plug-in. It's straightforward to use with clear documentation provided. Simply include the script in your head tag, and you're good to go.

Here's an example taken from the official jQuery documentation:

$(function() {
    var state = true;
    $("#button").click(function() {
        if (state) {
            $("#effect").animate({
                backgroundColor: "#aa0000",
                color: "#fff",
                width: 500
            }, 1000);
        } else {
            $("#effect").animate({
                backgroundColor: "#fff",
                color: "#000",
                width: 240
            }, 1000);
        }
        state = !state;
    });
});

By setting the backgroundColor property with this plug-in, the background color will smoothly transition to the specified color.



After reviewing different options, starting from scratch instead of relying on a plug-in can be a challenging task, but it could also be a valuable learning experience in coding. The choice depends on your specific needs and goals.

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

What is the best way to transfer Django variables to HTML?

Looking to send data from the rs232 port and showcase it in a graph using javascript? Check out this resource: Seeking guidance on importing the views.py variable into my html file. views.py import io from django.http import HttpResponse from django.shor ...

php code to send whatsapp message

Greetings! I am trying to send a WhatsApp message using PHP. Here is the code I am using: <?php require_once 'Chat-API-master/src/whatsprot.class.php'; $username = "6285648145xxx"; $nickname = "ardi"; $password = "password"; // The password ...

Maintain the initial value using ko.mapping.fromJS

How can I prevent new data fetched from an AJAX call using ko.mapping.fromJS from replacing the existing data in my observableArray? I want to append the new data without losing the previous entries. function ViewModel() { var self = this; self. ...

Conflicting jQuery slide effects and jQuery UI positioning causing issues

As you hover over an element, the position function adjusts its left attribute to the correct value. However, when you move the mouse away, it resets back to 0, causing the element to appear below the first one in the list. This issue is noticeable when y ...

I have a `null` input value. Is there a way to compute this value in relation to a date

When the input is null, what can be done to calculate the value with date? https://i.stack.imgur.com/DmFsJ.png /* // ======================================================== * * * * * How To Calculate Input Value With Date When Input Is Null * * */ // ...

Obtaining information from python script with 'child-process' functions successfully in a regular node.js script, yet encounters issues in a script that is being imported

I'm currently developing a node.js application that involves sending data to a python script for calculations, and then receiving the processed data back in a discord.js command-script command.js, which is executed from the main script index.js. To se ...

Permissible File Formats for Uploading via Ajax

I'm seeking assistance with a query regarding file uploads on a server using the AjaxFileUpload tool. I specifically want to restrict certain file types from being uploaded, and although there is server-side validation in place, I am looking to valida ...

Display a Google Map within a modal window following an Ajax request

I'm currently developing a website where I need to display a Google map inside a modal after an AJAX call. The modal is created using Bootstrap, but I'm facing an issue where the map remains blank once the modal is opened. An interesting observa ...

Troubleshooting Problem with CSS Gradient Text

I'm attempting to recreate the text effect found here: . However, I'm facing issues getting it to work despite using the same code. This is the HTML I am using: <h1><span></span>Sign Up</h1> My CSS looks like this: h1 { ...

Rendering multiple components in an array with React

I am trying to utilize the React MUI AccordionDetails component to display each element from the targetTypeData array, which always has a fixed length of 6 elements. Each element in the array consists of a Typography component. While my current approach s ...

My div is set to a specific width, but the content continues to overflow beyond its boundaries

Having trouble with my HTML code here - I can't seem to get my div to adjust its height automatically when the content exceeds the width. When I set the width to 70px, the content still overflows. Any suggestions? Here's my code. Thanks in advan ...

Using jQuery to include a sub-object in the "data" object for each AJAX request made on the webpage

Is there a way to enhance the functionality of jQuery.ajax by including a static sub-data object in every ajax request automatically? For instance, for an ajax request like this: jQuery.ajax({ url: 'request_file.php', data: { da ...

Create a repeating function that will show an image based on the specific class assigned to each individual element

Can someone help me create a function that automatically applies to all divs with a specific class on my document? I want the function to check for the presence of another class within those divs and display an image accordingly. document.getElementsByCla ...

Is there a way for a DOMWindow popup to automatically resize to fit its

Currently exploring JQuery and learning on the fly, I'm wondering if there's a method to automatically adjust the size of a DOM window based on its content? I've successfully modified the parameters to accept % width and height instead of p ...

LocalStorage is designed to hold only the most recent data input

As I work on developing an app using PhoneGap for iOS, I encounter an issue with LocalStorage. After entering and storing a username and password on my iPad, I close the app, open it again, and enter a new set of login credentials. However, when inspecting ...

Preventing Multiple Registration Accounts with the Same Email Address in Django

I created a registration page using Django, but I'm having trouble preventing the same email address from being used for multiple accounts. How can I fix this issue? Let me know if you need to see the code. models.py class Profile(models.Model): ...

Crop and upload images asynchronously using Node.js

I need to resize an image into multiple sizes and then upload them to AWS S3. The specific resizing dimensions are stored in an array. To accomplish this, I am utilizing the async waterfall method along with the series method. async.each(crop_sizes, func ...

Can Antd's Typography.Paragraph be used as a multi-row Menu title?

I am having trouble getting multiple rows to work inside the Antd Submenu. When I select only one row, it works fine. However, when I try to select multiple rows, the ellipsis is not shown at all and the text remains in one row. <SubMenu ...

What is the best way to apply padding to the top of a div when it is positioned below another div?

Observing the minimal spacing between the divs AboutDogs and AboutCats, I decided to apply padding-top: 20px to the AboutCats to create a visual distinction. However, I encountered a scenario where only AboutCats exists without any other div above it. In ...

There is no display of output or errors for the node indexes

I am facing an issue with my MongoDB code that is supposed to create an index and retrieve data, but it is not showing any output or errors. I have already installed the necessary dependencies like mongose and mongo-client, and there are no URL errors in ...