Make the child div images disappear gradually and at the same time, make an overlapping parent div image appear using Javascript

Check out my attempt at solving this challenge on jsfiddle: http://jsfiddle.net/oca3L32h/

In the scenario, there are 3 divs within a main div. Each of these divs contains an image and they overlap each other. By using radio buttons, the visibility of these divs can be controlled (showing one while hiding the others).

The goal is to create a Javascript function that will perform an AJAX query to the database when the page loads. If the response from the database is "0", a specific image should appear with 50% opacity overlaying the 3 divs. This semi-transparent image should prevent interaction with the original images underneath even when the radio buttons are clicked.

To simulate the database check in the jsfiddle, I added a "Click me" button that triggers the Javascript function. However, achieving the desired outcome has been challenging.

This is the current Javascript function:

//function to show transparent image
function ShowTransparentImage(){

//reduce opacity of firstDIV, secondDIV, and thirdDIV to 50%
document.getElementById("firstDIV").setAttribute("style","opacity:0.5; -moz-opacity:0.5; filter:alpha(opacity=50)");
document.getElementById("secondDIV").setAttribute("style","opacity:0.5; -moz-opacity:0.5; filter:alpha(opacity=50)");
document.getElementById("thirdDIV").setAttribute("style","opacity:0.5; -moz-opacity:0.5; filter:alpha(opacity=50)");

//increase opacity of masterDiv's background image to 50%
document.getElementById("masterDIV.background-image").setAttribute("style","opacity:0.5; -moz-opacity:0.5; filter:alpha(opacity=50)");

};

The challenge lies in properly manipulating the overlapping images through CSS changes within the Javascript function. Any assistance or guidance on how to tackle this issue would be greatly appreciated. Thank you!

Answer №1

UPDATE: Check out the latest version of the jsFiddle which includes fading effects.


If you are aiming to display one of three images based on user selection using radio buttons, along with a semi-transparent overlapping image controlled by JavaScript, here's an alternative method to achieve that. Instead of dynamically changing styles through JS, consider adding/removing classes and including additional CSS rules.

Here is the link to the updated jsFddle, and below is the code snippet for reference.

HTML:

<div><input class="transparentImageToggleButton" type="button" value="Toggle Transparent Image" /></div>
<div><input class="radio" type="radio" name="thing" value="0" checked />Image 0</div>
<div><input class="radio" type="radio" name="thing" value="1" />Image 1</div>
<div><input class="radio" type="radio" name="thing" value="2" />Image 2</div>

<div class="masterDiv">
    <div class="imageDiv active">
        <img src="http://lorempixel.com/g/400/400/sports" />
    </div>
    <div class="imageDiv">
        <img src="http://lorempixel.com/g/400/400/food" />
    </div>
    <div class="imageDiv">
        <img src="http://lorempixel.com/g/400/400/nature" />
    </div>
    <img class="masterImage" src="http://placehold.it/400x400?text=master+image" />
</div>

CSS:

.masterDiv {
    position: relative;
}

.imageDiv {
    display: none;
}

.imageDiv.active {
    display: block;
}

.masterImage {
    display: none;
    left: 0;
    opacity: 0.8;
    position: absolute;
    top: 0;
}

.masterImage.active {
    display: inline;
}

JS (with jQuery):

$('.transparentImageToggleButton').on('click', function() {
    $('.masterImage').toggleClass('active');
});

$('.radio').on('click', function() {
    $('.imageDiv').removeClass('active').eq($(this).val()).addClass('active');
});

Answer №2

Consider eliminating .background-image from the code

document.getElementById("masterDIV.background-image")
, and utilize .click() to invoke ShowTransparentImage function.

$('.radio input').on('click', function(){
    //Hide all image divs
    $imageDivs.css({'display':'none', opacity:1});
    $("#masterDIV").css({zIndex:0})
    //Then display the image div we want to see
    //To find that out, we'll retrieve the id of the current radio button
    var radioID = $(this).attr('id');

    //And then display that image div
    $('#' + radioID + 'DIV').css('display','block'); 
});

//function to show transparent image
$("button").click(function ShowTransparentImage(){

  //Fade out firstDIV, secondDIV, and thirdDIV by 50%
  document.getElementById("firstDIV").setAttribute("style","opacity:0.5; -moz-opacity:0.5; filter:alpha(opacity=50)");
  document.getElementById("secondDIV").setAttribute("style","opacity:0.5; -moz-opacity:0.5; filter:alpha(opacity=50)");
  document.getElementById("thirdDIV").setAttribute("style","opacity:0.5; -moz-opacity:0.5; filter:alpha(opacity=50)");

  //Fade in masterDiv's image with 50% opacity
  document.getElementById("masterDIV").setAttribute("style","opacity:0.5; -moz-opacity:0.5; filter:alpha(opacity=50);z-index:2");   
});

css

#masterDIV{
    opacity:0;
    width:400px;
    height:400px;
     position: absolute;
    background-image: url(https://jonathanhult.com/blog/wp-content/uploads/2013/06/padlock.png);
}

jsfiddle http://jsfiddle.net/oca3L32h/5/

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

The jQuery CSS menu is having trouble highlighting the active link

