Displaying a single div while concealing the remaining two divs upon pressing a button

There are 3 hidden DIVs on a webpage. Clicking on a heading should display one DIV while hiding the other 2. Below is the code I used to achieve this, but it doesn't work properly on all browsers like iPad and iPhone. Is there a more efficient way to achieve the same result?

<html xmlns="http://www.w3.org/1999/xhtml">
<script type="text/javascript" Src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

<head runat="server">
<style>
.div1, .div2, .div3 { display:none; }
</style>

<script>
$(window).load(function () {

    $(".bt1").click(function () {
        $(".div1").css("display", "block");
        $('[class^="div"]:not(.div1').css("display", "none");
    });

    $(".bt2").click(function () {
        $(".div2").css("display", "block");
        $('[class^="div"]:not(.div2').css("display", "none");
    });

    $(".bt3").click(function () {
        $(".div3").css("display", "block");
        $('[class^="div"]:not(.div3').css("display", "none");
    });
});
</script>

</head>
<body>
<form id="form1" runat="server">
<div id="divID1" class="bt1">bt1</div>
<div id="divID2" class="bt2">bt2</div>
<div id="divID3" class="bt3">bt3</div>
<br />

<div id="id1" class="div1">Content1</div>
<div id="id2" class="div2">Content2</div>
<div id="id3" class="div3">Content3</div>

</form>

Answer №1

To streamline your code, consider utilizing a single handler such as:

