Switch between 2 sections with a click of a button (Implementing Javascript, HTML, and CSS)

There are two divs with different content inside, and I want to toggle between them using a button.

Here are my two divs with classes "step1Content" and "step2Content" respectively.

<div class='step1Content'> Content1 </div>
<div class='step2Content'> AnotherContent </div>

I have set the style display: block for step1Content.

.step1Content { display: block; }

I have set the style display: none for step2Content.

.step2Content { display: none; }

There is a button that should toggle between these two to show or hide.

<button onclick='step2()'>2. Taskeros and Prices</button>

Here is the JavaScript function:

function step2(){
document.getElementsByClassName('step1Content')[0].style.display = 'none';
document.getElementsByClassName('step2Content')[0].style.display = 'block';
}

However, when I click the button, nothing happens. Any idea why this might be occurring?

Answer №1

Just a reminder that

getElementsByClassName

will give you a collection of all elements in the document that have the specified class name, returned as a NodeList object.

You can also use either getElementById or querySelector

Check out this solution in action. I hope it can assist you!

function step2(){
        if(document.querySelector('.step1Content').style.display === "none"){
            document.querySelector('.step2Content').style.display = 'none';
            document.querySelector('.step1Content').style.display = 'block';
        }else{
            document.querySelector('.step1Content').style.display = 'none';
            document.querySelector('.step2Content').style.display = 'block';
        }
    }
.step1Content { display: block; }
.step2Content { display: none; }
<button onclick = 'step2()'>2. Taskeros and Prices</button>
<div class= 'step1Content'> Content1 </div>
<div class = 'step2Content'> AnotherContent </div>

Answer №2

It's crucial to remember that the function is actually getElementsByClassName, not the commonly mistaken getElementByClassName. This function returns an array-like collection of elements, so be sure to use index 0 when accessing the first element.

function step2(){
  
 var element=document.getElementsByClassName('step1Content');
element[0].style.display = (element[0].style.display ==='none') ? 'block' : 'none';
 var element1= document.getElementsByClassName('step2Content');
  element1[0].style.display = (element1[0].style.display ==='block') ? 'none' : 'block';
}
.step1Content { display: block; }
.step2Content { display: none; }
<div class = 'step1Content'> Content1 </div>
<div class = 'step2Content'> AnotherContent </div>

<button onclick = 'step2()'>2. Taskeros and Prices</button>

Answer №3

To easily toggle the visibility of a div, you can utilize the jQuery toggle function. For more information, check out http://api.jquery.com/toggle/

$("button").click(function(){
    $("#shay").toggle();
});

If you want to toggle two divs -

CSS - .show { display: block; } .hide { display: none; }

$("button").click(function(){
$('#div1').toggle();
$('#div2').toggle();
});

</script>
<body>
<div class="hide" id="div1">Hi Div1</div>
<div class="show" id="div2">Hi Div2</div>
<button>Click me</button>

Answer №4

You have the ability to utilize Array.prototype.reverse() in order to switch the display of various div elements

.step1Content {
  display: block;
}
.step2Content {
  display: none;
}
<button onclick='step2()'>2. Taskeros and Prices</button>
<div class='step1Content'>Content1</div>
<div class='step2Content'>AnotherContent</div>
<script>
  var divs = Array.from(document.querySelectorAll("div[class^=step]"));
  function step2() {
    divs[0].style.display = "none";
    divs[1].style.display = "block";
    divs.reverse();
  }
</script>

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 guide a user to a specific page based on the choice they made after submitting a form?

My form includes a list of 6 options where users can only select one. After submitting the form, I want to redirect them to a specific page based on their selection. For example, I have the following 3 options: Facebook Youtube Twitter If a user selects ...

Retrieve the current system datetime with just a click of a button

Does anyone know how to use JSF + RichFaces to automatically display the current date and time in an inputText field when a button is clicked? Any guidance on this would be greatly appreciated. Thank you! ...

Dynamic banner image

I currently have a jumbotron image in the background, but it isn't as responsive and I'm struggling to get the whole image to display properly. Here is what it looks like currently: https://i.sstatic.net/IpuDi.png Here is the full image for ref ...

Unexpectedly, Ajax call is triggering additional callbacks

I am currently facing an issue with my AJAX request in the code below. The Chrome Inspector is showing that the callback function associated with the request is being called twice, resulting in the response being logged into the console twice. Additional ...

