When clicking on the HTML div element, it will be appended to the application

Within my vertical menu, there are 5 items including web design and mobile app. When clicked on these items, they reveal their respective href attributes as shown below.

<div class="col-md-3">
        <ul class="nav nav-tabs nav-stacked">
            <li class="active">
            <a href="#web" onclick="webdesDiv()">Web Design and Development</a>   </li>
            <li><a href="#mob" onclick="mobileDiv()">Mobile Application Development</a></li>
            <li><a href="#ecom" onclick="ecommDiv()">eCommerce Solutions </a></li>
            <li><a href="#soft" onclick="softDiv()">Software Development</a></li>
            <li><a href="#supp" onclick="supportDiv()">Support & Maintenance</a></li>
        </ul>
    </div>


    <div class="col-md-9" style="display:none;" id="webdesc">
        <h4>View our Web Design page here</h4>
        <p>Discover a secure and interactive eCommerce storefront that boosts your product sales through cutting-edge coding techniques.</p>

    </div>
    <div class="col-md-9" style="display:none;" id="mobdesc">
        <h4>Explore our Mobile App section here</h4>
        <p>Experience a secure and interactive eCommerce storefront that enhances your product sales using top-tier coding methods in the industry.</p>
    </div>

An issue arises when clicking on options like ecommerce solutions, as the result gets appended to the current page instead of displaying only the specific description. How can I rectify this behavior? Any suggestions for fixing my code?

Below is my JavaScript code:

<script>
        function mobileDiv() 
        {
        document.getElementById('mobdesc').style.display = "block";
        }
        function webdesDiv() 
        {
        document.getElementById('webdesc').style.display = "block";
        }
</script>   

Answer №1

Consider this Approach :

<script>
    function showMobileDescription() 
    {
        document.getElementById('mobdesc').style.display = "block";
        document.getElementById('webdesc').style.display = "none";
    }
    function showWebDescription() 
    {
        document.getElementById('webdesc').style.display = "block";
        document.getElementById('mobdesc').style.display = "none";
    }
 </script>

Set one div to display:block and hide the others using display:none

Answer №2

To hide the blocks other than the one you clicked on, you can simply add display:none in your script. Here's an example:

function showOnlySelectedDivs() 
        {
          document.getElementById('selectedDiv').style.display = "block";
          document.getElementById('otherDiv1').style.display = "none";
          document.getElementById('otherDiv2').style.display = "none";
        }
<div class="col-md-3">  
        <ul class="nav nav-tabs nav-stacked">  
            <li class="active">  
            <a href="#" onclick="showOnlySelectedDivs()">Display Selected Div</a>   </li>     
        </ul>  
    </div>


    <div class="col-md-9" style="display:none;" id="selectedDiv">  
        <h4>This is the selected div content</h4>
        <p>Here is some information about the selected content.</p>

    </div>  
    <div class="col-md-9" style="display:none;" id="otherDiv1">  
        <h4>This is another hidden div</h4>
        <p>Some additional information goes here.</p>      
    </div>

Remember to apply display:none to all blocks except the one that is clicked.

A helpful tip: If you're using bootstrap, consider utilizing the built-in navigation component for better organization - http://getbootstrap.com/components/#nav.

Answer №3

To conceal the inactive division, follow these steps:

When coding in vanilla JavaScript, it is best to utilize hashes that serve a purpose rather than leading nowhere. The code snippet below seamlessly attaches event handlers to each link, utilizing their hash values to toggle the display of the corresponding div and to activate or deactivate the parent LI element.

window.onload = function() {
  var navLinks = document.querySelectorAll(".nav li a"); // fetch all nav links
  for (var i = 0; i < navLinks.length; i++) { // iterate over them
    navLinks[i].onclick = function() { // assign click handlers
      var activeLink = document.querySelector(".nav > li.active > a"),
        activeDivId = activeLink.hash.substring(1),
        activeLI = activeLink.parentNode;
      document.getElementById(activeDivId).style.display = "none"; // hide active div
      activeLI.className = ""; // make LI inactive
      activeDivId = this.hash.substring(1); // find new div ID 
      document.getElementById(activeDivId).style.display = "block"; // show it
      this.parentNode.className = "active"; // activate the LI
      return false; // cancel the click
    }
  }
  document.querySelector(".nav > li.active > a").click(); // show active link
}
.active {
  background-color: yellow
}
<div class="col-md-3">
  <ul class="nav nav-tabs nav-stacked">
    <li class="active"><a href="#webdesc">Web Design and Development</a>
      <div class="col-md-9" style="display:none;" id="webdesc">
        <h4>This is how the webdesign  page looks like</h4>
        <p>Secure and highly interactive eCommerce storefront that is designed to leverage your product sales is developed using the latest coding techniques in the industry.</p>
      </div>
    </li>
    <li><a href="#mobdesc">Mobile Application Development</a>
      <div class="col-md-9" style="display:none;" id="mobdesc">
        <h4>This is how the mobile app section page looks like</h4>
        <p>Secure and highly interactive eCommerce storefront that is designed to leverage your product sales is developed using the latest coding techniques in the industry.</p>
      </div>
    </li>
  </ul>
</div>

If jQuery is required:

$(function() {
  var $navLinks = $(".nav li a"); // get all nav links
  $navLinks.each(function() { // loop over them
    $(this).on("click", function(e) { // assign click handlers
      e.preventDefault();
      var $activeLink = $(".nav > li.active > a"),
          $activeLI = $activeLink.parent();
      $($activeLink.prop("hash")).hide(); // hide active div
      $activeLI.removeClass("active"); // make LI non-active
      $(this.hash).show(); // show it
      $(this).parent().addClass("active"); // activate the LI
    });
  });
  $(".nav > li.active > a").click(); // show active link
});

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 noticed that on my checkout sections, the toggle feature causes them to fold up and then immediately fold back down. This behavior should only happen

