Switch between showing and hiding two divs using jQuery

I'm attempting to create a link that will toggle hide/show between two divs, and while this concept is not uncommon, I am facing some difficulties. My HTML structure is as follows:

<div id="wrapper">
   <div id="tog_A">
   <div id="tog_B">
</div>

<a href="#" id="link">Toggle</a>

Here is the CSS:

#tog_A {
  display:block;
}
#tog_A {
  display:block;
}

Despite finding various solutions online, it seems that there is a conflict with other JavaScript code on my website. As a JavaScript beginner, I could really use some guidance on how to integrate these scripts seamlessly.

The current JavaScript code causing conflicts is:

//Load when dom ready
jQuery(function() {
// click listener for anchors
jQuery(document).on("click",'a[href^="#"]', function(e) {

// prevent click and side effects 
    e.preventDefault();

// do the scroll
  jQuery('body, html').animate({
    scrollTop : jQuery(this.hash).offset().top
  });

//change state of button
var oldHash = jQuery(this.hash).attr("id").split("-");
var oldNr = parseInt(oldHash[1],10);
var nrOfAllSections = jQuery('[id^="section-"]').length;
var nr = oldNr == nrOfAllSections ? 1 : oldNr+1;
if(oldNr == nrOfAllSections) {
  jQuery(this).text("Top ▴");
    } else {
  jQuery(this).text("Down ▾");
    }
var newHash = "#"+oldHash[0]+"-"+ nr;
jQuery(this).attr("href", newHash);
});

jQuery(document).on('click', "#scrollToInfo", function(e) {
   e.preventDefault();
   var nrOfAllSections = jQuery('[id^="section-"]').length;
   var hrefHash = "#section-" + nrOfAllSections;
   var ypos = jQuery(hrefHash).offset().top;
   window.scrollTo(0, ypos);
   jQuery('a#scrollToBottom').text("Top ▴").attr("href", "#section-1");
 });

});

Answer №1

Implement this strategy in your code

$("#link").click(function () {
       if ($("#tog_A").is(":visible")) {
         $("#tog_A").hide();
         $("#tog_B").show();
      } else {
        $("#tog_B").hide();
        $("#tog_A").show();
      }
    });

Answer №2

<head>
 <script>
  var changeDisplay = function() {
    var elementA = document.getElementById('tog_A');
    var elementB = document.getElementById('tog_B');
    if (elementA.style.display === 'none' || elementA.style.display === '' || elementB.style.display === 'none' || elementB.style.display === '')
      elementA.style.display = 'block';
      elementB.style.display = 'block';

     else
       elementA.style.display = 'none'
       elementB.style.display= 'none'
  }
</script>
</head>
<body>
<div id="wrapper">
   <div id="tog_A" style="display:none;">
   <div id="tog_B" style="display:none;" >
</div>

  <a href="#" onclick="changeDisplay();" id="link">Toggle</a>
<body>

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

Troubleshooting: Issue with changing the name of a cloned object in Internet Explorer?

Using jQuery, I have created a dynamic clone of an input checkbox object and then modified its name with the following code snippet: row.find('[name="ACCCHB_CDARM"]').attr("name",id); The original attribute's name that I am cloning is ...

What is the best way to create an Image Carousel with a background Image Property?

Currently, I am in the process of creating an image carousel. I am required to use the background-image property instead of utilizing the <img src="Image"> tag. The carousel functions properly when I use the img tag. However, it doesn't work ...

Using Bootstrap 3's "img-responsive" class can cause images to become distorted when