Steps to exit browser in WebDriver Sampler in JMeter and halt execution

I have been attempting to close the browser in my Selenium Jmeter last sampler thread, but I keep encountering the following error: INFO c.g.j.p.w.s.WebDriverSampler: WebDriver has been quit. 2024-02-01 22:53:24,989 ERROR c.g.j.p.w.s.WebDriverSampler: Sess ...

How come AJAX is not successfully processing the image file?

It's puzzling that the image file in the form is being processed without any issues when Ajax is not used, but encounters a problem with the Ajax script provided below. I'm struggling to understand why this discrepancy exists... Please note: Th ...

Any particular reason for Bootstrap v5 switching class names from .ml .mr to .ms .me?

I'm curious if anyone can explain the reasoning behind Bootstrap v5 changing the names of classes that are widely used? ...

Using rxjs for exponential backoff strategy

Exploring the Angular 7 documentation, I came across a practical example showcasing the usage of rxjs Observables to implement an exponential backoff strategy for an AJAX request: import { pipe, range, timer, zip } from 'rxjs'; import { ajax } f ...

Updating a Mongoose document without overwriting existing values using FindOneAndUpdate

I have the following schema: { guildId: { type: String, required: true, unique: true }, systems:{ reactChat:{ type: Array, required: true, ...

issue with AJAX POST request not functioning correctly upon form submission

Having an issue with Ajax post while trying to submit a form event. I am working with a table that is generated by opentable.php. Here is the code for opentable.php: <?php session_start(); require("dbc.php"); $memberid = $_SESSION['memberid' ...

Three JS tutorial: Slicing a 3D shape with a vertical plane

Can Three JS achieve the functionality of slicing a mesh or object with a plane (specifically along the Y axis) that is movable? I am looking to replicate the capability shown in this image: The objective is to maintain the integrity of the mesh so that u ...

What is the best way to align a dropdown menu and a textbox on the same line

I have recently been working on a search bar that includes a Dropdown for Location and a Textbox for Search. Prior to implementing bootstrap, these elements were displayed in a single line. However, after applying bootstrap, they are now stacked vertically ...

Things, their examples and the impact of setTimeOut

I'm currently delving into object oriented programming in JavaScript. function doStock() { //my class var that = this; var nAntiFreeze = null; // timeout ID var getContent = function(oInPageContainer) { GM_log('Antifreeze, before clea ...

What is the method for implementing two-way binding on a checkbox in Angular?

Within my accordion, I have a series of options in the form of checkboxes. Users are able to select these checkboxes, but I am seeking a way to pre-select certain checkboxes based on specific conditions. The challenge arises when these conditions are deter ...

An issue has been identified with the functionality of an Ajax request within a partial view that is loaded through another Ajax request specifically in

Here is the current scenario within my ASP.NET MVC application: The parent page consists of 3 tabs, and the following javascript code has been implemented to handle the click events for each tab: Each function triggers a controller action (specified in t ...

In search of a charts library that enables interactive, linked events

I need a library that can create charts similar to the "Annotated Time Lines" used in Google Finance. The library should not rely on Flash so it can work on all browsers and mobile devices like the iPad. I specifically need the ability to display linked ev ...

Analyzing Compatibility and Ensuring Security

I recently started using Parse and have been exploring the documentation and answered questions. However, I still have a couple of inquiries on my mind. Firstly, I discovered that the Javascript SDK does not function on IE9 and IE8 without an SSL certific ...

Verification of Phone Numbers (Global)

I am attempting to create a validation check for mobile numbers, similar to the one implemented by Gmail. Check out Gmail's signup page here However, there is significant variation in phone number formats across different countries, making it challe ...

Display or conceal button according to user SESSION in PHP for each iteration loop

How can I dynamically hide or show a remove button based on whether a user has uploaded a specific image? The issue arises because the remove button is within a foreach loop. if($user_id == $_GET['id'] It currently shows every button, but wh ...

What exactly is the significance of the </< in THREE.Camera.prototype.lookAt</<()?

After experimenting with THREE.js for a while, I came across something peculiar: When using Firefox and opening the developer console to type camera.lookAt (assuming your camera is named camera), it displays function THREE.Camera.prototype.lookAt</< ...