$(window).load(function() {
  var $divs = $('.div');
  $(".btn").click(function() {
    var $target = $('#' + $(this).data('target')).show();
    $divs.not($target).hide();
  });
});
.div {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="form1" runat="server">
  <div data-target="id1" class="btn">bt1</div>
  <div data-target="id2" class="btn">bt2</div>
  <div data-target="id3" class="btn">bt3</div>
  <br />
  <div id="id1" class="div">Content1</div>
  <div id="id2" class="div">Content2</div>
  <div id="id3" class="div">Content3</div>
</form>

Answer №2

$(".btn").hide();
$(".btnP").click(function() {
  $(".btn").hide();
  $("#" + $(this).data("rel")).show();
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form id="form1" runat="server">
  <div data-rel="btn1" class="btnP">bt1</div>
  <div data-rel="btn2" class="btnP">bt2</div>
  <div data-rel="btn3" class="btnP">bt3</div>
  <br />

  <div id="btn1" class="btn">Content1</div>
  <div id="btn2" class="btn">Content2</div>
  <div id="btn3" class="btn">Content3</div>

</form>

Answer №3

function switchTab(selection)
{
    $('#contents').find('div').not('#'+$(selection).attr('rel')).hide();
    $('#contents').find('#'+$(selection).attr('rel')).show();
}

$('#form1 div').click(function() { switchTab(this); });

Explore this JSFiddle example: http://jsfiddle.net/8n6rsvbL/

Answer №4

I am undecided on whether to utilize classes or ids, the choice is yours :)

Here is the HTML code snippet:

<form>
    <div class="btn" data-related-div="div1">Button 1</div>
    <div class="btn" data-related-div="div2">Button 2</div>
    <div class="btn" data-related-div="div3">Button 3</div>
    <br>
    <div class="div1 div">Content 1</div>
    <div class="div2 div">Content 2</div>
    <div class="div3 div">Content 3</div>
</form>

The corresponding CSS:

.div {
    display: none;
}

JavaScript using jQuery:

$(".btn").click(function () {
    $('.div').hide();
    $('.' + $(this).data('related-div')).show();
});

Check out the demo on JSFiddle

Answer №5

To simplify your code, consider using a shared class bt for buttons and div for div elements.

<form id="form1" runat="server">
<div id="divID1" class="bt">bt1</div>
<div id="divID2" class="bt">bt2</div>
<div id="divID3" class="bt">bt3</div>
<br />

<div id="id1" class="div">Content1</div>
<div id="id2" class="div">Content2</div>
<div id="id3" class="div">Content3</div>
</form>

You can then use a single handler to make it work:

$(".bt").click(function () {
   $(".div").hide().eq($(".bt").index(this)).show();
});

View the working demo here

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

Customize the background color of highlighted text using HTML and jQuery

Recently, I modified an existing code to divide plain text into four classes by selecting a portion of the text and coloring it. Afterwards, I extracted the text of each class and stored it in my database. While this code works well, I am looking for a way ...

Scrolling causes the header background color to change

Currently facing an issue with changing the background color of the header on scroll for my WordPress site. Using the scrollTop function to achieve this, but getting a function as the returned value instead. By logging the scroll position to the console us ...

Unable to generate a vertical navigation bar

When attempting to create a vertical menu, the final result doesn't align as expected. https://i.stack.imgur.com/2ok47.jpg This is the current code being used: $("#example-one").append("<li id='magic-line'></li>") ...

I require the slideshow div to smoothly move elements down as it transitions between slides

I'm facing an issue with a jquery slideshow that contains quotes of varying lengths. The problem is, the longer quotes overlap with the content below them. I'm trying to figure out how to make the longer quotes push the rest of the page down, avo ...

Comparing JSON Objects in Javascript

I'm in the process of developing a web application that retrieves data from a server and displays it to the user. The script pulls data from the server every 10 seconds, and if there's any change in the data, it alerts the user. Currently, the co ...

Using the "align" attribute is considered outdated and not recommended in HTML5 documents

I have encountered an error when using the align attribute. How can I fix this issue with the correct HTML5 compatible syntax? <table style="margin: 0 auto;"> <tbody> <tr> <td><input typ ...

Semantic UI Footer allows you to easily create a stylish

Greetings! I'm new to the semantic-ui framework and I'm encountering an issue with the footer. My goal is to have the footer always stay at the bottom of the page without being fixed. Here's a snippet of my simple HTML code: <!DOCTYPE h ...

Say goodbye to using 'jQuery .load()' with <img> elements inside <a> tags

I have a static HTML page and some other files with the same structure but different content. <div id="textRed" class="scrollbar"> <h1>Header</h1> <p>Lorem Ipsum</p> <a href="images/image1.jpg" data-lightbox ...

Aligning Font Awesome icons inside md-buttonsFinding the perfect alignment for

I am attempting to center font awesome icons within a button so that they align perfectly with the text on a toolbar. Below is the code snippet I am working with: <div ng-app="app"> <md-toolbar> <div class="md-toolbar-tools" md-tall ...

take a paragraph element outside of a container div

In my ASP project, I have incorporated JavaScript and CSS code that I obtained from JonDesign's SmoothGallery demo website. Now, I am trying to move the p tag containing the summary out of the div. Here is the current code snippet: <div id="myGall ...

Issue with Empty Selection in Drop Down List

How to bind a dropdown list with null value in the database? Solution: Select job_id and job_name from jobs, then union select null as none for both columns. ...

Automatically integrating Nivo Lightbox into your website

I incorporated Nivo Lightbox into my website, seamlessly integrating all images with the plugin using the following code: <div class="portfolio-item"> <div class="portfolio-thumb "> <a class="lightbox" data-lightbox-type="ajax" title="Strat ...

The autosearch feature seems to be malfunctioning

I am currently working on implementing an autocomplete suggestion feature using the AutoComplete plugin from GitHub. I am using a combination of HTML, JavaScript, and CSS for this project. The functionality works perfectly when I hardcode the data in the f ...

Div displaying with extra space below

UPDATE check out the new jsfiddle link here that effectively showcases the problem I am encountering an issue with white space appearing below my div. This can be seen in 2 photos, one of which is scrolled down: https://i.sstatic.net/yHlXL.png https:// ...

The website appears to be loading in a unique way on mobile upon the second loading

While developing my personal website, I encountered a bug that occurs when accessing the site on my Android phone using Firefox or Chrome. The issue arises when the page initially loads correctly, but upon refreshing, the layout is displayed differently. ...

delete the final directory from a file directory

let currentLocation = window.location.pathname; let directory = currentLocation.substring(0, currentLocation.lastIndexOf('/')); The current location is: /examples/html/home/ The directory is: /examples/html/home I am trying to remove the las ...

Creating dynamic content with Jquery templates using nested JSON objects

Currently, I am working on an app where I need to showcase a student's progress card using jQuery templates. However, I have encountered a difficulty while dealing with a JSON string as shown below: "[{"ID":1, "Name":"Frank", "Age":15, "Status":"Pass ...

The CSS file is failing to recognize the changes made to the data-theme attribute in the HTML

Currently implementing a dark theme on my website involves adding a toggle switch to the footer.html page, which adds a variable named data-theme = 'dark' to the html. The scss files of the footer and core are adjusting accordingly based on the c ...

Utilizing Bootstrap for aligning a span element beneath a div container

I'm working on enhancing a project by integrating more Bootstrap elements. In one part, I have a circular div with the text "Go to Homepage" below it. My goal is to center the span under the div and have it appear on a single line. How can I achieve t ...

The menu on Android gets cut off by the status bar

Seems like an easy fix, our menu is getting cut off by the status bar on certain Android devices as shown in this screenshot. Any suggestions on how to resolve this issue? Could it be related to z-index properties? https://i.sstatic.net/Jh5SZ.png ...