Conceal DIV containers during the loading of the page, and reveal them only upon the selection of Radio Buttons

In my user interface, I have implemented three radio buttons labeled as "Easy," "Medium," and "Hard." Each button is assigned to a distinct Javascript function that manipulates the visibility of corresponding div elements. The main purpose behind this setup is to allow users to select an option and view the related content within the designated div.

Despite my efforts over the past week and thorough exploration of various suggestions on platforms like StackOverflow, I seem to be missing a crucial detail for the functionality to work seamlessly.

The HTML code for the radio buttons is structured as follows:

<td width="100"><div align="center" class="radio">
<input type="radio" name='level' value='easy' id="easy" onclick="showEasy()"/></div>
</td>

<td width="100"><div align="center" class="radio">
<input type="radio" name='level' value='medium' id="medium" onclick="showMedium()"/></div>
</td>

<td width="100"><div align="center" class="radio">
<input type="radio" name='level' value='hard' id="hard" onclick="showHard()"/></div>
</td>

Below are the respective div elements that I intend to show/hide dynamically:

<td colspan="8" rowspan="12" align="center">
<div align="center" id="easyDIV"><img src="/images/pic1.jpg" alt="Image not loaded correctly." class="distort1" id="sample"/></div>

<div align="center" id="mediumDIV"><img src="/images/pic2.jpg" alt="Image not loaded correctly." class="distort2" id="sample1"/></div>

<div align="center" id="hardDIV"><img src="/images/pic3.jpg" alt="Image not loaded correctly." class="distort3" id="sample2"/></div>
</td>

Furthermore, I have included Javascript functions at the top of my page to dictate the visibility of each div element based on the selected radio button:

<script>
function showEasy()
{
$("#easyDIV").removeClass("displaynone");

// Ensure mediumDIV is hidden
$("#mediumDIV").addClass("displaynone");
// Ensure hardDIV is hidden
$("#hardDIV").addClass("displaynone");
}

function showMedium()
{
$("#mediumDIV").removeClass("displaynone");

// Ensure easyDIV is hidden
$("#easyDIV").addClass("displaynone");
// Ensure hardDIV is hidden
$("#hardDIV").addClass("displaynone");
}

function showHard()
{
$("#hardDIV").removeClass("displaynone");

// Ensure easyDIV is hidden
$("#easyDIV").addClass("displaynone");
// Ensure mediumDIV is hidden
$("#mediumDIV").addClass("displaynone");
}
</script>

Although my initial intention was to display only the Medium div upon page load by triggering showMedium();, there seems to be a brief moment where all divs are visible before getting hidden. This creates a suboptimal user experience that I am keen on resolving.

I experimented with different techniques such as using the <div hidden> attribute or employing display:none in the style attribute of the divs, along with dynamic changes via Javascript. However, these approaches resulted in unexpected behavior where clicking on Easy or Hard radio buttons left empty spaces instead of displaying the intended div.

If anyone has insights or suggestions on achieving the desired functionality without the temporary display of all divs, I would greatly appreciate your guidance and assistance in optimizing this feature for a smoother user interaction. Thank you in advance for your help!

Answer №1

UPDATE

I have taken the liberty of creating a version that includes the plugin:

You can view it here: http://jsfiddle.net/9L0fvt9n/

Here are a few key points to note:

1) The plugin has been integrated into the fiddle, with your code located at the bottom of that section.

2) It is worth mentioning that the plugin you are utilizing is quite old. If you intend to continue using it, ensure that jQuery Migrate is also implemented on the page. You can find more information about jQuery Migrate here: https://github.com/jquery/jquery-migrate/#readme (simply import it alongside standard jQuery).

3) The issue stemmed from the internal code of the plugin. To rectify this, I replaced the method of hiding images from display:none to visibility:hidden. This adjustment is significant as display:none treats the element as though it never existed, while visibility:hidden hides the element but retains its space on the page.

4) Given that visibility:hidden results in blank spaces where the image would be located, I introduced a wrapper <div> (with class .container) and utilized CSS to stack all three images on top of each other. As only one image is displayed at a time, all images maintain their rightful positions (you can experiment with my demo by removing the new CSS styles to observe the impact).

Please let me know if this proves helpful!


I have prepared a JSFiddle demonstration of a solution for you. However, it's important to highlight that many of the techniques you're employing are now considered outdated and not recommended (for instance - Avoid using tables to present non-tabular data).

In my example, I have addressed some of these concerns:

You can access the demonstration here: http://jsfiddle.net/wxda5yoq/

Upon initial page load, the CSS settings have been configured to exclusively display the designated div element.

Subsequently, additional div elements are dynamically shown or hidden based on the radio button selection. The primary event handler is elaborated below:

$('.radio input').on('click', function(){
  //Hide all image divs
  $imageDivs.css('display','none');

  //Then display the image div we want to see
  //To determine this, we extract the id of the current radio button
  var radioID = $(this).attr('id');

  //Finally, we reveal the corresponding image div
  $('#' + radioID + 'DIV').css('display','block');
});

Feel free to reach out if you require further clarification :)

Answer №2

To hide certain classes from the start, add the displaynone class to them, as your JavaScript will reset the class for all relevant divs when executed.

For instance:

<td colspan="8" rowspan="12" align="center">
<div align="center" id="easyDIV" class="displaynone"><img src="" alt="If you can see this, then the image didn't load properly." id="sample"/></div>

<div align="center" id="mediumDIV"><img src="" alt="If you can see this, then the image didn't load properly." id="sample1"/></div>

<div align="center" id="hardDIV" class="displaynone"><img src="" alt="If you can see this, then the image didn't load properly." id="sample2"/></div>
</td>

