Tips for displaying or concealing a specific block by clicking on an element

I have a list-menu called .sidebar-menu and each li within this list has its own unique id. There is also a block called .services-info, containing several blocks with one of them supposed to appear when you click on an item in the .sidebar-menu that corresponds to it. The blocks within .services-info are assigned the .invisible class to hide them and there's also a .visible class set with display: block property.

How can I achieve the functionality where clicking on an item in the .sidebar-menu makes the corresponding block visible while hiding the unnecessary ones? For instance, if I click on "Business card site," the block with the .business-card class should appear in .services-info (highlighted in red in the image) while the previous block disappears. Similarly, clicking on "Online store" should reveal the block with the .market class and hide the rest.

Check out the website at ct03638.tmweb.ru

Here's the code on jsfiddle: jsfiddle.net/qhfs7jmb/

https://i.sstatic.net/uztCC.jpg

Answer №1

Implement an event listener on the sidebar <ul> to monitor clicks on the sidebar elements.

Upon clicking a sidebar element, the listener will extract the ID of the clicked element and utilize it to generate a query selector for selecting the necessary content <div>.

Subsequently, apply the invisible class to hide all content <div> elements, remove the 'visible' class, then add the 'visible' class to the required content <div>

Instead of simply altering the existing visible content block, it's advisable to conceal everything that is not essential based on previous experiences.

The code snippet must be placed within <script> tags and inserted at the bottom of your webpage.

    document.querySelector('ul.sidebar-menu').addEventListener('click',function(e){
        e.preventDefault();
        // The <a> element was clicked, but we need the ID from the enclosing <li> element
        let clickedId = e.target.closest('li').id;
        // Set all the content elements to invisible (saves trying to find the visible one)
        let contentDivs = document.querySelectorAll('div.services-info>div.content>div');
        contentDivs.forEach((el)=>{el.classList.remove('visible'); el.classList.add('invisible')});
        // Now, using the ID from the <li>, create a query selector to find the content <div>
        let targetSelector = 'div.services-info>div.content>div.'+clickedId;
        // Set that element visible
        document.querySelector(targetSelector).classList.add('visible');
    });
.invisible{
    display:  none;
}


.visible {
    display: block;
}
<section class="services" id="services">
            <div class="services-info-bg"></div>
            <div class="wrapper">
                <div class="content">
                    <div class="sidebar">
                        <h3>Our Services</h3>
                        <ul class="sidebar-menu">
                            <li id="business-card"><a href="#">Business Card Website</a></li>
                            <li id="landing"><a href="#">Landing Page</a></li>
                            <li id="market"><a href="#">Online Store</a></li>
                            <li id="corp"><a href="#">Corporate Site</a></li>
                            <li id="bitrix"><a href="#">1C Bitrix</a></li>
                            <li id="advertising"><a href="#">Contextual Advertising</a></li>
                            <li id="seo"><a href="#">SEO Optimization</a></li>
                            <li id="promotion"><a href="#">Social Media Promotion</a></li>
                            <li id="marketing"><a href="#">Content Marketing</a></li>
                        </ul>
                        <ul class="sidebar-nav">
                            <li></li>
                            <li></li>
                            <li></li>
                            <li></li>
                            <li></li>
                            <li></li>
                            <li></li>
                            <li></li>
                            <li></li>
                        </ul>
                    </div>
                    <div class="services-info">
                        <div class="content">
                            <div class="business-card invisible">Business Card Website</div>
                            <div class="landing invisible">Landing Page</div>
                            <div class="market">
                                <div class="services-info-title">
                                    The online store websites expertly created by "Inter-web" possess the functionality vital for successful online trade.
                                </div>
                                <p>What our work includes:</p>
                                <div class="services-info-block">
                                    <ul>
                                        <li>+ Technical task preparation</li>
                                        <li>+ Prototype development</li>
                                        <li>+ Layout design</li>
                                        <li>+ Design integration</li>
                                    </ul>
                                    <ul>
                                        <li>+ Writing unique texts</li>
                                        <li>+ Collecting semantics</li>
                                        <li>+ Testing and launching</li>
                                        <li>+ Web analytics integration</li>
                                    </ul>
                                </div>
                                <div class="services-info-footer">
                                    <a class="order" href="#">Place Order</a>
                                    <a href="#" class="details">Learn More &rarr;</a>
                                </div>
                            </div>
                           
                        </div>
                    </div>
                </div>
            </div>
        </section>

