Unable to toggle visibility of div using Hide/Show function

I've noticed that the questions already posted do not solve my issue. I have a side menu bar displaying options and I want the content of the selected option to be displayed on the same page, while hiding the other div content. I have tried the following code, but it doesn't seem to work:

 $('a.common').click(function() {
   var id = $(this).attr('href');
   $(id).fadeIn('slow', function() {
     // Animation complete
   });
 });
<div id="container">

  <div id="canvas">

    <div id="nav">
      <h2 id="title">
<i class="fa fa-sitemap">
   </i> MENU</h2>
      <ul id="toggle">

        <li>
          <div class="active border">
            <a href="#div1" class="common">HOME</a>
          </div>
        </li>

        <li>
          <div>
            <span class="menu-icons  fa fa-user"></span> 
            <a href="#div2" class="common">ABOUT US</a>
          </div>
        </li>

        <li>
          <div>

            <a href="#div3" class="common">PORTFOLIO</a>
        </li>

        <li>
          <div>
            <a href="#">CONTACT</a>
          </div>
        </li>
      </ul>
      </div>
      <a href="#" class="toggle-nav" id="bars"><i class="fa fa-bars"></i></a>


      <div id="div1">TEST ONE</div>

      <div id="div2">TEST TWO</div>

      <div id="div3">TEST THREE</div>
    </div>
  </div>

Answer №1

The issue stemmed from using $('a.button') instead of $('a.common'). Additionally, it is advisable to apply a CSS rule to initially hide the divs. When introducing a new div with a fade-in effect, remember to hide the current one.

$('a.common').click(function() {
   var id = $(this).attr('href');
   $("#divs div").hide();
   $(id).fadeIn('slow', function() {
     // Animation complete
   });
 });
#divs div {display:none}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">

  <div id="canvas">

    <div id="nav">
      <h2 id="title">
<i class="fa fa-sitemap">
   </i> MENU</h2>
      <ul id="toggle">

        <li>
          <div class="active border">
            <a href="#div1" class="common">HOME</a>
          </div>
        </li>

        <li>
          <div>
            <span class="menu-icons  fa fa-user"></span> 
            <a href="#div2" class="common">ABOUT US</a>
          </div>
        </li>

        <li>
          <div>

            <a href="#div3" class="common">PORTFOLIO</a>
          </div>
        </li>

        <li>
          <div>
            <a href="#">CONTACT</a>
          </div>
        </li>
      </ul>
      </div>
      <a href="#" class="toggle-nav" id="bars"><i class="fa fa-bars"></i></a>


      <div id="divs">
        <div id="div1">TEST ONE</div>

        <div id="div2">TEST TWO</div>

        <div id="div3">TEST THREE</div>
      </div>
    </div>
  </div>

Answer №2

The issue lies within your jQuery selector:

//This line indicates that you are looking for an anchor tag with the class button
$('a.abutton').click(function() {})

//Instead, you should use:
$('a.common').click(function() {})

//This is because your anchor tags have the class 'common'

Answer №3

There were two issues that needed to be addressed:

  1. The <div> tag was not properly closed within the <li> element.
  2. The div was initially visible instead of being hidden, causing it to fade in upon clicking.

You can view the code on this fiddle: https://jsfiddle.net/2tkfq87o/

Answer №4

One issue is that there was an error in your html code as the <div> element was missing. Additionally, you forgot to call hide() on all the divs initially, which meant none of them were hidden. Having only fadeIn when all divs are visible doesn't make sense.

To fix this, first hide all the divs. Then trigger fadeIn on click while also hiding the currently displayed div.

