jQuery for concealing and revealing div elements when they are dry

I am facing a challenge in streamlining this code. My goal is to hide one div while another one appears, but I can't seem to figure out how to achieve this using a for loop. I want each div to hide separately, not all at once.

Any advice would be greatly appreciated by this aspiring JavaScript programmer.

$( document ).ready(function() {

$(".hide").hide();

$("#pic0").click(function(){
    $("#text0").slideToggle("fast");
    $("#pic0").hide();
  });

  $("#text0").click(function(){
    $("#pic0").slideToggle("fast");
    $("#text0").hide();
   
  });

  $("#pic1").click(function(){
    $("#text1").slideToggle("fast");
    $("#pic1").hide();
 
  });

  $("#text1").click(function(){
    $("#pic1").slideToggle("fast");
    $("#text1").hide();

  });

  $("#pic2").click(function(){
    $("#text2").slideToggle("fast");
    $("#pic2").hide();


    
  });

  $("#text2").click(function(){
    $("#pic2").slideToggle("fast");
    $("#text2").hide();

  });
  
  });
.first {
  background-color: black;
  height: 300px;
  width: 300px;
  margin: 10px;
 }

.hide {
  background-color: red;
  height: 300px;
  width: 300px;
  margin: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div class="first" id="pic0"></div>
<div class="hide" id="text0"></div>

<div class="first" id="pic1"></div>
<div class="hide" id="text1"></div>

<div class="first" id="pic2"></div>
<div class="hide" id="text2"></div>

Answer №1

Do you require this information? http://jsfiddle.net/ymayo1by/

$(document).ready(function () {

    $(".hide").hide();

    $(".first").click(function () {
        $(this).next('.hide').slideToggle('fast')
        .siblings('.hide:visible').slideUp('fast');
    });

});

UPDATE: resolved toggle problem on the active item.

Answer №2

Whether you're honing your Javascript skills or tackling a development project, jQuery UI Accordion seems to offer the solution you need.

Check out this example: JSFIDDLE

  $(function() {
    $( "#accordion" ).accordion({
      collapsible: true
    });
  });

Answer №3

When updating your HTML code, consider organizing the sets as follows:

<div class="group">
    <div class="first pic" id="pic0"></div>
    <div class="hide text" id="text0"></div>
</div>

<div class="group">
    <div class="first pic" id="pic1"></div>
    <div class="hide text" id="text1"></div>
</div>

To update the corresponding javascript code:

$('.pic').on('click', function () {
    $(this).siblings('.text').slideToggle("fast");
    $(this).hide();
});

$(".text").click(function () {
    $(this).siblings('.pic').slideToggle("fast");
    $(this).hide();
});

For a demonstration, check out this link: http://jsfiddle.net/zz7mt93o/1/

Answer №4

The solution you need is right here:

Check out the jsFiddle Demo

$('div[id^="pic"]').click(function(){
    var num = this.id.slice(-1); //extracts last character: 0, 1, 2, and so on
    $('#text'+num).slideToggle('fast');
    $(this).hide();
});
$('div[id^="text"]').click(function(){
    var num = this.id.slice(-1); //extracts last character: 0, 1, 2, and so on
    $('#pic'+num).slideToggle('fast');
    $(this).hide();
});

To prevent the annoying bouncing of the divs as they appear/disappear, simply (1) enclose them in container divs with (2) a fixed height. See this small adjustment to the previous jsFiddle here.

Key Points:

  1. We utilized the "starts with" css/jQuery selector to connect the initial click event to all DIVs with IDs that start with "pic"...

  2. this.id (native javascript) offers quicker performance than using $(this) without any difference in value

  3. We use slice to remove the last character, store it in variable num, and then utilize it to target the correct text or pic div for toggling

Answer №5

To start with, it would be beneficial to enhance your markup by grouping it together for easier manipulation using JS/jQuery. I have devised a rough solution that does not require any changes to the markup. Give it a try and see if it meets your needs.

$(".hide").hide();
$("[id^='pic'], [id^='text']").click(function() {
    var id = this.id.slice(0, -1);
    var $which = id==="text" ? $(this).prev() : $(this).next();
    $(this).hide();
    $which.slideToggle("fast");
});

View the live demonstration on Fiddle

Check out the slightly refined version on jsFiddle

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

Retrieve records with at least one connection, but display all of them

After creating this entry, it now consists of 2 tags - tag1 and tag2. { "id": "d87de1d9-b048-4867-92fb-a84dca59c87e", "name": "Test Name", "tags": [ { "id": "fa0ca8fd-eff4-4e58-8bb0-a1ef726f01d4", "name": "tag1", "organizationI ...

What is the best way to include a variable or literal as a value in styled components?

When it comes to managing various use cases, I always rely on props. However, I am currently facing a challenge in changing the border color of a styled input during its focus state. Is there a way to utilize props for this specific scenario? Despite my f ...

Centered at the bottom of the screen lies a Bootstrap button

As a beginner with bootstrap, I am currently exploring new concepts and experimenting with different features. One thing I am attempting is to center a bootstrap button at the bottom of the screen. Here is my current code: .bottom-center { position: a ...

JavaScript validation is failing, yet the form is still getting submitted

I'm facing an issue with my JS validation. It seems to be working fine, checking for a valid number that isn't zero, but the form is still submitting. I've searched for a solution to this problem, but none seem to work for me. Any suggestion ...

Adjust the size of a Div/Element in real-time using a randomly calculated number

Currently, I am working on a script that is designed to change the dimensions of a div element when a button on the page is clicked. The JavaScript function connected to this button should generate a random number between 1 and 1000, setting it as both the ...

Creating dynamic links within HTML through real-time updating

In my application, I have a feature that generates a list of words and converts them into clickable links. When the user clicks on a link, I want to extract the {{word.name}} from the HTML link without navigating to a new page. I simply need to retrieve th ...

Encountering npm install failure post updating node version

When attempting to execute npm i, the following error message is now appearing: npm i npm ERR! path /home/ole/.npm/_cacache/index-v5/37/b4 npm ERR! code EACCES npm ERR! errno -13 npm ERR! syscall mkdir npm ERR! Error: EACCES: permi ...

Tips on moving down the `<li><span>` elements with the jQuery `.slidedown()` method

I'm struggling to articulate my question clearly, so please bear with me. Essentially, I have a jquery script that reveals content within a div nested in an li. When I click on the header, the content drops down and visually pushes the next header do ...

Transferring the input value to a different input field with Keyup in Angular 9

Is there a way to instantly pass data from one input field to another in Angular? I am facing some issues with this. How can I troubleshoot this problem? Component.ts export class AppComponent { number = ''; //initialized the text variable ...

Encountering an issue with compiling Angular due to a Type Inference error

interface Course { name: string; lessonCount: number; } interface Named { name: string; } let named: Named = { name: 'Placeholder Name' }; let course: Course = { name: 'Developing Apps with Angular', lessonCount: 15 }; named = ...

Unable to customize the appearance of the Facebook like button

I have been attempting to implement the suggestions provided here, but I am encountering difficulties in styling the Facebook like button. The website in question is: Currently, my main priority is preventing the comment box from appearing as a temporary ...

Having trouble determining the height of a div element?

I'm struggling with a seemingly simple problem that I just can't seem to solve. I'm trying to get the height of my div element, but for some reason it keeps returning 0. Even when I inspect the element in Chrome, it shows me a height. Here&a ...

I need help determining the starting date and ending date of the week based on a given date

I am looking to determine the starting date (Monday) and ending date of a specified date using Javascript. For instance, if my date is 2015-11-20, then the starting date would be 2015-11-16 and the ending date would be 2015-11-21. ...

Jquery Fails to Execute When Clicking on Radio Button

Whenever a user selects a radio button, I want to display an alert box. I have already written the jQuery code to achieve this. Here is my implementation: <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></ ...

Using jQuery, transform JSON into an array

After running my PHP code, I have the following result: $result = '[{"MFG_NAME":"ABC","CONCATED_MKT_SHARE":"01-MAR-14|0.59"},{"MFG_NAME":"XYZ","CONCATED_MKT_SHARE":"01-MAR-14|0.87"},{"MFG_NAME":"ABC","CONCATED_MKT_SHARE":"01-APR-14|0.25"},{"MFG_ ...

Calculating the percentage difference between two dates to accurately represent timeline chart bar data

I am in the process of creating a unique horizontal timeline chart that visually represents the time span of milestones based on their start and finish dates. Each bar on the timeline corresponds to a milestone, and each rectangle behind the bars signifies ...

What is the best way to assign a name to an unnamed function or an express middleware in JavaScript?

Recently, I implemented some middleware in my express application. Here's the snippet: const app = express(); const port = 8000; const customMiddleware = () => { return async (req, res, next) => { await new Promi ...

"Angular 6: A Guide to Customizing Text Colors Based on Status

I have a view on angular just like this: https://i.sstatic.net/JimWN.png And this is my dashboard.component.ts: export class DashboardComponent implements OnInit { tablePresetColumns; tablePresetData; ngOnInit() { this.tablePresetColumns = [{id: ...

display or conceal a div when a radio button is selected

I need a way to display a specific div containing unique text once a radio button is selected, while hiding all other div sections. <?php foreach ($items as $item){ $i=1; echo ' <div class="form-check"> <input class="fo ...

How can you declare variables in CSS using LESS?

I am facing a challenge where I need to dynamically change the branding color and other styling variables on the portal based on certain conditions at runtime. I have successfully implemented this functionality using CSS with the code snippet provided be ...