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

Transforming a React object into an array and displaying it on the frontend using the .map method

After making a single API call, I have received two different sets of data. The first set is an array containing information about various items, including their names, prices, rarity, and images. The second set consists of items with details such as condi ...

The browsers Firefox and Internet Explorer are unable to perform ajax requests

Currently, I am utilizing jQuery version 3.3 in conjunction with the following Ajax script: <script type="text/javascript"> $(document).ready(function(){ $("form").submit(function(){ $.ajax({ url: 'msgs.p ...

When using $.ajaxSetup, the content type is not configured for Get requests

Snippet 1 $.ajax({url:"1.aspx/HelloWorld",type:"GET",dataType:"json",contentType:"application/json"}); Snippet 2 $.ajaxSetup({ contentType: "application/json", dataType: "json" }); $.get( ...

Retrieving and showing information from a database (Using Javascript Ajax)

I'm in need of assistance with a project for my course and would appreciate any guidance or help that can be offered. My task involves creating a simple JavaScript XML Http Request to display basic information (specifically the country_name & country_ ...

Wind - Best practices for managing the status of multiple entities within a single display prior to executing the save changes function

In my system, there are three main entities: Project, Attachment, and Messages. A project can have multiple attachments and messages associated with it. The issue arises on the project detail view, where I display the project's messages and any attac ...

What is the best way to configure custom CSS styles in a React project?

I've been trying to position my Grid component from Material-UI, but so far, I haven't had any luck. What could be the issue here? class Scene extends React.Component { render() { const mystyle = { backgroundColor: "DodgerBlue", ...

Populating the jQuery datetime picker with the datetime value stored in the database

I am currently working on a project to create a multilingual website. My main challenge is setting the date and time in the datepicker from the database because users may have selected different timezones when registering on the site. Currently, I am retri ...

Ways to display and modify chosen and not chosen categories on the product editing page

I have three tables Categories: cat_id ... other ... primary key (cat_id) Product: Product_id ... other ... primary key (Product_id) Product_cat: Product_id foreign key (post.Product_id) cat_id foreign key (Categories.cat ...

Using Bootstrap: adjusting the height of input-group and select elements

How come the select element within an input-group doesn't render similarly to the input element? I would like the height of the select element to be relative to the input-group. <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css ...

Toggle sideBar within an iFrame by implementing Media Queries

I have implemented media queries in my code to hide the .sideBar when the screen resolution is less than 768px, showing only the .main section. @media (max-width: 768px) { .sideBar { display: none !important; } } Now, I want to add a ha ...

Vue js throws a maximum call stack error when updating a Chart component

I have successfully created a line chart using the Chart.js 3.5 library. The chart is responsive, all animations are working fine too. I am currently facing an issue where I am attempting to update the data from a parent component and trigger a chart updat ...

Locate the word or phrase without a comma

I am currently working on a code that involves finding keys with string values separated by commas. var db = { "name": "Nkosana", "middle": "Baryy", "surname": "walked", "batch_number": "test,b", "temp": ",,67,6,87,86,5,67865,876,67" ...

Mastering Angular: Tackling a Directive with Two Parts

I'm working on a directive that's responsible for embedding footnotes into a body of text while providing popover functionality. The text-notes directive is designed to be placed on a parent element, loading content and its related text notes dyn ...

Modal does not close

I am experiencing an issue with closing a modal. I have checked jQuery and everything seems to be working fine. Currently, I am using version 1.12.4 and have the following script tag in the head of my code: <script src="https://ajax.googleapis.com/aja ...

Is there a way to utilize javascript std input/output in repl.it effectively?

I created a straightforward program that calculates the factorial of a specified number, and I am interested in running it on repl.it. During its execution, I would like to interact with standard input and output through the command line. Is there a way ...

Swap two frames effortlessly with just a single click!

Is there a way to effortlessly change the contents of two frames with just one click? With a single click, I'd like to modify both "framename" and "framename2" by setting their href attribute to 'qwerty' and 'qwerty2' respectively ...

Is it necessary to incorporate Babel into a project that involves developing a backend service using Node.js and a front-end component using the EJS view engine?

I find myself a little confused. Some say that if you are working on pure Node.js projects, there is no need to stress about this issue. However, for web development, it's important to be familiar with these tools. On the other hand, some recommend us ...

Increase the value by one of the number enclosed in the <h3> element

I have a variable number of <h3> tags with the same class .love_nummer <h3 class="love_nummer">1</h3> Each of these tags contains a number, and alongside each .love_nummer tag is another tag with the class .give_love <h3 class="give ...

Simply interested in extracting the JSON Class specifically, not all of the data

Looking for a way to extract only text from a specific class using $.getJSON and YQL. Currently, it retrieves all data and removes tags. Is there a method to achieve this? function filterData(data){ // remove unwanted elements // no body tags ...

Checking for a particular element's existence in an array using jQuery

Is there a way to verify the presence of the var element in the array sites? var sites = array['test','about','try']; var element = 'other'; ...