Is there a way to make my checkout sections fold up once instead of folding up and down when using toggle? I have created a test case in jsfiddle: (no styling done yet!) http://jsfiddle.net/Wd8Ty/ The code responsible for the behavior is located in AMLRW ...

I'm having trouble getting my placeholder to display correctly in react-native-datepicker. What could be the issue?

I'm struggling with displaying a placeholder correctly in the datepicker package I'm utilizing for react native... This is how I've configured the component: The _onDateChange function: const _onDateChange = (startTime) => { pickDa ...

What is the method for accessing the locale and messages of the IntlProvider within a component?

My index.js file includes the following code: import trFi from './translations/fi_FI.json'; import trSv from './translations/sv_SE.json'; ReactDOM.render( <IntlProvider locale={my_locale} messages={{ fi: trFi, sv: trSv } ...

Implementing an active class in a React render method

Working with UI Kit Components <ul className='uk-nav'> {languages.map(function (lang) { return ( <li style={lang === this.state.selectedLanguage ? {color: '#d0021b'} : n ...

tips for incorporating staticfiles processing into css files on django

Within my CSS stylesheets, I often have code snippets like the following: #defaultCountdown span.countdown_section { color:#fff; padding:7px 15px!important; margin-bottom:2px; font-weight:300; background:url(../img/bg-white.png); t ...

Optimal approach for blending release and debug code in a web application

Currently, I am in the process of developing a simple browser-based game for two players. While my main focus lies on the backend, I need to monitor the states of both players simultaneously. To achieve this without the hassle of working with two separate ...

Having trouble implementing a custom font family in a React Native Text component

Struggling to integrate a custom font into my react native app, I've gone through various solutions from SO and Google but nothing seems to work. I attempted to inform react native about the font by adding "rnpm": { "assets": [ "./assets/fonts/" ...

When attempting to render a React child, it is important to note that objects are not valid (found: [object Promise]). If your intention was to display a collection of children, it is advised

Instructions in "/pages/blog/index.js" : import BlogComponents from "../../components/Blog/blogComponents"; import { listBlogs } from "../../server/mongodb"; const index = async (props) => { console.log(props) return ( ...

Storing the entire HTML5 game on the local device for faster loading and

I'm in the process of developing a 2D HTML5 game and I'm looking to optimize asset storage by requesting each asset only once and then storing them in the user's filesystem. Currently, I'm utilizing localStorage for this purpose, but it ...

Try utilizing a variety of background hues for uib progressbars

Looking to incorporate the ui-bootstrap progressbar into my template in two different colors, background included. My initial idea was to stack two progress bars on top of each other, but it ended up looking too obvious and messy, especially in the corner ...

express.js creating dynamic URLs causing confusion

router.get('/:username', function(req, res, next) { res.render('dashboard'); }); router.get('/', function(req, res, next) { if(req.user) // this has value res.redirect('/'+req.user); }); I'm experi ...

Picking Layers on Google Maps with Three.js

I have incorporated the google-maps-api-threejs-layer library into my project from this source. Now, I am looking to implement a picking feature. Here is the modified code snippet: <!doctype html> <html> <head> <meta charset=&qu ...

Retrieving the nth character from a given string

How can I extract every 3rd character from a given string, such as the word GOOGLE? I have attempted to accomplish this using JavaScript, but I am unsure of what code to include after the 'if' statement. function getNthElements(string) { v ...

Tips for crafting a successful form success message within a bootstrap modal

RESOLVED After a long struggle, I finally managed to solve the issue using AJAX. However, in order to make it work, I had to remove WordPress and plan on re-uploading it in a separate directory later. Thankfully, this workaround does not affect my index p ...

Issue with Bootstrap 5 spinner's lack of motion in Firefox browser

Essentially, the issue is that a very simple Bootstrap 5 spinner does not spin in Firefox. It works fine in Chromium and all other Bootstrap components work well in Firefox as well. Here is the html code (identical to Bootstrap docs): <div class=&q ...

How can you change the alignment of items from vertical to horizontal using Bootstrap?

I'm looking to create a responsive layout similar to the design of duckduckgo.com. This page features a logo, the DuckDuckGo brand name in text form, and a search box. When I reduce the width of the browser window to nearly horizontal bar size, the th ...

What is the more effective option: utilizing the bootstrap offset feature or inserting an empty div?

<div class="col-xs-3"></div> <div class="col-xs-6 col-sm-6 col-md-6" style="min-width: 320px;"> </div> OR <div class="col-xs-6 col-md-offset-3 col-sm-offset-3 " style="min-width: 320px;">` </div> I would like to remo ...

Experience a seamless front/back DIV transition with a mouseover effect similar to the ones on USAT

Recently, I was tasked with creating a mouseover transition effect for a div similar to the one used on USAToday's website. The structure of the boxes on the site includes: <div class="asset"> <div class="front">'image and some t ...

Error: The addDoc() function in FireBase was encountered with invalid data, as it included an unsupported field value of undefined during the execution

As I attempt to input data into the firebase database, an error arises: 'FireBaseError: Function addDoc() called with invalid data. Unsupported field value: undefined'. The registration form requests 2 inputs - name and email. The function handle ...

"Declare the Status, Refresh the Page, and Specify the Web

After refreshing the page, I am facing an issue where the text corresponding to the current URL is not being displayed. My application consists of a Main component that renders a MiniDrawer component containing a NavLink, followed by routing with the Route ...