When an image is rotated 90 degrees inside a modal, the img-responsive feature stops working and the image height exceeds the modal height. function rotateImage(){ var angle = ($('#testImg').data('angle') + 90) || 90; $(&apos ...

Problem with manual initialization and overriding angular services during configuration stage

Trying to make my Angular application work in live mode and prototype mode by overriding services. When the prototype mode is activated in the config, the bootstrap process is paused, mock service files are loaded, and then bootstrapping resumes. Below is ...

Getting data after submitting a form using AJAX in a Django view

One issue I'm facing is with a query form that can generate a large json object from server data. The user should be redirected to the results page with a progress bar that updates as the AJAX request for generating results progresses. However, curren ...

Accessing JSON data dynamically in a Vue v-for loop is made possible by utilizing variables

I am working with the following block of HTML: <div class="home-cards flex-cards" > <div class="card border-info" style="width: 18rem;" v-for="name in equipment.data"> <div class="card-body"> ...

Issue with launching Android application from website

I am looking to add a feature to my Android app that will open the app when a specific link (for example, www.example.org) is visited in the web browser. I have been experimenting with intent filters, but haven't had much success so far. Although I h ...

Filter an array of objects in Javascript based on a key present in another array of objects

Having two arrays, one with all products and one with products a user can access, both sharing a common ID. The goal is to filter the products array to only include those accessible to the user. All available products (products) [{ "productName": "My P ...

What is the reason behind the inability to overflow the Safari viewport?

My website, , has a footer that is clickable in Chrome but not in Safari. When users scroll to the footer in Safari, the screen jumps back to the top, making it inaccessible. Can anyone help me identify the issue? Below is the CSS code for my React projec ...

Unveiling the Masked Phone Number in jquery.maskedinput for Database Insertion

Currently, I am grappling with removing the phone number mask while working with jquery.maskedinput.min.js in an MVC web app. Here is the JavaScript code snippet I am using: @section Scripts { @Scripts.Render("~/bundles/jqueryval") <script type="text/ ...

Using TypeScript with Vue and Pinia to access the store

Is it necessary to type the Store when importing it to TypeScript in a Pinia Vue project? // Component <p>{{ storeForm.firstName }}</p> // receiving an error "Property 'storeForm' does not exist on type" // Store ...

Dividing internal CRUD/admin panel from the live application

Currently developing a moderately complex react app with redux. We have a production version that meets our requirements and now we are working on an administrative area for a local version of the application. This local version will only have basic CRUD f ...

Once all the fields are filled, I would like for my button to trigger the opening of my

I need help figuring out how to summon my modal only when all fields are filled: <form action="" id="myForm"> <fieldset> <input type="hidden" name="action" value="contact_s ...

Eliminate billing information from the Woocommerce order management page on the backend

Is there a way to modify the text "Paid on" in the backend order details page of WooCommerce? I have already implemented this for BACS and local pickup payment methods. Replace a specific word for BACS payment method in Woocommerce order edit pages I am ...

What is preventing my textbox from accepting decimal points?

After applying this code, I encountered an issue where the textbox does not accept input with a decimal point .. <asp:TextBox ID="txtDetAmount" runat="server" AutoPostBack="true" OnTextChanged="OntxtDetAmountC ...

When an option is selected on the navigation bar, side bars appear for additional navigation

How can I remove the bars on the side of the navigation bar when hovering over it? I don't want to alter the appearance or position of the navbar itself, just the parts that are affected by hovering over it. HTML: <!DOCTYPE html PUBLIC "-//W3C//D ...

When I use the select picker class, the <select> tag does not appear as intended

Is there a way to retrieve data from the second select, specifically the one with the class 'select picker'? I am encountering an issue where the data is not displaying when using the bootstrap-select component. I have confirmed that the componen ...

Error encountered when attempting to use setInterval: '$' not located

I'm attempting to programmatically click a button as soon as it's created, and then close the interval. However, I'm encountering an error that says $ is not defined when running the script below. Can someone assist me in identifying where m ...

Position the button at the bottom of the page with MUI v5 in a React application

How can I ensure the button is always positioned at the center bottom of the page, regardless of the content height? This is a snippet from my code: const useStyles = makeStyles({ button: { bottom: 0, right: 0, position: "absolute" ...

stop all HTML5 videos when a specific video is played using jQuery

I am facing an issue with 10 HTML5 videos on the same page, CHALLENGE Whenever I click on different videos, they all start playing simultaneously... <div><video class="SetVideo"></video><button class="videoP"></button>< ...