Switching between divs using buttons

After researching examples and tutorials on HTML/CSS/jQuery, I was able to create a set of buttons that toggle content based on user interaction. However, I believe there must be a more efficient method of writing the code by using element identifiers or a similar approach. Since I am new to jQuery, I am open to any suggestions for improvement.

I am specifically seeking a solution that utilizes jQuery and Bootstrap.

$(document).ready(function() {
  $("#button1").click(function() {
    $("#div1").show();
    $("#div2").hide();
    $("#div3").hide();
    $("#div4").hide();
  });
  $("#button2").click(function() {
    $("#div1").hide();
    $("#div2").show();
    $("#div3").hide();
    $("#div4").hide();
  });
  $("#button3").click(function() {
    $("#div1").hide();
    $("#div2").hide();
    $("#div3").show();
    $("#div4").hide();
  });
  $("#button4").click(function() {
    $("#div1").hide();
    $("#div2").hide();
    $("#div3").hide();
    $("#div4").show();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<div class="container">
  <h2>Button group</h2>
  <div class="btn-group">
    <button id="button1" type="button" class="btn btn-primary">Div 1</button>
    <button id="button2" type="button" class="btn btn-primary">Div 2</button>
    <button id="button3" type="button" class="btn btn-primary">Div 3</button>
    <button id="button4" type="button" class="btn btn-primary">Div 4</button>
  </div>
  <div class="div-group">
    <div id="div1" style="background-color: red;">div 1</div>
    <div id="div2" style="background-color: blue;">div 2</div>
    <div id="div3" style="background-color: red;">div 3</div>
    <div id="div4" style="background-color: blue;">div 4</div>
  </div>
</div>

Answer №1

To easily select and hide sibling divs based on the index of a clicked button, you can utilize the index() method. This code snippet demonstrates how to achieve this functionality:

$('.btn-group button').click(function() {
  $('.div-group #div' + ($(this).index() + 1)).show().siblings().hide()
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <h2>Button group</h2>
  <div class="btn-group">
    <button id="button1" type="button" class="btn btn-primary">Div 1</button>
    <button id="button2" type="button" class="btn btn-primary">Div 2</button>
    <button id="button3" type="button" class="btn btn-primary">Div 3</button>
    <button id="button4" type="button" class="btn btn-primary">Div 4</button>
  </div>
  <div class="div-group">
    <div id="div1" style="background-color: red;">div 1</div>
    <div id="div2" style="background-color: blue;">div 2</div>
    <div id="div3" style="background-color: red;">div 3</div>
    <div id="div4" style="background-color: blue;">div 4</div>
  </div>
</div>

Answer №2

If you want to streamline your code, consider utilizing multiple selectors for a more efficient approach.

$("#btn1").click(function(){
   $("#box1").show();
   $("#box2, #box3, #box4").hide();
});

For more insights on using multiple selectors, check out this resource:

Answer №3

Despite the possibility of simplifying the expressions, I don't see any failure in approaching it that way. However, if you opt to utilize libraries like JQuery-ui, you can manipulate the HTML element's ID directly as indicated in the documentation. It seems to be what you're searching for.

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Tabs - Default functionality</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>
  $( function() {
    $( "#tabs" ).tabs();
  } );
  </script>
</head>
<body>
 
<div id="tabs">
  <ul>
    <li><a href="#tabs-1">Nunc tincidunt</a></li>
    <li><a href="#tabs-2">Proin dolor</a></li>
    <li><a href="#tabs-3">Aenean lacinia</a></li>
  </ul>
  <div id="tabs-1">
    <p>Proin elit arcu, rutrum commodo, vehicula tempus, commodo a, risus. Curabitur nec arcu. Donec sollicitudin mi sit amet mauris. Nam elementum quam ullamcorper ante. Etiam aliquet massa et lorem. Mauris dapibus lacus auctor risus. Aenean tempor ullamcorper leo. Vivamus sed magna quis ligula eleifend adipiscing. Duis orci. Aliquam sodales tortor vitae ipsum. Aliquam nulla. Duis aliquam molestie erat. Ut et mauris vel pede varius sollicitudin. Sed ut dolor nec orci tincidunt interdum. Phasellus ipsum. Nunc tristique tempus lectus.</p>
  </div>
  <div id="tabs-2">
    <p>Morbi tincidunt, dui sit amet facilisis feugiat, odio metus gravida ante, ut pharetra massa metus id nunc. Duis scelerisque molestie turpis. Sed fringilla, massa eget luctus malesuada, metus eros molestie lectus, ut tempus eros massa ut dolor. Aenean aliquet fringilla sem. Suspendisse sed ligula in ligula suscipit aliquam. Praesent in eros vestibulum mi adipiscing adipiscing. Morbi facilisis. Curabitur ornare consequat nunc. Aenean vel metus. Ut posuere viverra nulla. Aliquam erat volutpat. Pellentesque convallis. Maecenas feugiat, tellus pellentesque pretium posuere, felis lorem euismod felis, eu ornare leo nisi vel felis. Mauris consectetur tortor et purus.</p>
  </div>
  <div id="tabs-3">
    <p>Mauris eleifend est et turpis. Duis id erat. Suspendisse potenti. Aliquam vulputate, pede vel vehicula accumsan, mi neque rutrum erat, eu congue orci lorem eget lorem. Vestibulum non ante. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Fusce sodales. Quisque eu urna vel enim commodo pellentesque. Praesent eu risus hendrerit ligula tempus pretium. Curabitur lorem enim, pretium nec, feugiat nec, luctus a, lacus.</p>
    <p>Duis cursus. Maecenas ligula eros, blandit nec, pharetra at, semper at, magna. Nullam ac lacus. Nulla facilisi. Praesent viverra justo vitae neque. Praesent blandit adipiscing velit. Suspendisse potenti. Donec mattis, pede vel pharetra blandit, magna ligula faucibus eros, id euismod lacus dolor eget odio. Nam scelerisque. Donec non libero sed nulla mattis commodo. Ut sagittis. Donec nisi lectus, feugiat porttitor, tempor ac, tempor vitae, pede. Aenean vehicula velit eu tellus interdum rutrum. Maecenas commodo. Pellentesque nec elit. Fusce in lacus. Vivamus a libero vitae lectus hendrerit hendrerit.</p>
  </div>
</div>
 
 
</body>

Answer №4

To streamline your code, consider using a single if statement that determines the action based on the id of the clicked element, rather than creating multiple click events for each specific id. Take a look at this demo for an example:

$(document).ready(function() {
  $('button').click(function() {
    if (this.id == 'button1') {
      $("#div1").show();
      $("#div2, #div3, #div4").hide();
    } else if (this.id == 'button2') {
      $("#div1, #div3, #div4").hide();
      $("#div2").show();
    } else if (this.id == 'button3') {
      $("#div1, #div2, #div4").hide();
      $("#div3").show();
    } else if (this.id == 'button4') {
      $("#div1, #div2, #div3").hide();
      $("#div4").show();
    }
  })
});

Answer №5

If you have the following HTML structure:

<div class="container">
  <h2>Button group</h2>
  <div class="btn-group">
    <button class="button btn btn-primary">Div 1</button>
    <button class="button btn btn-primary">Div 2</button>
    <button class="button btn btn-primary">Div 3</button>
    <button class="button btn btn-primary">Div 4</button>
  </div>
  <div class="div-box">
    <div class="box" style="background-color: red;">div 1</div>
    <div class="box" style="background-color: blue;">div 2</div>
    <div class="box" style="background-color: grey;">div 3</div>
    <div class="box" style="background-color: green;">div 4</div>
  </div>
</div>

You can simplify your jQuery code into a single .click() function to toggle the visibility of the div boxes based on the button clicked:

$('.button').click(function() { 
  var index = $(this).index() + 1;
  $('.div-box div:nth-of-type('+index+')').show().siblings().hide();
});

Make sure to include the necessary CSS and JavaScript files:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

Answer №6

If you assign the id of the DIV to be displayed to a data-rel attribute of the button, you can then retrieve it using Jquery when the button is clicked.

$(".btn-primary").click(function(e) {
e.preventDefault();
$('.div-group div').hide();
$('#' + $(this).data('rel')).toggle();});

I have created a demo on JSFiddle: https://jsfiddle.net/pj4m9cbe/1/

Answer №7

To create a tab system, assign a unique id to each button and link it to the corresponding tab with the same id.

Upon clicking a button, hide all tabs and display the one with the matching id.

$(document).ready(function() {
  
  $("ul a").click(function() {
    var thisId = $(this).attr("id") ; //Retrieve id of clicked tab
    
    $("ul a").removeClass("active") ; //Deselect all tabs
    $(".tab").removeClass("active") ; //Hide all tab contents
    
    $(this).addClass("active") ; //Select clicked tab
    $(".tab[id='" + thisId + "']").addClass("active") ; //Display content related to the clicked tab
  }) ;
  
  $("ul").find("li").first().find("a").trigger("click") ; //Show content of first tab on page load
  
}) ;
.clear{
  display: block;
  clear: both;
}
ul{
  list-style: none;
  display: block;
}
li{
  float: left;
  margin-right: 10px;
}
a{
  text-decoration: none;
}
a.active{
  color: #ff2525;
}

.tabs{
  margin-top: 30px;
  display: block;
}
.tabs .tab {
  display:none;
}
.tabs .tab.active{
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li><a href="javascript:;" id="tab1">Tab 1</a></li>
  <li><a href="javascript:;" id="tab2">Tab 2</a></li>
  <li><a href="javascript:;" id="tab3">Tab 3</a></li>
  <li><a href="javascript:;" id="tab4">Tab 4</a></li>
<ul>
<div class="clear"></div>
<div class="tabs">
  <div class="tab" id="tab1">This is Tab 1</div>
  <div class="tab" id="tab2">This is Tab 2</div>
  <div class="tab" id="tab3">This is Tab 3</div>
  <div class="tab" id="tab4">This is Tab 4</div>
</div>

Answer №8

Utilizing the power of index(), eq(), and chaining these methods for seamless functionality

$('.btn-group button').click(function(){
   var idx = $(this).index();
   // hiding all div elements before displaying the corresponding indexed one
   $('.div-group div').hide().eq(idx).show() 
})
.div-group >div{display:none}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<div class="container">
  <h2>Button group</h2>
  <div class="btn-group">
    <button id="button1" type="button" class="btn btn-primary">Div 1</button>
    <button id="button2" type="button" class="btn btn-primary">Div 2</button>
    <button id="button3" type="button" class="btn btn-primary">Div 3</button>
    <button id="button4" type="button" class="btn btn-primary">Div 4</button>
  </div>
  <div class="div-group">
    <div id="div1" style="background-color: red;">div 1</div>
    <div id="div2" style="background-color: blue;">div 2</div>
    <div id="div3" style="background-color: red;">div 3</div>
    <div id="div4" style="background-color: blue;">div 4</div>
  </div>
</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

Selecting multiple rows in the Telerik MVC Grid is a breeze!

I've searched extensively for a solution to this, but haven't been able to find one. Is there anyone out there who knows if it's possible to select multiple rows at once by holding down the shift or control key instead of using checkboxes? ...

What is the best way to add shadow effects to a DIV using CSS?

Is there a way to add shadows within an element using CSS? I attempted the following method but it did not work: #element { shadow: 10px black; } ...

Using jQuery Mobile for Enhanced PHP Form Submissions

My jquery mobile application code is not functioning properly when it comes to posting data from a form created using PHP. I even attempted using data-ajax="false", but the form still doesn't submit the data as expected. <table id="stock"> < ...

Is there a way to extract all nested URLs on a webpage using rvest and xml2?

I need assistance extracting nested links from the website provided. Despite my efforts, the code I am using is only producing an empty character vector. url1 <- "https://samplewebsite.com/sample-page" url1 <- read_html(url1) url1_body < ...

The jQuery validation error message states that the object 'this.0.form' is either null or does not exist

My code is generating an error in ie7 that says 'this.0.form' is null or not an object. The issue occurs when a button triggers the form to submit upon being clicked. In other browsers, the form is validated by the validation plugin without any p ...

create a miniature display featuring text and visuals using HTML

Currently, I am in the process of developing a website and require assistance. My goal is to have a small screen appear with text and images whenever a link is clicked, similar to the functionality found in Chrome's "chrome://settings/startup". Howeve ...

PHP: Showing the content of every div on the page

I am facing an issue with retrieving input values from multiple divs in the HTML code provided below. Specifically, I want to extract the Input values with the name LI_Dept as an array for each individual div when handling data in PHP. Is there a way to f ...

Is it possible to create a grid by arranging each statement with a specific format?

After fetching and parsing some data, I have utilized the 'each' function to display it: $.ajax({ url : 'http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent('htt ...

Offsetting absolute elements in a horizontal landscape view

When I view my page on a mobile browser (tested on Android JB and iOS 6), it renders fine initially in both portrait and landscape modes. However, the issue arises when I switch from landscape to portrait - the absolute positioned divs are offset from thei ...

What is the process for generating a GET request for selected checkboxes and subsequently showcasing the data on an HTML webpage?

Currently working on an app project and need assistance with implementing a feature. I have successfully set up a POST method for the checkboxes that are checked, but I am unsure how to retrieve this data and display it on my HTML page using a GET method ...

Search for a DIV element within iMacro on a consistent basis

I recently started using iMacro and encountered an issue while recording a script that involved clicking on a pop-up when it appeared on the screen. The problem arose because the pop-up only appears when a new event is posted. Therefore, when I initially c ...

Jquery and adaptability

I currently have a scrollTo anchor link script on my website that has an offset of -35px to account for my 35px high navigation bar. However, I find that this offset may need to be adjusted for different screen resolutions, such as smartphones or tablets ...

The optimal method for selecting a button from a group of buttons on a calculator using pure JavaScript

I have developed an HTML/CSS code inspired by the Mac/Apple calculator design. It features buttons organized in 5 rows using flexbox. You can view my code on this codepen: <div class="wrapper"> <div class="calheader"> ...

Issues with HTML text areas tags not being recognized after submitting a form occur specifically in Internet Explorer

I am encountering an issue with my form. I have a textarea field within the form, and on submit, I am trying to copy the content of a div containing a table into this textarea field. However, when I send this form and the email in IE, the values appear as ...

Issue with jquery .val() function not functioning as expected

I am experimenting with the jQuery .val(value) function to set the value of an attribute using the code snippet below. <!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">< ...

Customize the appearance of the search box in Serverside Datatables

Is there a way to adjust the search and show inputs for datatables so that I can customize their width and make them fit my dynamic column sizing? The issue I ran into is that these inputs are enclosed within <label> tags in the source JavaScript, an ...

Ensure each list item is directly aligned when swiping on a mobile device

Looking to make a simple horizontal list swipeable on mobile devices with tabs that snap from tab to tab, activating the content for the active tab immediately. The desired effect is to swipe directly from one tab to the next without having to click separ ...

Tips for resolving unforeseen issues stemming from a CSS selector

Currently, I am diving into the world of SASS and experimenting with building webpages using this preprocessor. However, I encountered some errors in the CSS file generated from the SASS file. Below is the snippet of CSS code that is causing the issue: .l ...

The functionality of window.localStorage.removeItem seems to be malfunctioning when used within an $http

Currently, I am sending a post request to my web service and upon successful completion, I am attempting to remove a token from local storage. Here is the code snippet: $http.post("MyService/MyAction").success(function (res) { if ( ...

Looking to retrieve just your Twitter follower count using JavaScript and the Twitter API V1.1?

I am trying to retrieve my Twitter follower count using JavaScript/jQuery in the script.js file and then passing that value to the index.html file for display on a local HTML web page. I will not be hosting these files online. I have spent weeks searching ...