You may also consider removing the code that triggers displayMedium() on page load.

Answer №3

One approach to consider is implementing a logic that checks if the radio button has been clicked (if true), then proceed to toggle other classes accordingly.

To retrieve the input values, you can refer to:

var easy = $('easy:checked').val(),
medium = $('medium:checked').va(),
hard$('hard').val();

if(this.radiobutton == true){
medium.toggleClass(); }
else{
toggle some more classes
}

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 distinguish elements in the same HTML using Angular Material?

Currently, I am working on a project using Angular material, where I have a component.html file that defines a form and a table with data. In the first image of my project, you can see the tab title, a form to add new records, and the table displaying exi ...

Issue encountered when attempting to insert data via node into MySQL database

As a new Node developer, I am in the process of building some initial applications. Currently, I am working on inserting records into a MySQL database using Node. Below is an example of my post method: router.post('/add',function(req,res){ c ...

Steps to update the value of an object stored within an array

I have a collection of items stored in an array. Each item is represented by an object with properties. I want to update the value of a specific property within each object: var array=[{a:1, b:false}, {a:2, b:true}, {a:3, b:false}] My goal is to set the p ...

Express application encountering an issue when trying to render a live chart with flot in the Jade client

Encountering an issue while trying to visualize real-time data using a flot chart. The client code displays the following error: Uncaught Invalid dimensions for plot, width = 1584, height = 0 I am perplexed by the fact that the height is showing as 0. ...

What is the approach for utilizing Vue List Rendering with v-if to verify the presence of items within an array?

My current implementation utilizes v-if to conditionally display a list of cafes. However, I am interested in filtering the list based on whether a specific drink item is found in an array. For instance, I have a collection of cafes and I only want to dis ...

Attempting to incorporate icons into a Material UI table design

Hello, I've incorporated a Material UI table into one of my projects with a design concept similar to this - https://i.stack.imgur.com/i6Fsj.png I'm aiming to include icons within the tables. Here's the code I've worked on so far - ...

Guide to implementing an $http post service with defer and promise in AngularJS

var myAppModule = angular.module('myApp', []); myAppModule.controller('mainController', function($scope, userService) { $scope.addUser = function() { var email = $scope.user.email; var password = $scope.user.password ...

Troubleshooting: Unable to execute a jQuery search in the database after applying accent-neutralization in datatables

Greetings, I am working with a table using the DataTables jQuery plugin. In my index.php file in the footer (pages loaded using switch), I have added a script to neutralize accents for search purposes so that I can search without diacritics. However, this ...

Is there a way to automatically load an entire Facebook profile in one go using a program?

Does anyone know a way to automatically download all photos from a Facebook profile, not just thumbnails? I'm thinking of using wget to fetch the page source code and then extract links to images from child a elements of all div with class="rq0e ...

Can a form be submitted using an Ajax request triggered by a div element instead of an input type submit?

I used to submit the form by triggering $(".btn-update.").click() before, but now that I'm using $(".btn-update").ajaxForm(), the form is not getting submitted. Here is the HTML code: <form id="company-profile-edit-form" name="company-profile-edi ...

Use jQuery to redirect the user if the URL does not match

Is there a way to automatically redirect users to a specific page if they are not currently on that page? For example, something like the following pseudo code: if not (url = example.com/index.php) redirect to example.com/index.php /if When a user vi ...

Use ajax, javascript, and php to insert information into a database

Issue at Hand: I am trying to extract the subject name from the admin and store it in the database. Following that, I aim to display the query result on the same webpage without refreshing it using Ajax. However, the current code is yielding incorrect outp ...

the components progress down the line

For my right column implementation, I decided to use CSS position:relative and put different elements inside in position:absolute as shown below: <!-- Right Column --> <div class="col-xs-3 pl18" style="position:relative;"> <!-- Withou ...

Updating a URL for all users using React/Next.js and Firebase: a guide to refreshing the page

I am currently developing a Next.js application with a Firebase backend and have encountered an issue. In my setup, users can create sessions that others can join, but only the creator of the session can "start" it, triggering a state change. I need all us ...

Tips for centering Font Awesome icons in your design:

I'm struggling to align the font awesome icons with a lower text section in the center. Here is the HTML code snippet: .education-title { font-family: Alef, Arial, Helvetica, sans-serif; text-align: center; font-size: 1.5em; } .edu-co ...

Limit the display of an element to a single occurrence by utilizing jQuery cookies

I have a unique piece of HTML and JS code that showcases an eye-catching modal box. This remarkable feature is present on every page of my website. However, to enhance the user experience, I would like to ensure that this div element is displayed only once ...

Searching for a file in Mongoose using an array field of IDs

I am working on a system with two models, Trade and Work, that serve as categories and subcategories of labor. I am trying to implement a feature where new additions automatically select a Trade based on the given Work. However, I am facing challenges in f ...

Updating input values dynamically using AJAX in Laravel 6

Having an issue with filling Input after selection in a Dropdown. The database contains contact details. On the form, there is a Dropdown displaying names of people that should populate the fields with data on click. Using Ajax with Jquery for this purpose ...

When the page loads, a JavaScript function is triggered

My switchDiv function in Javascript is being unexpectedly called when the page loads. It goes through each case in the switch statement, except for the default case. Does anyone know how to solve this issue? $(document).ready(function() { $("#be-button" ...

Trouble persisting values with Heroku due to variable issues

Here is a concise example: let value = null; const getValues = () => { fetch('/third-party-api') .then(res => res.json()) .then(data => { value = data; }) } getValues(); app.get("/values", async (req, res) ...