Toggle the display of two div elements

I'm looking to easily switch visibility between two different divs on my webpage. The default display should be div id2, but when a user clicks a link, I want div id1 to replace it. I've tried various methods and even tinkered with it on jsfiddle, but for some reason I can't seem to get it right.

Here's the HTML code snippet:

<a href="#id" onclick="toggle_visibility(id1, id2);">Change Payment Method</a>
<div id="id1" style="display: none"><p>test 1</p></div>
<div id="id2"><p>test 2</p></div>

And here's the JavaScript function:

function toggle_visibility(id1, id2) {  
var e = document.getElementById(id1);
var e2 = document.getElementById(id2);
if(e.style.display == 'block') {                
  e.style.display = 'block';             
  e2.style.display = 'none';
}
else {
  e.style.display = 'none';            
  e2.style.display = 'block';
}              
}

Answer №1

Take a closer look at the function signature:

function toggle_visibility(id1, id2) 
                           ^^^^^^^^ 

Now pay attention to how you are actually calling it:

onclick="toggle_visibility('id'); toggle_visibility('id2');"
                           ^^^^                     ^^^^^

Do these match up? Unfortunately, no. You should be making one call with two arguments like this:

onclick="toggle_visibility('id1', 'id2');"

Another issue to note is that your function implementation is incorrect; refer to Fibbe's solution for guidance on that matter.

Answer №2

To ensure that multiple lines are impacted by the if-statement, brackets must be used:

function toggle_visibility(id1, id2) {  
   var e = document.getElementById(id1);
   var e2 = document.getElementById(id2);
   if(e.style.display == 'block') {                
      e.style.display = 'block';             
      e2.style.display = 'none';
   }
   else {
      e.style.display = 'none';            
      e2.style.display = 'block';
   }              
} 

Answer №3

It appears that the code snippet within the JavaScript function "toggle_visibility" has been incorrectly written in terms of the statements within the "if" and "else" blocks. The accurate implementation should be as follows:

function toggle_visibility(id1, id2) {  
   var e = document.getElementById(id1);
   var e2 = document.getElementById(id2);
   if(e.style.display == 'block') {                
      e.style.display = 'block';             
      e2.style.display = 'none';
   }
   else {
      e.style.display = 'none';            
      e2.style.display = 'block';
   }              
} 

In addition, it seems that there's an issue with how the arguments are being passed. The correct method to pass the arguments is demonstrated below:

<a href="#id" onclick="toggle_visibility('id1', 'id2');">Change Payment Method</a>
<div id="id1" style="display: none"><p>test 1</p></div>
<div id="id2"><p>test 2</p></div>

Answer №4

If you're looking to control the visibility of elements on your webpage, this code may come in handy:

<div id="mydivon" style="display:block">This is on.</div>
<div id="mydivoff" style="display:none">This is off.</div>


<a href="javascript:;" onmousedown="toggleDiv('mydiv');">Toggle Div Visibility</a>

<script language="javascript">
  function toggleDiv(divid)
  {

    varon = divid + 'on';
    varoff = divid + 'off';

    if(document.getElementById(varon).style.display == 'block')
    {
    document.getElementById(varon).style.display = 'none';
    document.getElementById(varoff).style.display = 'block';
    }

    else
    {  
    document.getElementById(varoff).style.display = 'none';
    document.getElementById(varon).style.display = 'block'
    }
}
</script>

Answer №5

If you are familiar with using Jquery:

Markup

<a id="button" >Click</a>
<div class="div show">1</div>
<div class="div">2</div>

Javascript

$('#button').click(function() {
    $('.div').toggleClass('show');
});

Cascading Style Sheets (CSS)

.div {display:none;}
.show {display:block;}

Answer №6

<a href="#id" onclick="toggle_visibility('uniqueID1', 'uniqueID2');">Update Payment Information</a>
<div id="uniqueID1" style="display: none"><p>example 1</p></div>
<div id="uniqueID2"><p>example 2</p></div>

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

Tips for mocking constructors in AngularJS, specifically the Date() constructor

Trying to verify a function which receives millisSinceEpoch and gives back the time if it is today's date, otherwise it gives the date. getLocaleAbbreviatedDatetimeString: function(millisSinceEpoch) { var date = new Date(millisSinceEpoch); if (d ...

How can we stop the page from scrolling after a click?

Upon clicking the link labeled Click Me, the page automatically scrolls back to the top. This behavior is not desired. How can I correct this issue? For example, here is a link to a relevant resource: http://jsfiddle.net/Y6Y3Z/ Regarding the scroll-bar: ...

Enhancing auto-suggestion layout using JQuery

