Display a div depending on the chosen option and conceal the previous div

Is there a way to toggle the visibility of one DIV by clicking on another, while hiding the previously active DIV?

I attempted to use JQuery's slideUp() and slideDown() methods with no success.

Here is the JSFiddle I am currently experimenting with: https://jsfiddle.net/wLayxqq2/

My goal is to display content associated with different colors!

I have come across similar JSFiddles that demonstrate showing and hiding content from individual divs, but none that address hiding content from the previously "active" div!

HTML Code:

<div class="option">Red</div>
<div class="option">Yellow</div>
<div class="option">Green</div>

<div id="red" class="colors"> This is content for red </div>
<div id="yellow" class="colors"> This is content for Yellow </div>
<div id="blue" class="colors"> This is content for Green </div>

CSS Code:

.option{
    display:inline-block;
    border: solid 1px;
    margin:5px;
    padding:5px;
}

Answer №1

Create a unique data-attribute for each div and assign colors to map them accordingly:

<div data-id="red" class="option">Red</div>
<div data-id="yellow" class="option">Yellow</div>
<div data-id="blue" class="option">Green</div>

<div id="red" class="colors"> This is content for red </div>
<div id="yellow" class="colors"> This is content for Yellow </div>
<div id="blue" class="colors"> This is content for Green </div>

Utilize jQuery to toggle visibility based on the selected option:

$(".colors").hide();
$(".option").click(function(){
    $(".colors").hide();
    $("#"+$(this).data("id")).show();
});

Check out the Fiddle!

Answer №2

attempt

$(".colors").hide();
$('.option').click(function(){
    $(".colors").hide();
  $("#"+$(this).text().toLowerCase()).show();

});

DEMO

Answer №3

HTML: Red Blue Green

<div id="red" class="colors"> This is content for red </div>
<div id="blue" class="colors"> This is content for Blue </div>
<div id="green" class="colors"> This is content for Green </div>

JS:

$('.option').click(function(){
    $('.colors').hide();
    $('#' + $(this).data('id')).show();
});

Answer №4

<div class="choice" data-shade="crimson">Crimson</div>
<div class="choice"  data-shade="gold">Gold</div>
<div class="choice"  data-shade="emerald">Emerald</div>

<div id="crimson" class="shades"> This is content for crimson </div>
<div id="gold" class="shades"> This is content for Gold </div>
<div id="emerald" class="shades"> This is content for Emerald </div>

$(".choice").on("click",function(){
    shade = $(this).data("shade");
    $(".shades").slideUp();
    $("#"+shade).slideDown();
})

https://jsfiddle.net/4q38yo4z/

Answer №5

There appears to be a small error:

<div class="option">Green</div>
...
<div id="blue" class="colors"> This is content for Green </div>

Relying on the name in the DIV tag to display the content could lead to failure.

Instead, consider adding unique identifying information to the divs you wish to click on. jQuery's data() method can help with this.