Answer №2

To display a section when a menu item is clicked, you can set an attribute with the selected menu item id on the body element and use CSS to show the element with the same class name as the id. The section that should be shown upon clicking a menu item must have the matching class name as the id of the <li> item:

const menu = document.querySelectorAll(".sidebar-menu li > a"),
      onClick = e =>
      {
        e.preventDefault();
        //get ID from <li> element and add it to the body "show" attribute
        document.body.setAttribute("show", e.target.parentNode.id);
      };

for(let i = 0; i < menu.length; i++)
  menu[i].addEventListener("click", onClick);
.services-info .content > div
{
  display: none;
}

body[show="business-card"] .business-card,
body[show="landing"] .landing,
body[show="market"] .market,
body[show="corp"] .corp,
body[show="bitrix"] .bitrix,
body[show="advertising"] .advertising,
body[show="seo"] .seo,
body[show="promotion"] .promotion,
body[show="marketing"] .marketing
{
  display: block;
}
<section class="services" id="services">
            <div class="services-info-bg"></div>
            <div class="wrapper">
                <div class="content">
                    <div class="sidebar">
                        <h3>Our Services</h3>
                        <ul class="sidebar-menu">
                            <li id="business-card"><a href="#">Business Card Site</a></li>
                            <li id="landing"><a href="#">Landing Page</a></li>
                            <li id="market"><a href="#">Online Store</a></li>
                            <li id="corp"><a href="#">Corporate Website</a></li>
                            <li id="bitrix"><a href="#">1C Bitrix</a></li>
                            <li id="advertising"><a href="#">Contextual Advertising</a></li>
                            <li id="seo"><a href="#">SEO Optimization</a></li>
                            <li id="promotion"><a href="#">Social Media Promotion</a></li>
                            <li id="marketing"><a href="#">Content Marketing</a></li>
                        </ul>
                        <ul class="sidebar-nav">
                            <li></li>
                            <li></li>
                            <li></li>
                            <li></li>
                            <li></li>
                            <li></li>
                            <li></li>
                            <li></li>
                            <li></li>
                        </ul>
                    </div>
                    <div class="services-info">
                        <div class="content">
                            <div class="business-card invisible">Business Card Site</div>
                            <div class="landing invisible">Landing Page</div>
                            <div class="market">
                                <div class="services-info-title">
                                    Websites for online stores created by experts at "Inter-web" possess the necessary functionality for successful online trading.
                                </div>
                                <p>What's included in our work:</p>
                                <div class="services-info-block">
                                    <ul>
                                        <li>+ Preparation of technical specifications</li>
                                        <li>+ Prototype development</li>
                                        <li>+ Layout implementation</li>
                                        <li>+ Design integration</li>
                                    </ul>
                                    <ul>
                                        <li>+ Writing unique texts</li>
                                        <li>+ Collecting semantics</li>
                                        <li>+ Testing and launch</li>
                                        <li>+ Web analytics integration</li>
                                    </ul>
                                </div>
                                <div class="services-info-footer">
                                    <a class="order" href="#">Place an Order</a>
                                    <a href="#" class="details">Learn More &rarr;</a>
                                </div>
                            </div>

                        </div>
                    </div>
                </div>
            </div>
        </section>

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

``I am experiencing difficulties with utilizing a personalized color scheme in React JS with Material

I'm currently working on customizing the color palette for my project, but I am only able to modify the main attribute and not others. My development environment is JavaScript with MUI, not Typescript. import './App.css'; import {BrowserRout ...

Limiting overflow:visible to input and select fields only

I'm currently facing an issue with a Lightning Web Component in Salesforce, however, I believe the root cause of this problem is not specific to this platform. Within my container div, I have row divs displaying select/combobox fields that need to ex ...

Choose specific GeoJSON elements using a mouse click - OpenLayers 3

I'm working with GeoJSON features that consist of multiple smaller features. When I hover over one of them, I'm hoping to have the entire layer selected, rather than just a portion of it. I'm not sure where to begin in order to make this ha ...

The disappearance of data stored in .data() in JQuery