$(document).ready(function() {

  $('a.common').click(function() {
    hideAllDivs();
    var id = $(this).attr('href');
    $(id).fadeIn('slow', function() {
      // Animation complete
    });
  });

  var hideAllDivs = function() {
    $('#div1').hide();
    $('#div2').hide();
    $('#div3').hide();
  }
  hideAllDivs();
  $('#div1').show();

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">

  <div id="canvas">

    <div id="nav">
      <h2 id="title">
<i class="fa fa-sitemap">
   </i> MENU</h2>
      <ul id="toggle">

        <li>
          <div class="active border">
            <a href="#div1" class="common">HOME</a>
          </div>
        </li>

        <li>
          <div>
            <span class="menu-icons  fa fa-user"></span> 
            <a href="#div2" class="common">ABOUT US</a>
          </div>
        </li>

        <li>
          <div>

            <a href="#div3" class="common">PORTFOLIO</a>
          </div>
        </li>

        <li>
          <div>
            <a href="#">CONTACT</a>
          </div>
        </li>
      </ul>
    </div>
    <a href="#" class="toggle-nav" id="bars"><i class="fa fa-bars"></i></a>


    <div id="div1">TEST ONE</div>

    <div id="div2">TEST TWO</div>

    <div id="div3">TEST THREE</div>
  </div>
</div>

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

Error Encountered in Three.js CSS3D Renderer: undefined function TypeError

I'm really struggling to make the CSS3d renderer work, and it seems like basic Javascript is causing some issues. Currently, I load all the Three.js libraries separately using Sid.js. When I try to add the CSS3DRenderer.js file through this method, I ...

What are the best strategies for mastering conditional promises in Angular?

I've been struggling with a problem in angularjs for several hours now. Here's the pseudo code I'm working with: doSomething(param){ var res; if(param = "ok"){ //perform some api calls with promises res = promise r ...

finding the node version in a code repository

Is it possible to determine the targeted node version (4 or 6) of a Node.js application by examining its code? I'm currently reviewing this: https://github.com/jorditost/node-postgres-restapi ...

Button in Angular CLI not triggering method on click event

After running the phpStorm Angular CLI project, I encountered an issue with adding a button and assigning a listener to it for the click event. Despite researching extensively and even referencing code from the official Angular documentation, the button do ...

Trouble with Styling React-Toastify in TypeScript: struggling to adjust z-index in Toast Container

Currently in the process of developing a React application utilizing TypeScript, I have incorporated the React-Toastify library to handle notifications. However, encountering some challenges with the styling of the ToastContainer component. Specifically, ...

What could be preventing this src tag from loading the image?

Here is the file structure of my react project Within navbar.js, I am encountering an issue where the brand image fails to load from the Assets/images directory. import '../../Assets/Css/Navbar.css'; import image from '../../Assets/Images/a ...

What is the process for including the posting date in the JSON format while using the Instagram

Struggling to incorporate the date into my JSON Instagram feed has been a challenge for me. For reference, here is a demonstration on JSFiddle: http://jsfiddle.net/galnova/p74jy3sk/ The following code snippet includes the commented-out section related to ...

Discovering all CSS files on a website by utilizing PHP

My goal is to locate all CSS files on a website, so I can later extract all image URLs from each of the CSS files on the server. I have attempted the following: $url_to_test = $_GET['url']; $file = file_get_contents($url_to_test); $doc = new DO ...

Does the AngularJS Controller disappear when the DOM element is "deleted"?

One challenge I encountered is regarding a directive that is connected to an angularjs controller, as shown below: <my-directive id="my-unique-directive" ng-controller="MyController"></my-directive> In the controller, at a certain point, I ne ...

Creating a Vue Directive in the form of an ES6 class: A step-by-step

Is it possible to make a Vue directive as an ES6 Class? I have been attempting to do so, but it doesn't seem to be working correctly. Here is my code snippet: import { DirectiveOptions } from 'vue'; interface WfmCarriageDirectiveModel { ...

Is it possible to connect to the Oculus Go controller using the GamePad API within the Oculus Browser

Exploring my three.js apps on the new Oculus Go has led me to question whether I can interact with the controller solely through the GamePad API supported by major browsers. Although Oculus documentation suggests using OVRManager in Unity or Unreal Bluepri ...

Efficiently managing desktop and mobile pages while implementing lazy loading in Angular

I am aiming to differentiate the desktop and mobile pages. The rationale is that the user experience flow for the desktop page involves "scrolling to section", while for the mobile page it entails "navigating to the next section." The issue at hand: Desk ...

php json with multiple dimensions

Unable to retrieve the deepest values from my json object, which contains an array of images listed as: { "imgs":[ { "Landscape":{ "2":"DSCF2719.jpg", "3":"DSCF2775.jpg", "4":"IMG_1586.jpg", ...

Unable to connect state to props when utilizing combineReducers

I'm currently working on integrating my state with a specific component using Redux. To achieve this, I have implemented two reducers and utilized combineReducers to merge them into a rootReducer before initializing my store. const rootReducer = comb ...

Adjusting an HTML table to fit within a designated space

I am currently in the process of constructing an HTML table that will showcase data retrieved from a MySQL database. This table will include functionalities to update or delete rows within the database. Here is a glimpse of my code: <table> <tr& ...

Automatically move to the latest message as soon as it is posted

After trying multiple codes and encountering issues, I am attempting to add my message in a textarea that will automatically scroll down. Even though I have my own codes, they don't seem to work properly. I also tried using the code provided Here. ED ...

Make sure to employ the require_once function when handling an ajax request

I am trying to implement require_once for my ajax request, but I keep encountering an error. Below is the code snippet that is causing the issue: var val = $('#customers option:selected').val(); $.post('base/chartval.php', {customer:v ...

Believing that members possess a certain role when they actually do not

const { Discord, MessageEmbed } = require("discord.js"); module.exports = { name: "ban", description: "bans user from guild", execute(client, message, cmd, args, Discord) { const member = message.mentions.u ...

Strategies for extracting special character codes from API data within a React functional component

I have been experimenting with a simple trivia API to improve my understanding of REACT. I have noticed that the question data is returning with special character codes, which is causing issues with react jsx. Can anyone suggest a method to easily convert ...

Is there a way to prevent a keydown event from causing interference with input fields in a form?

I have set up event listeners for the left and right arrow keys as shown below: $(document).keydown(function(e) { switch(e.which) { case 39: $("#next").trigger('click'); break; case 37: $("#prev").trigger('click ...