JavaScript tri-state toggling

After devising 2 buttons, each intended to toggle a heading or paragraph, I encountered a slight issue. When using the 'Toggle Para' button, the switch occurs between 2 paragraphs upon 2 clicks. However, on the third click, I desire for both paragraphs to be visible, and so forth.

I find myself in need of some assistance.

function toggle() {

  var x = document.getElementById("heading1");
  
  if (x.style.display == "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}

function toggle1() {
  var y = document.getElementById("p1");
  var z = document.getElementById("p2");

  if (y.style.display == "block") {
    z.style.display = "block";
    y.style.display = "none";
  } else if (y.style.display == "none") {
    y.style.display = "block";
    z.style.display = "none";
  } else {
    y.style.display = "none";
    z.style.display = "block";
  }
}
<h1 id="heading1">Toggling with Paragraphs</h1>
<script type="text/javascript" src="toggle.js"></script>
<p id="p1"> 1. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
  dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p><br>

<p id="p2"> 2. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
  dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p><br>

<input type="button" id="button1" value="Toggle H1" onclick="toggle()" />
<input type="button" id="button2" value="Toggle Para" onclick="toggle1()" />

Answer №1

Keep track of the various states in which your paragraphs can appear, and cycle through them accordingly.

function toggle()
{

    var x = document.getElementById("heading1");
    //var y = document.getElementById("p1");
    //var z = document.getElementById("p2");

    if (x.style.display == "none") {
        x.style.display = "block";
    } else {
        x.style.display = "none";
    }
}

var states = [[true,true], [true,false],[false,true]];
var currentState = 0;
function toggle1()
{
    var y = document.getElementById("p1");
    var z = document.getElementById("p2");

    currentState++
    if(currentState>=states.length) currentState = 0;
    
    y.style.display = states[currentState][0] ? 'block' : 'none';
    z.style.display = states[currentState][1] ? 'block' : 'none';
   
}
<h1 id="heading1">Toggling with Paragraphs</h1>
    <script type="text/javascript" src="toggle.js"></script>
    <p id="p1"> 1. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
    tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
    quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
    consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
    cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
    proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p><br>

    <p id="p2"> 2. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
    tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
    quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
    consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
    cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
    proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p><br>

    <input type="button" id="button1" value="Toggle H1" onclick="toggle()"/>
    <input type="button" id="button2" value="Toggle Para" onclick="toggle1()"/>

Answer №2

If you are looking to create three different states, where:

  1. p1 and p2 are visible
  2. p1 is visible, p2 is not
  3. p2 is visible, p1 is not
The conditions for these states will depend on the current display state of both p1 and p2. You can achieve this by using the script below (feel free to adjust the order of making paragraphs visible or invisible as needed):

function toggle()
{

    var x = document.getElementById("heading1");
    
    if (x.style.display == "none") {
        x.style.display = "block";
    } else {
        x.style.display = "none";
    }
}

function toggle1()
{
    var y = document.getElementById("p1");
    var z = document.getElementById("p2");
   if (y.style.display != "none" && z.style.display != "none") {
        z.style.display = "block";
         y.style.display = "none";
    } 
    else if (y.style.display == "none" && z.style.display != "none") {

        y.style.display ="block";
        z.style.display = "none";
    }
    else {
        y.style.display ="block";
        z.style.display = "block";
    }
}
    <h1 id="heading1">Toggling with Paragraphs</h1>
    <script type="text/javascript" src="toggle.js"></script>
    <p id="p1"> 1. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
    tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
    quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
    consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
    cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
    proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p><br>

    <p id="p2"> 2. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
    tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
    quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
    consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
    cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
    proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p><br>

    <input type="button" id="button1" value="Toggle H1" onclick="toggle()"/>
    <input type="button" id="button2" value="Toggle Para" onclick="toggle1()"/>

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

Error when compiling TypeScript: The callback function provided in Array.map is not callable

This is a Node.js API that has been written in Typescript. app.post('/photos/upload', upload.array('photos', 12), async (req, res) => { var response = { } var list = [] try { const col = await loadCollection(COLLECTION_NAM ...

Execute MySQL query when the content of an HTML text field changes

My goal is to check if the value entered in an input text box matches any rows in a database. I want the DB to be searched when text is typed into the input field. <input type='text' name='barcode'> I would like it to search the ...

Craft a specialized script for manipulating the DOM

I'm currently working on a project using Angular 2. I have implemented a menu that should be able to close when a button is clicked. Instead of using a component for the menu, I want to keep it lightweight by placing it outside of Angular. However, I ...

Making a request using AJAX to retrieve data from an API

Looking to create an API GET request using ajax? Want a jquery function that takes an api key from the first input field and displays a concatenated result on the second input field (#2)? The goal is to make the get request to the value shown in the 2nd ...

What steps should I take to resolve the issue with running npm start?

I am encountering an issue while using React and trying to run my application. When I execute "npm run start," I receive the following error message: npm ERR! Missing script: "start" npm ERR! npm ERR! Did you mean one of these? npm ERR! npm star # Mark ...

Efficiently rendering a million elements on an HTML canvas (and replicating the render from the server)

I'm currently working on developing an HTML application using a canvas as the base. The canvas will consist of a large grid, around 1500 x 700 in size, totaling to over 1 million cells. The main concern is how to efficiently render this grid without ...

Despite adding a content security policy within the meta tag of my HTML, the policy does not seem to be properly enforced

I have implemented the Content Security Policy within the HTML meta tag <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initia ...

What is the best way to deselect all "md-checkboxes" (not actual checkboxes) on an HTML page using a Greasemonkey script?

After spending a frustrating amount of time trying to disable the annoying "md-checkboxes" on a certain food store website, despite unchecking them multiple times and reporting the issue without any luck, I have come to seek assistance from knowledgeable e ...

Having issues with InstaFeed (search) feature and jQuery Mobile

As a new developer, I am working on my first JQM site. However, I am facing an issue with my search input form where the instafeed photos do not show up until after a manual page refresh following submission. Despite numerous attempts, I cannot seem to res ...

Tips for configuring the navigation links on the current page using Bootstrap

In my Angular application, I have set up navigation links for home, about, notifications, and logout. However, when I click on the home link, it redirects me to the login page instead of remaining on the current page. I need the functionality to stay on ...

Stop form from submitting on bootstrap input, still check for valid input

Encountering a dilemma here: Employing bootstrap form for user input and utilizing jQuery's preventDefault() to halt the form submission process (relying on AJAX instead). Yet, this approach hinders the input validation functionality provided by boots ...

Tips for connecting an input tag within a popover to a Vue Model

I've got an input nested inside a popover content as shown below: JSFiddle Link HTML code snippet: <div id="vue-app"> <div class="btn btn-primary" data-toggle="popover" data-placement="bottom" title="Hello World!" data-html="true" data ...

Video is not visible in safari browser initially, but becomes visible only after scrolling for a little while

Having issues with a video not displaying correctly in Safari? The problem is that the video only becomes visible after scrolling the browser window. Want to see an example of this issue in action? Click here and select the red bag. Check out the code sni ...

How to Retrieve JSON Data in JavaScript

My AJAX request looks like this: $.ajax({ url: baseurl, dataType: 'json', data: { "id": id }, type: "POST", success: function(data) { console.log(data) } }); When I check the console, the data variabl ...

"Animating dynamic elements based on conditions in React: A step-by-step

I am currently working on a React application where I am using React Spring for animations. However, I am facing some difficulties in animating certain elements. The primary animation I am experimenting with is a simple opacity transition. i ...

How can I insert a button into a Flatlist using React Native?

Is there a way to add a single scrollable button inside a FlatList without duplicating it? I've been experiencing issues where adding a button inside the FlatList results in multiple buttons being displayed. On the other hand, placing the button outs ...

Error in Django & Angular 2: {_dataService is not defined}

I recently tried incorporating Angular 2 into my Django application as a frontend. However, I encountered an issue while attempting to create a GET request. Angular 2 kept throwing me an error that I couldn't paste here due to formatting constraints. ...

Issue of delayed loading of CSS in Vue.js application

My vue PWA is experiencing slow loading of CSS when using Vue Bootstrap and Buefy. I attempted to use V cloak, but it only hides components milliseconds after the raw HTML is briefly displayed without any CSS applied. I am looking for a method to display ...

Optimizing CSS across various pages and screens sizes with critical importance

My CSS file is in need of optimization for quicker loading times. It contains numerous components utilized across various pages (such as the start page, category pages, and detail pages) on different screen sizes (mobile, tablet, desktop). Manual optimizat ...

Is the Vue-portal enabled conditionally?

I am looking to include some additional information in the navbar (parent component) using Vue Portal. So, within a component, I can use the following code: <portal to="navbar"> <b-button>Some option</b-button> </portal&g ...