Display 'Div 1' and hide 'Div 2' when clicked, then reveal 'Div 2' and hide 'Div 1' when a different button is clicked

I need help figuring out how to make two separate buttons work. One button should display 'Div 1' and hide 'Div 2', while the other button should show 'Div 2' and hide 'Div 1' when clicked.

My knowledge of jquery and js is limited, so I've only been able to come up with this...

jsfiddle

$('.button-1').click(function() {
  var i = $(this).index();
  $('.div-2').hide();
  $('.div-1' + (i+1)).show();
});

If anyone can provide assistance, it would be greatly appreciated!

Answer №1

$('.button-1').click(function() {
    $('.div-2').hide();
    $('.div-1').show();
});

$('.button-2').click(function() {
    $('.div-1').hide();
    $('.div-2').show();
});

Answer №2

To reveal the desired box, first conceal both boxes:

$('.button-1, .button-2').click(function() {
  $('.boxes > div').hide();
  $('.div-' + $(this).index()).show();
});

Check out this demonstration on Fiddle

Answer №3

Instead of using + (i + 1), you can simply toggle the visibility between div-1 and div-2 based on which button is clicked.

$('.button-1').click(function() {
      $('.div-2').hide();
      $('.div-1').show();
});
$('.button-2').click(function() {
      $('.div-1').hide();
      $('.div-2').show();
});
.boxes {
    height: 100px;    
}

.div-1 {
    background-color: red;
    width: 50px;
    height: 50px;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 2;
}

.div-2 {
    background-color: blue;
    width: 60px;
    height: 60px;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1;
}

button {
    position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="boxes">
    <div class="div-1">Div 1</div>
    <div class="div-2">Div 2</div>
</div>    

<button class="button-1">Button 1</button>
<button class="button-2">Button 2</button>

Answer №4

If you want to achieve this effect, you can use the following code:

$('.button-1').click(function() {

    $('.div-2').hide();
    $('.div-1').show();
});

$('.button-2').click(function() {

    $('.div-1').hide();
    $('.div-2').show();
});

http://example.com/jsfiddle/code1234

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 creating a responsive tab indicator in Material UI?

I successfully integrated react router with material-ui and the routing system is working as expected. Clicking on a tab routes you to the corresponding component. However, I am facing an issue where the blue underline indicator that typically accompanies ...

SVGs do not display on iPhones

Having some issues with my code - specifically, I have an SVG animation that seems to work on all devices except iPhones. I've been struggling to find a solution. Here is the code snippet for the SVG: <div class="contenuto-svg"> <svg vi ...

Avoid unnecessary re-renders in ReactJS Material UI tabs when pressing the "Enter

I've created a user interface with tabs using material-ui in reactJS. The issue I'm facing is that every time a tab is selected, the content under that tab reloads, causing performance problems because there's an iFrame displayed in one of t ...

Origin of SVG Circle Stroke

Describing my current issue is proving to be challenging, but I'll do my best: My project involves creating an SVG circle progress bar and fortunately, I came across a great example that aligns with what I aim to achieve. I prefer not to use any thir ...

Experiencing a problem with a loop in iMacros/JS?

I have an iMacros/JS script for Facebook that logs into a FB account from a CSV file, then it has a second loop j which sends 20 friend requests from each account. The issue arises when switching accounts and encountering a popup message requiring phone n ...

A Comprehensive Guide to Handling Errors in Angular 4: Passing the err Object from Service to Component

Currently, I am in the process of developing a login page using Angular for the front-end and Spring Security for the back-end. Everything appears to be functioning correctly, except for handling exceptions when attempting to catch errors from the service ...

Creating a bordered triangle using only CSS

Looking to create a message holder with a triangular tip bordered shape? I've successfully crafted the tip using two triangles: #triangle-border { width: 0px; height: 0px; border-style: solid; border-width: 0 100px 80px 100px; bor ...

Customizing skin CSS for DNN Portal and Page images

Currently, I have a unique custom skin that I personally created. It is implemented on multiple portals that I am responsible for managing. My goal is to incorporate the ability for the header image to change based on the specific page being viewed. The he ...

Triggering a re-render in React

There are times when I find myself needing to trigger a re-render while still in the middle of executing a function. As a solution, I've developed a method using the state variable my_force_update. Basically, I change it to a random value when I want ...

I am encountering unexpected issues with the functionality of img srcset and sizes

Attempting to enhance the responsiveness of images on my website has led me to discover the srcset and sizes attributes. The objective is clear: If the screen size exceeds 600px or falls below 300px, a 250x250 image should be displayed For sizes in betw ...

Stop a hyperlink from refreshing the webpage

Currently, I am in the process of developing a responsive menu. You can view a demo of my progress on Codepen. In order to prevent the page from reloading when I click a link within the menu, I have implemented the following JavaScript code: $('nav. ...

Adjust the formatDate function in the Material UI datepicker

I recently implemented the material-ui datepicker component with redux form and it's been working great. However, I have encountered a minor issue. Whenever I change the date, it displays in the input field as yyyy-mm-dd format. I would like it to app ...

Learn how to implement form validation on a sliding form in just 5 easy steps using jQuery

I am new to programming and I struggle to comprehend complex JavaScript code written by others. Instead of using intricate code that I don't understand, I would like to request help in creating a simplified jQuery script for me to implement. Current ...

The useEffect alert is triggered before the component is re-rendered

Can someone help me understand why the HP in the code below is displayed as "1" when the alert is thrown, and only set to "0" after I confirm the alert? Shouldn't the component be rerendered before the alert is thrown so that it has already been displ ...

How can the callback from C++ be successfully installed in the Javaobject window within QtWebkit?

I have successfully implemented HTML-JS to call a C++ method using QtWebkit. Now, I want to send a callback from the C++ method to the JavaScript window. How can I achieve this? Below is my code snippet. #include <QtGui/QApplication> #include <Q ...

AngularJS - Import and save CSV files

I have set up a nodeJS program as the server and an AngularJS web application as the client. For generating CSV files, I am utilizing the "express-csv" library (https://www.npmjs.com/package/express-csv) Below is the code for the server side: Definition ...

Ways to reach state / methods outside of a React component

Implementing the strategy design pattern to dynamically change how mouse events are handled in a react component is my current task. Here's what my component looks like: class PathfindingVisualizer extends React.Component { constructor(props) { ...

Node.js is known for its unreliable promise returns

Currently, I have a function in place that establishes a connection with a sql database. After querying the database and formatting the results into an HTML table, the function returns the variable html: function getData() { return new Promise((resolv ...

How to populate an ExtJS 3.4 combobox with local JSON data in a few simple steps

I am utilizing ExtJS 3.4 and in need of populating a combobox with specific data obtained from a previous XMLHttpRequest, stored in a variable as follows: my_variable = "[{"cod_domini":"1","nom_domini":"Sant Esteve de Palautordera"},{"cod_domini":"2","no ...

Facing difficulties in retrieving my static files with Express and Node.js

I'm puzzled as to why express isn't able to access my static file to display my CSS. Here is the code snippet from express.js: app.use(express.static(__dirname + '/public')); Contents of style.css: <style type="text/css"> bod ...