I have implemented a custom autocompletion plugin for my project. It's designed to fetch data from a specified URL and provide auto-complete suggestions based on the input. Below is the code snippet I am using for auto-completion: autocompleteurl = ...

Is it possible to use uglifyjs to merge multiple files into a single minified file?

I attempted to compress multiple javascript files into one using the uglifyjs tool, but encountered an issue. I ran $node uglifyjs.js to execute the file. Below is the content of the uglify.js file: var fs = require('fs'); var uglifyjs = re ...

Creating unique shaders with THREE.ShaderLibLearn how to craft personalized shaders using THREE

I've been diving into the world of THREEJS shader materials. So far, I've grasped the concept of how uniforms, vertexShader, and fragmentShader work together to manipulate and color vertices and fragments in the realm of glsl and webgl. I've ...

Utilize a class within a Framer Motion element to incorporate animations or set initial properties

Is there a way to apply a class using Framer Motion tag in the animate and initial props? Here's an example: <motion.div initial={{ className: 'hidden' }} animate={{ className: 'visible' }} > <div>yo</div> & ...

Renaming ngModel in an AngularJS directive's "require" attribute can be achieved by specifying a different alias

I need help with a basic AngularJS directive: <my-directive ng-model="name"></my-directive> I want to change the "ng-model" attribute to "model", but I'm unsure how to pass it to the "require" option in the directive. Here is the full co ...

What advantages can be found in using various CRUD techniques?

When working with CRUD operations, the process can be done using a form like this: <form action="/todo/<%= todos[i]._id %>?_method=DELETE" method="POST> <button>x</button> </form> The corresponding con ...

Troubleshooting a CORS problem with connecting an Angular application to a Node server that is accessing the Spotify

I am currently working on setting up an authentication flow using the Spotify API. In this setup, my Angular application is making calls to my Node server which is running on localhost:3000. export class SpotifyService { private apiRoot = 'http://lo ...

What is the best way to incorporate component-specific CSS styles in React?

This is the layout that I am attempting to replicate (originally from react-boilerplate): component |Footer |style.css |Footer.js In Footer.js, the styles are imported in a very elegant manner like this: import React from 'react'; im ...

Choosing "grandoffspring"

I have a complex inquiry! Let's examine three potential scenarios Situation 1 <div class="entry-content"> <p><a href="#"><img src="#"></a></p> </div> Situation 2 <div class="entry-content"> &l ...

Issue encountered: "An error has occurred stating that your cache folder contains files owned by root. This is likely a result of a bug present in older versions of npm. This issue arose during the execution of the

While attempting to create a new react app using the command npx create-react-app example_app, I encountered the following issue: [ Your cache folder contains root-owned files, due to a bug in previous versions of npm which has since been addressed sudo ...

Running a Gulp task to launch an express server

Within the same directory, I have both a server.js file and a gulpfile.js file. In the gulpfile.js, I am requiring the server.js file: var express = require('./server.js') My intention is to run it within the default task: gulp.task('defa ...

Replace Formik with useFormik to streamline your code

I have implemented Formik/Yup for validation on a page that triggers a GraphQL mutation. The code is functioning as expected: export default function RemoveUserPage() { const [isSubmitted, setIsSubmitted] = useState(false); const [isRemoved ,setIsRemo ...

Dynamic Express Route Handler

I have an array: var arr = ["/index.html", "/alternative_index.html", "/index"] and I am trying to make the Express server return the same output for these different routes: localhost:8080/index.html localhost:8080/alternative_index.html localhost:8080/ ...

Aligning float:left divs vertically

I have multiple divs with equal widths but varying heights that I need to fit together tightly. When I set them to float left, they don't align vertically but instead line up at the bottom of the row above. Even with the example below, I want to eli ...

Repetitive process in JavaScript

I am struggling to write certain attributes to HTML using a recursive loop and I can't seem to get the code to work properly. The JSON data consists of an array of hashes with the following attributes: serno (serial number), parent_serno (serial numb ...

Dealing with unexpected modifications in a React class component

In short, I need to adjust the data in my class component before sending it to the server to match the API request format. To achieve this, I created a method called transformData within my class component which transforms the data extracted from the state ...

React.js is throwing an error due to an unexpected character '⇒'

This is my first time working with React.js and I'm experimenting with some code. I am really enjoying it, but there's one syntax error that keeps tripping me up: {this.state.data.map((person, i) ⇒ )}. An online tutorial said this should work, ...

Imitate the actions of images with {width: 100%; height : auto} properties

I am interested in creating a unique layout that consists of a stripe composed of images with varying widths and heights. These images need to be proportional, scaled at the same height, and collectively have a width equal to the parent element. However, ...