Simplifying the process of implementing Jquery CSS Toggles

I am planning to simplify the process of toggling visibility for 12 different divs when clicking on 12 different buttons. Instead of repeating the same code multiple times, I am considering a more efficient approach.

My idea is to:

Step A) Initially hide all divs

Step B) Use a switch statement to compare with the clicked element and show the corresponding DIV as inline-block

Do you think this would be a good solution?

Please find my current progress on this CodePen link here.

Thanks in advance,

EDIT: I am currently encountering an "unexpected identifier" error on each case statement. Here is the updated code snippet:

$(".klik").click(function(){

    $("#oppehoejre").children().css("display","none"); 
    $("#nedrevenstre").children().css("display","none");

    var emne = $(this).attr('id');

    alert(emne);

    switch (emne) {             

        Case 'klik_multimedia':
            $(".multimedia").css("display","inline-block");
            break;

        Case 'klik_student':
            $(".sprogligstudent").css("display","inline-block");
            break;                      

        Case 'klik_datamatiker':
            $(".datamatiker").css("display","inline-block");                    
            break;                      

        Case 'klik_itdiplom':
            $(".itdiplom").css("display","inline-block");                   
            break;                      
        
        default:
            $(".multimedia").css("display","inline-block");
            break;                      

    };

});

Answer №1

After reviewing your inquiry, I believe this solution aligns with what you are seeking. Feel free to check out the code snippet on this fiddle link.

$(document).ready(function() {
  $("button").click(function() {
    var n = $('button').index(this);
    position = n + 1;
    $("div").removeClass("display_me");
    $("div").addClass("display_none");
    $("div:nth-child(" + position + ")").removeClass("display_none");
    $("div:nth-child(" + position + ")").addClass("display_me");
  });
});
div {
  height: 100px;
  width: 100px;
  background: #fff;
  font-size: 20px;
  text-align: center;
}

.display_none {
  display: none;
}