$(".option").on("click", function(e){
    var id = $(this).data("color");
    $(".colors").hide();  // Hide all content DIVs
    $("#"+id).show();     // Show the target DIV
})
.option{
    display:inline-block;
    border: solid 1px;
    margin:5px;
    padding:5px;
}
.colors {
    display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="option" data-color="red">Red</div>
<div class="option" data-color="yellow">Yellow</div>
<div class="option" data-color="green">Green</div>

<div id="red" class="colors"> This is content for red </div>
<div id="yellow" class="colors"> This is content for Yellow </div>
<div id="green" class="colors"> This is content for Green </div>

Check out your revised Fiddle

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

Discovering hyperlinks within a text input and converting them into HTML links using AngularJS

I am trying to convert links in a text input into HTML links using AngularJS. Below is the code I have written, but it doesn't seem to be working as expected. Html <div class="item item-body" ng-bind-html="{{deal.notification_details}} | linky" &g ...

Retrieving multiple checkbox values from the front end using AJAX and passing them to

I have some code for ajax that is causing me issues. Here it is: var userCheckbox = $("input[name=chk]:checked").val(); This is the checkbox section in my html: <input id="checkbx" type="checkbox" name="chk" value="apple"/>apple</td> <inp ...

Design and execution of webpage structure

My website features a single-page layout with fixed navigation that allows users to easily navigate up and down the page using #. However, when the page loads I want it to display the second section of content instead of the top section. Is there a way to ...

Using ng-mouseover along with ng-if and an animated class causes issues

Whenever I hover over a link, it triggers a change in a variable value which then displays a <p> tag using ng-if. The code snippet looks like this: <div class="position text-center" ng-mouseover="social=1" ng-mouseleave="social=-1"> &l ...

What is preventing me from obtaining the select and input values?

I'm currently facing an issue where I am unable to retrieve the values of customInput and customSelect and store them in the state. The challenge arises when trying to integrate these components into a react dashboard material-ui setup. Strangely, whe ...

Having trouble getting my images to load in React. Seems like a common issue that many people run into

UPDATE: After trying different paths for my image import (such as 'import Github from '../..img/github.png'), the errors have disappeared but the image still won't load on my app. Folder Structure: My-Portfolio node_modules public src ...

How can I design a tooltip window using HTML, jQuery, or other elements to create a box-like effect?

As someone who is new to front end development, I am facing a challenge with my web app. The requirement is that when a user hovers over an image, I need a 'box' to open nearby and display a pie chart. Although I have managed to get the hover fu ...

Designing a card flip animation featuring front and back faces without using absolute positioning

Looking to enhance my website with a new feature that incorporates the card-flipper schema found on David Walsh's site: https://davidwalsh.name/css-flip. The challenge arises from the fact that the content within my cards is dynamic, making the height ...

Pair of dimensions painting with d3 version 4

I am having trouble converting my code from d3 v3 to d3 v4 Below is the original code snippet: var brush = d3.svg.brush() .x(x) .y(y) .on("brushstart", brushstart) .on("brush", brushmove) .on("brushend", brushend); However ...

Executing a JavaScript function using document.write()

When I try to click on the SWF part1 links within the document.write() function in order to call the openswf function, nothing happens. Here is my code: <html> <a href="#" onclick="Popup();">show popup</a> <script> functio ...

Get access to documents through angular

I'm currently working on a file server project. The backend is built with Node.js and MongoDB GridFS is used for file storage. Files are retrieved from the server using gridfs-stream. For the front-end, Angular is being utilized. However, I have encou ...

Receiving an empty response when utilizing Ajax to fetch a token from an external website

I currently have two websites in operation. One of the sites has a token, while the other is designed to allow a user to utilize this token for certain actions. Upon visiting the first site which contains the token, mySite.local/services/session/token I ca ...

Transforming seconds into years, months, weeks, days, hours, minutes, and seconds

Can anyone help me modify Andris’ solution from this post: Convert seconds to days, hours, minutes and seconds to also include years, months, and weeks? I am currently running this code: getDateStrings() { console.log(req_creation_date); const toda ...

Problem with UL LI styling in Internet Explorer 8

One issue I'm encountering is that a specific LI item in the list seems to be displaced from the others: https://i.sstatic.net/cxazD.jpg Have any of you experienced this problem as well? Any successful solutions or workarounds? ...

What could be causing the CSS to malfunction when the dropdownlist is updated without refreshing the page?

Currently, I have implemented DropKick CSS/JQuery to customize the appearance of my asp:DropDownList: <asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server"> <ContentTemplate> <asp:DropDownList AutoPostBack=" ...

React Hooks: In useEffect(), unable to modify parent component's state

Within my component, I have a form for users to input a title, description, and images. This component is nested within its parent component, and I want the form data to be saved if the user switches sections and returns later without losing their progress ...

Modifying the input field's name attribute while utilizing multiple datasets in typeahead.js

I am currently utilizing typeahead.js with multiple datasets, following the guidance provided here. I have chosen not to employ Bloodhound in my implementation, resulting in some differences in my code structure, outlined below: $('#search .typeahead ...

Remove the space gap between the header and card in Bootstrap

I'm in the process of creating a sleek landing/login page for my web application using Bootstrap. The current layout includes a header with text and an image, followed by a login form within a card. Looking at the image provided, it's clear that ...

Focusing on particular jQuery elements that share the same class names

I am facing an issue with dynamically generated divs that share the same class names. When I hover over the parent div (myDiv), I want to trigger an event and add a class to the myDiv child button. However, when I click on the parent div, I want to unbind ...

Issue with JavaScript not executing upon clicking the submit button on a form within the Wordpress admin page

In the admin pages of my Wordpress installation, I have created an HTML form. My goal is to validate the data inputted when the submit button is pressed using a Javascript function. If the data is not correctly inserted, I want alerts to be displayed. Desp ...