Can you help me figure out what's wrong with this code and how I can fix it? I'm working on a CSS menu (horizontal) where I want the background and font to change when an item is selected. I found some jQuery code from another post that should m ...

Find the div element that wraps around the currently selected radio button

Take a look at this code snippet: <div class="paymentOption"> <input type="radio" name="paymentOption" value="1" /> <span class="marginLeft10">1-time payment using a different credit card</span> </div> Is it feasible ...

Accessing AngularJS variable scope outside of a function

Utilizing a socket, I am fetching data into an angularJS controller. $rootScope.list1= ''; socket.emit('ticker', symbol); socket.on('quote', function(data) { $rootScope.list1 = angular.fromJson(data.substring(3)); //I can ...

What is the best way to make a hyperlink in HTML open in the same page or window, without relying on the <iframe> tag or JavaScript?

I have two html files and one css file. My question is how to open the link monday.html on the same page or window in my content section. For example, when someone clicks on the Monday navigation button, I want the result to show up in the content section ...

Can a hyperlink open multiple links at the same time when hovered over?

Can two links be opened in the same hyperlink when hovered over? ...

Conditional logic in Gravity Forms enhanced with Date Picker functionality

I've been faced with a challenge when it comes to gravity forms for quite some time now. I'm seeking a way to establish conditional logic based on the day selected by users. Each day of the week should have its own set of options, prioritizing th ...

JavaScript issue: "No relay configuration found" error specifically occurs in Internet Explorer versions 7 and 8

Encountering issues with loading JavaScript only on specific pages in Internet Explorer. Safari, Firefox, and Chrome render the page correctly. Debugging revealed the following errors: 1) No relay set (used as window.postMessage targetOrigin), cannot send ...

What is the method for adding the square root symbol to a button's value?

I am attempting to display the square root symbol inside a button, but I am having trouble making it work. Below is my button code: <input type="button" id="sqrt" value="sqrt" onclick="insert function here"> For the value, I want the square root sy ...

javascript - The Key Pair of a Jquery Object is Not Defined

I'm currently going through an HTML element, which is an input field using jQuery, but I keep encountering an error. Here's the code snippet: $(".submit_button").on("click touch", function(e){ e.preventDefault(); var formdat ...

Troubleshooting difficulties integrating NodeJS with R using an R script

I have been attempting to execute an R-script from a js-file but I am consistently receiving a null value as the return. Here is my folder structure: -R_test --example.js --helloWorld.R The contents of example.js are as follows: var R = require(" ...

Trigger notifications exclusively for specific hyperlink texts that are selected

I'm facing an issue where I need to notify the user when a specific link text for a hyperlink is clicked. The code provided here showcases the problem I am currently encountering. At the moment, the alert triggers whenever any link text is clicked, ra ...

Customize your file input with Bootstrap 4 using bs-custom-file-input and create a Symfony 5 collection with dynamic upload fields

The issue of not having a label for the chosen filename in a bootstrap 4 upload field has been resolved using the plugin https://github.com/Johann-S/bs-custom-file-input You can utilize "bs-custom-file-input" to showcase the selected filename in the boots ...

JavaScript breaks when using jQuery Ajax to pass an email to a PHP script

Whenever I try to pass variables to my mail.php script for email composing, the script breaks down as soon as I enter an email address. It seems like the email is automatically converted to a URL, causing my JavaScript to crash. Am I misunderstanding some ...

Guide to executing a server-side FUNCTION within a specific namespace room exclusively with the help of socket.io, express, and node.js

I've been developing an online multiplayer game using socket.io, express, and node.js. The server is supposed to detect the number of users connected to a specific room within a namespace and start the game if there are more than two players. However, ...

Viewer model aggregation - coordinating problem

In the Viewer, I am dynamically aggregating models from multiple BIM files. The process involves initializing the viewer and then using LoadDocument and LoadModel for each model chosen by the user. These models are primarily NVC files (the ones I used for ...

CSS or Coding? Learn how to display items side by side instead of on top of each other

Hey there! I manage a music website that is currently in beta. I'm running into an issue with the way the music results are appearing in the bottom player - they're all stacked on top of each other instead of being listed side by side. I've ...

Changing innerHTML in CoffeeScript

Are there other options instead of using the 'innerHTML' property in CoffeeScript? In JavaScript, you typically write something like this: document.getElementById('element').innerHTML = "blah_blah" Is there a different approach to ac ...

Querying a Database to Toggle a Boolean Value with Jquery, Ajax, and Laravel 5.4

I am facing an issue with a button I created to approve a row in a table. It seems that everything is working fine when clicking the button, but there is no change happening in the MySQL database Boolean column. Here is the code for my button: <td> ...

Opting for fetch over jQuery's ajax for making successful GET requests to an API

Recently, I found myself in a situation where I needed to convert a function that uses a remote API from returning a callback to returning a Promise. This change presented an opportunity for me to also switch from using $.ajax to fetch, since fetch already ...

Utilize custom fonts from your local directory within a Vite Vue3 project

Inside my main.scss file, I am loading local fonts from the assets/styles/fonts folder: @font-face { font-family: 'Opensans-Bold'; font-style: normal; src: local('Opensans-Bold'), url(./fonts/OpenSans-Bold.ttf) format('truety ...