I've encountered an issue with a function that creates an anchor, stores data, and appends it to a div element. var x = $("<a class='randomclass'></a>"); x.data('foo', 'bar'); console.log(x.data()); ... $("&l ...

Using dynamic forms with HABTM relationships

The application I'm developing involves Reports, Sections, and Writers. A Report has multiple Sections and Writers. Sections and Writers have a many-to-many relationship because a writer can write several sections, and a section can be written by mul ...

Display information when hovering over a tag

I'm working on adding a feature where hovering over a link will display a tooltip. For reference, here is an example: https://i.stack.imgur.com/K84Wf.png Are there any alternative JavaScript libraries that offer this functionality? (ideally similar ...

What is causing me to repeatedly encounter the 403 forbidden error?

I keep encountering a 403 forbidden error and I am unable to retrieve my JSON data at all. Here is an excerpt from my HTML source: <html> <head> <meta name="keywords" content="jquery,ui,easy,easyui,web"> <meta name="descriptio ...

When it comes to using the text() function, the statement encounters difficulty

let person = $(".tekst").text(); if (person=="XxX") { $("#discu").css("display", "none"); } alert(person); When I access my element with class .tekst and get its text using the text() function, it correctly displays as XxX, which is what I expected. ...

Re-activate external script following a language update in Next.js

In my Next.js 13 app, I have implemented a live chat support button that is dynamically added based on the language selection. The code for rendering the button looks like this: import Script from 'next/script'; ... <div id={`onlinehelp-button ...

The drop-down list was designed with a main button to activate it, but for some reason it is not functioning properly. Despite numerous attempts, the list simply will not display as intended

<html> <body> <button onclick="toggle()" class="nm" > main</button> <div class="cntnr" style="display : none;"> <ul class="cnkid"> <li class="cnkid"><a class="cnkid" ...

Tips for making a screen adapt to different monitor resolutions

Hello there! I've been working on a login screen using bootstrap 4, but I'm facing an issue with the layout. My concern is about adjusting the page layout so that the background image does not get cut off or distorted. Take a look at the image ...

Encoding multiple arrays in JSON using Zend PHP

I'm encountering an issue with the JSON functionality in Zend and JavaScript. Initially, I attempted to encode a single array that contained a certain number of models in the following manner: echo json_encode(Application_Model_Marker::getMarkers()) ...

Issue with Vue JS component on blade template page

Having trouble loading a Vue component into a Laravel blade file? Despite making changes, the content of my vue file isn't showing up in the blade file - even though there are no errors in the console. Any suggestions on how to resolve this issue woul ...

What is the best way to utilize the Material UI theme provider in a React application that includes a mix of class components and functional components?

I have been working on a React app that utilizes class components, but I have been transitioning to using functional components instead. I have replaced some class components with functional ones in the application. However, I have encountered an issue whe ...

What could be the reason for my inability to import styles.css from @rainbow-me/rainbowkit?

Currently, I am in the process of integrating the rainbowkit and wagmi libraries into an existing website that is built using web3. The integration works fine when I comment out the styles import, but unfortunately, it results in a rather unattractive appe ...

Updating components reactively in Vue.js when a click event occurs

I have a dilemma with my component that allows users to add or remove an item from their favorites. While the functionality works smoothly, there is no visual indication for the user to know whether the item has been added to favorites or not. Currently, I ...

When setting the height to auto in Dreamweaver for a background image, no content will be displayed

I have been searching through several questions on this platform today in the hopes of finding an answer to my query, but unfortunately, I haven't had any luck so far. That's why I'm turning to you all for help. My current goal is to transi ...

Having trouble getting Angular-UI-Select to work with a basic variable on $scope?

How can you reset an array with selected values so that the values can be reselected from the dropdown? I am working with a people array where the values are initially displayed in a select dropdown. When I choose certain names, they get transferred to th ...

Is it necessary to perform a specific action if the text within a div matches pre

I've been struggling to make this work properly. Even after removing the AJAX POST function, the issue persists. No alerts or any indication of what's going wrong. Check out the code on JSFiddle: HTML <div class="notification"> ...

JavaScript Tutorial: Adding Custom Metadata to PDFs

Does anyone know of a JavaScript package that can assist in adding custom metadata to a PDF file? ...