Utilizing Jquery to Toggle Visibility of Images and Text with Buttons

I created a website with two buttons implemented using jQuery. When I click on btn1, the first image appears. Then, when I click on btn2, the first image disappears and the second image associated with btn2 appears.

The issue arises when I try to switch back to btn1 after clicking btn2. It requires a double click on each button to toggle between showing and hiding the images.

My goal is to be able to click once to display an image and seamlessly switch to the other button to show its corresponding image without any extra clicks.

Additionally, I want the third image to appear when the website is loaded initially, but hide as soon as either of the buttons (btn1 or btn2) are clicked.

The third image is not related to btn1 or btn2, it should only appear upon opening the webpage and disappear when clicking on any of the button images. Thank you for your assistance.

<html>
<head>

<script type="text/javascript">

function showhide_menu(id){
   $("#" + id).toggle();
}

</script>
</head>
<body>
<button onclick="showhide_menu('btn1');">Show/Hide.  </button>

 <button onclick="showhide_menu('btn2');">Show/Hide.  </button>

<div id="btn1" style="display:none;">
    <img src="http://mybroadband.co.za/photos/data/500/apple-logo.jpg"/>
    text text text text text text text text text....</div>

<div id="btn2" style="display:none;">
    <img src="http://www.inquisitr.com/wp-content/2012/02/breaking-dawn-saga.jpg"/>
    text text text text text text text text text....</div>

</body>
</html>

Answer №1

Add a class to the btn div elements. Then, hide them before toggling:

Check out this example on jsFiddle

Here is the HTML code:

<div id="btn1" class="btn" style="display:none;">
    <img src="http://mybroadband.co.za/photos/data/500/apple-logo.jpg"/>
    text text text text text text text text text....
</div>
<div id="btn2" class="btn" style="display:none;">
    <img src="http://www.inquisitr.com/wp-content/2012/02/breaking-dawn-saga.jpg"/>
    text text text text text text text text text....
</div>

And here is the JavaScript code:

function showhide_menu(id){
    $('.btn:not(#'+id+')').hide();
    $("#" + id).toggle();
}

Answer №2

Feel free to also utilize this

function toggle_visibility(){
    if($('#box1').is(':visible'))
    { 
        $('#box1').hide();
        $('#box2').show();
    }
    else
    {
       $('#box2').hide();
        $('#box1').show();
    }
}

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

Struggling to get the fluid image feature to work properly on Bootstrap 4

I seem to be facing an issue with creating responsive images using Bootstrap 4. Whenever I view the code below on a browser, I see three images in the navbar at the top left corner. Unfortunately, these images do not scale down in size when viewed on mobil ...

jQuery popups are not being initialized properly following an ajax response

My current setup involves using a pageless solution to showcase a listing of various locations. Among these locations, there is a jQuery popup that displays additional data in a box. The issue arises when new locations are added dynamically via ajax, as th ...

Harnessing Spread Syntax with Map and Filter Operations

Recently stumbled upon a fascinating problem that I couldn't wait to share with all of you. Here is the question at hand: [...[0,1,...[-1,0,1].map((x)=> x+1)].filter((x)=>x)),7] I managed to successfully solve the initial section up to the fi ...

Printing a React component using a button causes formatting related to className to be lost, while printing it inline preserves the formatting

I've hit a roadblock in trying to figure out the React and printing issue for the past week and a half, and it feels like I'm going in circles. Despite finding some helpful solutions on Stack Overflow, none of them seem to work completely for me ...

How can I dynamically set the width of a span element in HTML?

Hello there! As a beginner in html and angularjs, I'm experimenting with dynamically assigning span width based on an angular js response. <div class="statarea" ng-repeat="x in names"> <div class="ratingarea"> <div class=" ...

Conceal certain digits of a credit card number in a masked format for security purposes

Is there a reliable method to mask Credit Card numbers in password format within a text field? **** **** **** 1234 If you are aware of a definitive solution, please share it with us. ...

Create a unique Bootstrap 5 carousel featuring a single progress bar

Hey guys, I'm having some trouble with my Bootstrap 5 carousel. I want to add a progress bar with left and right arrows, and also the number of slides displayed, just like in this image: https://i.sstatic.net/pqOMy.jpg I did some research and found ...

Is there a way to obtain a direct video link from an embedded iframe?

I'm facing an issue trying to extract a video from an embedded iFrame. The JavaScript is obfuscated, and I suspect there might be an actual source link hidden in the JS code. Despite my best efforts, I have been unsuccessful in de-obfuscating it. When ...

Conflicting abstract views in UI-Router routes

I'm currently using UI-Router and trying to incorporate a subview into another view. Specifically, I want to display the "owner" view within the "dog" view. The following code accomplishes this: Here is how my UI-Router configuration looks like: .st ...

Utilizing React Router to dynamically render components based on JSON object data

My current challenge involves rendering React components based on the component names in a JSON file I've created. Specifically, I want to render the TestSection component within the context of my Route component. To achieve this, I am utilizing the ...

What causes the failure of this select menu in the latest combination of jQuery and JQM?

I am looking to enhance this code, but I have noticed that it does not limit the selection (by count) in the newer versions of jQuery and JQM. Check out this example which demonstrates that it works with jQuery 1.8.3 and JQM 1.2.0. Here is the jQuery cod ...

Tips for receiving alerts on external updates to a mongo collection using sails

Currently, I am in the process of creating an application utilizing mongo and sails. As part of my development, I am investigating how the real-time update feature in sails functions. Although I am currently using sails 0.9.16, I am also curious about ans ...

Detail row in DataTables without using nesting

I'm currently in the process of creating a table with nested data. My goal is to maintain a single set of column headers at the top of the table that extend throughout. In order to achieve this, I have begun modifying the Row Details example to suit m ...

Efficiently adding values to a variable with the forEach method

I'm encountering an issue with displaying data from a JSON file similar to the one below: Currently, "checked" is set to null. I aim to update it to true within the steps array using a forEach loop. JSON data snippet: { "id": 4, "process": { ...

Guide on accessing and displaying data table values in console.log using Vue.js and vuetify

Hello, I am new to Vue.js and I am trying to work with data tables. I have copied some code from the Vuetify website and I am attempting to call the desserts' names from a sample table using console.log. Below is the code snippet: <template> ...

Creating a multi-line form in Python Django involves defining a form

Brand new to Django and currently working on creating a form within a page. The form consists of multiple fields, all of which are currently displayed in a single line on the page. This is the code snippet I am using in the template: <form action=&apos ...

Issue with jQuery draggable appendTo functionality not functioning as expected

Below is the code snippet: JavaScript jQuery $('.dragBox').draggable({ axis: 'y', appendTo: 'parent', containment: [0,0,0,150], start: function() { $(this).addClass('grab ...

Resizing webpages for mobile devices results in misaligned rows

I'm currently using Bootstrap on a website and encountering issues with the responsiveness of rows on mobile devices. The desired outcome is for rows to be divided into 4 equal sections per row on larger screens, then scale down to 2 equal sections p ...

Managing errors with asynchronous operations through promises and the async module

I'm currently diving into the world of node.js, focusing on developing an API that interacts with mongodb. As I work on the apiRequest function, I realize that it needs to call two separate functions, each responsible for querying the database. Howev ...

Limiting the number of rows in pagination using a select option

Having a pagination feature on my page, I now aim to add a new functionality. When the user selects the number of rows from a drop-down menu, the webpage should display matching data. Despite trying to implement this with ajax, the limit variable is not be ...