.display_me {
  display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="display_none display_me">1</div>
<div class="display_none">2</div>
<div class="display_none">3</div>
<div class="display_none">4</div>
<div class="display_none">5</div>
<div class="display_none">6</div>
<button>
  Click 1
</button>
<button>
  Click 2
</button>
<button>
  Click 3
</button>
<button>
  Click 4
</button>
<button>
  Click 5
</button>
<button>
  Click 6
</button>

Answer №2

Are you looking for something like this?

Simplified HTML:

<div id="click_diploma">click_diploma</div>
<div id="click_student">click_student</div>

Using jQuery:

$('#click_student, #click_diploma').on('click', function(){

$(".computer_engineer").css("display","none");
    $(".diploma_holder").css("display","none");               
    $(".multimedia_designer").css("display","inline-block");                 
    $(".language_student").css("display","none");

});

View Example on jsFiddle

Answer №3

Finally cracked the code!

This new approach makes managing the display of elements so much smoother, eliminating the need to write a .click block for each scenario.

Adding 8 extra cases to the page is now a breeze with minimal additional code required.

$(".klik").click(function(){    // Wait for an element with class .klik to be clicked

    $("#oppehoejre").children().css("display","none"); // Hide all inner frames in oppehoejre
    $("#nedrevenstre").children().css("display","none"); // Hide all inner frames in nedrevenstre 

    var subject = $(this).attr('id');

    // alert(subject); // Used only for debugging purposes

    switch (subject) {             // Switch to display only relevant content

        case 'klik_multimedia':
            $(".multimediedesigner").css("display","inline-block");
            break;
        case 'klik_student':
            $(".sprogligstudent").css("display","inline-block");
            break;                      
        case 'klik_datamatiker':
            $(".datamatiker").css("display","inline-block");                    
            break;                      
        case 'klik_itdiplom':
            $(".itdiplom").css("display","inline-block");                   
            break;                      
        default:
            $(".multimedia").css("display","inline-block");

    };

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

CSS slideshow with automatic horizontal image transition that seamlessly restarts

I am facing an issue with my HTML & CSS automatic horizontal slideshow. Everything works fine, except for when the last image finishes sliding and the slideshow loops back to the first image, there is a sudden jump in the appearance of the first image. How ...

Using jQuery, hide any table rows that have a concealed field that matches a specific value

While I am aware that this question may have been answered before, I have not been able to find a satisfactory answer for my specific query. I am trying to filter rows in a table based on whether or not they contain a hidden field with a specific value. ...

Tips for adjusting font sizes within the same HTML header?

Looking to design an HTML header in the following format: "(10.3.4) Version1: vs (10.3.4) Version2:" Need the version numbers to be smaller than "Version1" and "Version2." Any ideas on how to achieve this? ...

Get the PDF file and access it with Ajax technology

I am facing an issue with my action class that is responsible for generating a PDF. The code snippet shown sets the contentType appropriately. public class MyAction extends ActionSupport { public String execute() { ... ... File report = si ...

Form validation in AngularJS for controllers with multiple instances

My specific needs In order to meet the unique requirements of my business, manual validation is necessary. The validation rules can vary in strictness depending on the context in which a specific screen is accessed. It is also important to note that ther ...

How to create centered striped backgrounds in CSS

Attempting to achieve a background similar to the one shown Can this be accomplished using CSS? ...

iPhone 3GS and 4 not expanding DIVs by 100%

I've been encountering a significant issue with a div that's set to 100%. It displays properly on desktop screens, but on iPhones, there appears to be a gap on the right side. I've attempted to use the following CSS: body { min-width:980p ...

How can I add rows to the tbody of a table that is already inside a div container?

I have an existing table and I want to append a tbody element to it. Below is an example of the HTML table: <div id="myDiv"> <table class="myTable"> <thead> <tr> <th>ID</th> ...

A step-by-step guide on how to display a specified amount of images in the center of

I'm currently working with a div that displays images dynamically loaded from a database, ranging from 1 to 5 images. The number of images may vary each time, and I need assistance in centering these images inside the div regardless of their quantity. ...

Control the switch for CSS selectors

Consider the following scenario where CSS rules are defined: <style> table {background:red;} div {background:green;} </style> In addition, there is HTML code that calls a JavaScript function: <table onclick="tu ...

How come the dropdown menu consistently disrupts my CSS design?

Whenever I add a dropdown menu, my CSS layout gets all messed up. Can someone please explain why this happens and how to fix it? Below is the code snippet: <asp:Label ID="projnamelbl" runat="server" CssClass="editlabels" Text="Project Name"></as ...

Get the PDF document via FTP by utilizing an XMLHttpRequest and a generic handler

Attempting to download a PDF file from an FTP server using a JQuery Ajax request. The reference used was found at . Below is the Jquery ajax call being made: $.ajax({ xhr: function () { var xhr = new window.XMLHtt ...

I developed an RPG game with an interactive element using jQuery. One of the biggest challenges I'm facing is the random selection process for determining which hero will be targeted by the enemy bots during battles

Hello, this marks my debut on stack overflow with a question. I've created a game inspired by old school RPGs where players choose from three heroes based on the Marvel universe to battle one of three enemies. The problem I'm facing is that even ...

What is the best way to extend an image to fill the width of a webpage?

Can you advise me on how to expand the image to fit the width of my webpage? If possible, could you take a look at this website: Poklanjam The specific image I am referring to is the one of the city on the left-hand side. What additional CSS code should ...

The offset value was inconsistent in the desktop version of Firefox

Could you take a look at my code on the fiddle link, Here is the code snippet: <body> <div id="content" style="width:400px; height:110px;"> <svg id="circle" height="300" width="300"> <circle cx="150" cy="150" r="40" st ...

Centered flex item with a flexbox grid underneath

Looking to create a layout with an intro section on the left side and a sidebar on the right within a container. Below the intro section, I want four divs evenly spaced like a grid. But I'm struggling with setting up this grid, possibly due to flexbo ...

Adjusting the background color using CSS according to the browser's dimensions

I'm having trouble identifying the issue with this code. The background color remains white and doesn't change as expected. <style type="text/css"> h1 { position: absolute; text-align: center; width: 100%; ...

What is the best way to integrate HTML templates into AngularJS?

I am currently working on developing an HTML fragment that will eventually function as an image slider. At this point, it only consists of a test div element: slider.html: <div>TEST</div> In order to incorporate this into my index.html, I hav ...

A particular character is displayed exclusively in a text box using either jQuery or JavaScript

Text Box <input id="txtbo" type="text" value="CAN'T TOUCH THIS!" size="50" /> Solution Using jQuery or Javascript: var readOnlyLength = $('#txtbo').val().length; $('#txtbo').on('keypress, keydown', function(even ...

Enhance your iPad's design with a stylish div box-shadow

I'm in the process of developing a touch-optimized web application. As part of the design concept, I've implemented some visually appealing div elements that respond to clicks or touches for easy navigation. While this functionality works perfec ...