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

Interactive sidebar scrolling feature linked with the main content area

I am working with a layout that uses flexboxes for structure. Both the fixed sidebar and main container have scroll functionality. However, I have encountered an issue where scrolling in the sidebar causes the scroll in the main container to activate whe ...

Is there a way to position an image to the left of the container in Jinja templating while floating it?

I am currently working on a project using Flask that utilizes Jinja templates. In my layout.html file, there is a grey colored container that extends to all child pages. I have a specific page that extends the layout.html where I want to place an image flo ...

Is there a way to use a less mixin or selector to adjust the position depending on the sibling

Currently, I am working on adjusting the position of multiple sibling divs depending on their order. Although they are all currently set to position: absolute, this may change. Each div is a few hundred pixels tall, but I want them to overlap in such a wa ...

What is causing me to have difficulty importing any of the images located in the public folder?

I'm currently tackling the NextJS framework, and I'm having trouble importing images that are stored in the public folder. Despite being able to navigate through folders, the images aren't displaying as expected. Here is the import line and ...

"Learn how to smoothly navigate back to the top of the page after a specified amount of time has

Just starting out with JS, CSS, and Stack Overflow! I'm currently working on a div box that has the CSS property overflow: auto. Is it possible to make the box automatically scroll back to the top after a certain amount of time when the user scrolls ...

jQuery form validation not functioning as expected

I'm attempting jQuery form validation but encountering issues with the desired functionality. I would like the border of an input to turn red when it's empty upon focus out. Alternatively, I aim to incorporate the "has-danger" bootstrap class to ...

Issue with Flat-UI: Navigation bar is not collapsing correctly. Need help to resolve this problem

I am currently utilizing the most recent Twitter Bootstrap along with Flat UI. I have been trying to create a basic navbar that collapses when the screen size is reduced. How can I resolve this issue? This is how it currently appears: My navigation items ...

Problem with items overlapping in hoverable drop-down menu

I have been attempting to create a hoverable dropdown menu, but I am encountering an issue where the items of the dropdown are overlapping. Despite my efforts to adjust the CSS classes, I have not been successful in fixing this problem. Additionally, I ha ...

Ways to halt a CSS animation when it reaches the screen boundary

I put together this demo: By clicking, a red box falls down. The issue arises when trying to determine the screen size using only CSS. In my demo, I set the box to fall for 1000px regardless of the actual screen height. Here is the keyframe code snippet ...

What is the best way to retrieve the previously chosen value from one dropdown and populate it into another dropdown when

I have 3 choices available. When the user selects the third option, a jQuery onchange event is triggered to send the variable to another PHP file for database validation based on the selected id. The challenge lies in how I can also include the variables f ...

Transmitting a jQuery array from the client to the server using AJAX in

I've looked at so many posts about this issue, but I still can't get my code to work. My goal is to retrieve a PHP array of values from the checkboxes that are checked. Here is my code snippet: <!doctype html> <html> <head> & ...

Inconsistency in date serialization using JSON.stringify across various web browsers

I've written this snippet in an HTML file: alert(JSON.stringify(new Date())); To cater to older browsers lacking JSON.stringify(), I've included the latest json2.js (2009-09-29 version) along with jquery-1.3.2.js. In modern browsers with native ...

Issue with jQuery .css() function malfunction in Internet Explorer

While trying to enhance my website, I experimented with the Add class method $("select[name='" + ABC+ i + "']").addClass('addBorder'); To my disappointment, it worked smoothly in Chrome, FF, and Safari but failed in IE. So I decided ...

Blending an HTML jQuery toggle

Is there a way to make the current headline fade out while simultaneously fading in a new one when switching to the next div using a jQuery .html switch? Check out the codepen example: https://codepen.io/balke/pen/JpNNve $(window).scroll(function() { ...

Should padding be added to container-fluid in order to ensure consistent spacing on all devices from left to right?

After creating a webpage, I realized that it wasn't responsive. Now I am in the process of recreating the page and have a dilemma on whether to use container or container-fluid. Based on some blogs I've read, container-fluid seems like a better o ...

Guide to displaying a custom HTML tag

In this example: <?php $html='<p style="color:#eee;"> Test content 1. </p> <p dir="LTR" style="color:#f00;"> <span>Test content 2.</span> </p> <p style="color:#000;"> Test content 3. </p>' ?> ...

Customize the appearance of buttons and tabs located in the header section

Front end development is new to me and I'm trying to learn, but I've hit a roadblock. I have 4 components - 2 buttons and 2 tabs that I want to style in a header at the top of the page. Specifically, I want one button on the top left with padding ...

Using Javascript or Jquery, you can submit a form without the need for a button

I'm attempting to submit a form without using a button by invoking a JavaScript function and processing the form with JQUERY/PHP. My goal is for the form to be submitted silently on the backend without causing the page to reload. However, I keep encou ...

When the Chrome Dev Tools are activated, the responsive website malfunctions

As I work on designing a responsive website, I've encountered an issue with media queries. When I set the breakpoint to min-width: 320px in Chrome dev tools, all of my CSS styles disappear. The same problem occurs when I zoom the window size to 150%, ...

Can you suggest the best HTML5 structure for a multi-chapter novel?

In the process of creating a small HTML5 book with chapters and sections, I encountered a dilemma when it comes to structuring my documents like this: chapter1.html - introduction to chapter 1 chapter1section1.html - section 1.1 chapter1section2.ht ...