Using jQuery to show and hide elements on a webpage

One issue I'm facing is changing the content on a page depending on the clicked link. The problem arises when the displayed content for one link persists even after clicking another link, despite setting it to not display when another link is clicked. It seems that the "display: block" property overrides the "display: none" property.

While some suggest using .show() and .hide(), I feel that method might not work best for me as I need to add a class to the elements for potential animation in the future. Thanks for understanding!

jQuery(document).ready(function() {
  jQuery('#link_one').click(function() {
    jQuery('#about_us').addClass('hide');
    jQuery('#why_us').addClass('hide');
    jQuery('#our_prods').addClass('hide');
    jQuery('#accreditations').addClass('show');
  });

  jQuery('#link_two').click(function() {
    jQuery('#why_us').addClass('hide');
    jQuery('#accreditations').addClass('hide');
    jQuery('#our_prods').addClass('hide');
    jQuery('#about_us').addClass('show');
  });

  jQuery('#link_three').click(function() {
    jQuery('#about_us').addClass('hide');
    jQuery('#our_prods').addClass('hide');
    jQuery('#accreditations').addClass('hide');
    jQuery('#why_us').addClass('show');
  });

});
nav {
  width: 100%;
  text-align: center;
}

nav ul {
  list-style-type: none;
}

nav ul li {
  display: inline-block;
}

nav ul li a {
  font-size: 40px;
  margin: 0 10px;
}

p {
  font-size: 30px;
  font-weight: bold;
}

div {
  width: 100%;
  text-align: center;
}

.hide {
  display: none;
}

.show {
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav>
  <ul>
    <li><a id="link_one" href="#">link 1</a></li>
    <li><a id="link_two" href="#">link 2</a></li>
    <li><a id="link_three" href="#">link 4</a></li>
  </ul>
</nav>

<div id="about_us">
  <p>About Us Page - to be displayed by default</p>
</div>

<div id="accreditations">
  <p>Accreditations Page Content - Link 1</p>
</div>

<div id="our_prods">
  <p>Our products - Link 2</p>
</div>

<div id="why_us">
  <p>Why us content - link 3</p>
</div>

https://codepen.io/Reece_Dev/pen/gWdEoJ

Answer №1

Here are my recommendations:

HTML

<ul>
    <li><a href="#" id="link_1" class="link" data-target="accreditations">Link 1</a></li>
    <li><a href="#" id="link_2" class="link" data-target="our_prods">Link 2</a></li>
    <li><a href="#" id="link_3" class="link" data-target="why_us">Link 3</a></li>
</ul>

<div class="pageContainer" id="uniqueID">
    <!-- content -->
</div>

jQuery

$(document).ready(function()
{
    $('.link').on('click', function()
    {
        $('.pageContainer').addClass('hide');
        $('#'+ $(this).data('target')).removeClass('hide');
    });
});

When a element with the class .link is clicked, this script will hide all elements with the class .pageContainer and then reveal the one that matches the target ID (e.g. $('#why_us') if the why_us link was clicked).

You can use data attributes to attach extra information to HTML elements. Using .data() retrieves an array of all data tags on the element, while .data('string') fetches a specific data tag based on the string.

https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/data-*

Answer №2

There seems to be an issue with your current code where the toggling of the hide and show classes is not working correctly.

To simplify, you can utilize jQuery's built-in .hide() and .show() methods instead of constantly adding and removing classes:

$(document).ready(function() {
  $('#link_one').click(function() {
    $('#about_us').hide();
    $('#why_us').hide();
    $('#our_prods').hide();
    $('#accreditations').show();
  });
  $('#link_two').click(function() {
    $('#why_us').hide();
    $('#accreditations').hide();
    $('#our_prods').hide();
    $('#about_us').show();
  });
  $('#link_three').click(function() {
    $('#about_us').hide();
    $('#our_prods').hide();
    $('#accreditations').hide();
    $('#why_us').show();
  });

});

Check out a demo below:

$(document).ready(function() {
  $('#link_one').click(function() {
    $('#about_us').hide();
    $('#why_us').hide();
    $('#our_prods').hide();
    $('#accreditations').show();
  });

  $('#link_two').click(function() {
    $('#why_us').hide();
    $('#accreditations').hide();
    $('#our_prods').hide();
    $('#about_us').show();
  });

  $('#link_three').click(function() {
    $('#about_us').hide();
    $('#our_prods').hide();
    $('#accreditations').hide();
    $('#why_us').show();
  });

});
nav {
  width: 100%;
  text-align: center;
}

nav ul {
  list-style-type: none;
}

nav ul li {
  display: inline-block;
}

nav ul li a {
  font-size: 40px;
  margin: 0 10px;
}

p {
  font-size: 30px;
  font-weight: bold;
}

div {
  width: 100%;
  text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav>
  <ul>
    <li><a id="link_one" href="#">link 1</a></li>
    <li><a id="link_two" href="#">link 2</a></li>
    <li><a id="link_three" href="#">link 4</a></li>
  </ul>
</nav>

<div id="about_us">
  <p>About Us Page - to be displayed by default</p>
</div>

<div id="accreditations">
  <p>Accreditations Page Content - Link 1</p>
</div>

<div id="our_prods">
  <p>Our products - Link 2</p>
</div>

<div id="why_us">
  <p>Why us content - link 3</p>
</div>

Answer №3

Utilize the jQuery show and hide functions instead of adding a hide class. This is because when you add a hide class to an element that already has a show class, the display block will take precedence over display none. Here's how you can use it:

jQuery('#link_one').click(function() {
    jQuery('#about_us').hide();
    jQuery('#why_us').hide();
    jQuery('#our_prods').hide();
    jQuery('#accreditations').show();
});

jQuery('#link_two').click(function() {
    jQuery('#why_us').hide();
    jQuery('#accreditations').hide();
    jQuery('#our_prods').hide();
    jQuery('#about_us').show();
});

jQuery('#link_three').click(function() {
    jQuery('#about_us').hide();
    jQuery('#our_prods').hide();
    jQuery('#accreditations').hide();
    jQuery('#why_us').show();
});

Answer №4

The issue lies in the fact that you are not removing the class after clicking a link, causing both the hide and show classes to be present simultaneously. This results in the show class taking precedence over the hide class due to its order in the CSS.

To address this problem, simply add .removeClass('show') at the end of your modifications. For example:

jQuery('#our_prods').addClass('hide').removeClass('show');

Alternatively, you can use the jQuery methods show() and hide() without the need to toggle classes. This simplifies the process, as shown below:

jQuery('#link_two').click(function() {
  jQuery('#why_us').hide();
  jQuery('#accreditations').hide();
  jQuery('#our_prods').hide();
  jQuery('#about_us').show();
});

Answer №5

I have identified an issue where the class 'show' is being removed instead of hiding the content.

A more suitable approach would be to utilize jQuery hide and show functions for this purpose.

The revised script looks like this:

<script type="text/javascript">
    jQuery(document).ready(function() {
      jQuery('#link_one').click(function() {
        jQuery('.content').hide()
        jQuery('#accreditations').show()
      });

      jQuery('#link_two').click(function() {
            jQuery('.content').hide()
        jQuery('#our_prods').show()
      });

      jQuery('#link_three').click(function() {
            jQuery('.content').hide()
        jQuery('#why_us').show()
      });

});
</script>

Additionally, a class named 'content' has been added to the page containers.

<nav>
  <ul>
    <li><a id="link_one" href="#">link 1</a></li>
    <li><a id="link_two" href="#">link 2</a></li>
    <li><a id="link_three" href="#">link 4</a></li>
  </ul>
</nav>

<div id="about_us" class="content show">
  <p>About Us Page - to be displayed by default</p>
</div>

<div id="accreditations" class="content">
  <p>Accreditations Page Content - Link 1</p>
</div>

<div id="our_prods" class="content">
  <p>Our products - Link 2</p>
</div>

<div id="why_us" class="content">
  <p>Why us content - link 3</p>
</div>

The updated CSS styling:

<style type="text/css>

    nav {
  width: 100%;
  text-align: center;
}

nav ul {
  list-style-type: none;
}

nav ul li {
  display: inline-block;
}

nav ul li a {
  font-size: 40px;
  margin: 0 10px;
}

p {
  font-size: 30px;
  font-weight: bold;
}

div {
  width: 100%;
  text-align: center;
}
.content{
    display: none;
}
.show{
    display: block;
}
</style>

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

Obtain Jsonp Callback and data from a WCF Service

Thank you for all your amazing assistance thus far! I have been making great strides with my project. However, I've hit another roadblock that I can't seem to overcome. The function in my service Interface appears as follows: <OperationC ...

Invoking a C# function from JavaScript

I need to implement a way to invoke the method GetAccount from my controller AccountController.cs within my JavaScript factory LoginFactory.js. Here is an example of what I am trying to achieve: AccountController.cs: public Account GetAccount(string userN ...

Positioning a button on the side of the screen while a hidden side panel is open

I am attempting to create an animation using a side panel that will slide into view when a button is clicked. Here is how it appears when the page loads: When the user clicks on one of the buttons, the notes panel will become visible like this: This is ...

Steps for implementing a reset button in a JavaScript slot machine game

I need assistance with implementing a reset button for my slot machine game prototype written in JS. I attempted to create a playAgain function to restart the game by calling the main game function, but it's not working as expected. Do I need to pass ...

"Revolutionize real-time data updates with Node.js, Redis, and Socket

Greetings! I am currently working on a project for my school that involves creating a "Twitter clone." My goal is to incorporate a publish subscribe pattern in order to facilitate real-time updates. One key feature users will have access to is the abili ...

Error: ajax is not defined and needs to be declared (repeated twice)

Currently, I have a form that requires processing using Ajax. <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script> <div class="column1"> <form class="form box" action="javascript:networkCheck();" ...

Removing a data entry from a PHP-generated MySQL table

In the process of developing a system, I have encountered a need to display database records in an HTML table. The functionality for creating the HTML table and retrieving data is working as expected. However, I am facing an issue with adding a column cont ...

Positioning a fixed div within a responsive div using AngularJS and Bootstrap

I'm currently working on a page layout that consists of a fixed sidebar on the left side and a main container taking up the rest of the page on the right. Inside this right-side container, which is a div, there are 2 elements. <div class="col-sm-1 ...

The button event is unresponsive within the Bootstrap modal

I've been attempting to capture the button click event within a modal, but unfortunately, it's not functioning as expected. Am I overlooking something crucial? Below is the header section of my HTML file, which is built using Django. {% load st ...

Determining which data is retrieved from a database based on a specific field using Sequelize and MySQL

I'm looking to retrieve the most recent records from a database, organized by category. My goal is to fetch 20 records, with 5 of the latest posts in each category. I want to ensure that the result consists of 20 total records, evenly distributed amon ...

What is the best way to retrieve the parent element in jQuery when you already have the child element selected

I am working with jQuery Mobile, which automatically generates a lot of the DOM structure. The challenge I am facing is removing radio buttons without having an id for the parent div due to the HTML construction in jQuery Mobile. While I can easily targe ...

How to Customize Password Input Fields in HTML

My input field is set to password type, allowing only a six-digit number: <fieldset> <label for="password-input">Enter New Pin</label> <input type="password" name="password" id="password-input" inputmode="numeric" minlength="6" ...

What is the best way to send a populated custom class from JavaScript to a .NET MVC app using AJAX?

I am working with a .NET class in C# called BusinessModel: public class BusinessModel { public string BlobName { get; set; } public string NewName { get; set; } } In my MVC Ajax Controller, I have an action called DoBusiness: [HttpPost] public A ...

Upon clicking a link, the webpage will automatically scroll to a specific point

As I work on creating my website, I have come across a specific need: I currently have a menubar with a dropdown menu. Inside this dropdown, there are 4 different options. These options are all located on the same page. What I would like to achieve is tha ...

The content within a select tag is experiencing vertical misalignment

The select tag on my page is behaving oddly - when there is a value in it, it is aligned to the bottom vertically. Upon inspecting the CSS, I noticed that the only styles applied are font size and type. Strangely, removing the doctype from the page resol ...

Skip ahead button for fast forwarding html5 video

One of the features in my video player is a skip button that allows users to jump to the end of the video. Below is the HTML code for the video player: <video id="video1" style="height: 100%" class="video-js vjs-default-skin" controls muted autoplay=" ...

Scroll the content of a div to the bottom using JavaScript

I'm facing a situation with my code: function scrollme(){ dh=document.body.scrollHeight ch=document.body.clientHeight if(dh>ch){ moveme=dh-ch window.scrollTo(0,moveme) } } However, I am looking for a way to make it scroll only within a specific d ...

What steps should I take to create a plugin for a library if defining it as a peerDependency does not provide a specific implementation for me to work with?

Requirements for My Plugin: I'm currently in the process of developing a new plugin that is dependent on popularLibrary.js. Here are the key points about my plugin: It will not function properly if popularLibrary.js is missing. It is designed to wo ...

Arrange search results using $in array parameter in MongoDB

My challenge involves managing two collections: users and items. Within the user.profile.savedItems array, items are saved in the following format: {"itemId" : "yHud5CWpdPaEc6bdc", "added" : ISODate("2014-09-12T22:28:11.738Z")} My goal is to retrieve ...

What could be causing this ajax function to fail?

I referred to a solution in response to this question: My objective is to execute a query on the database when a user clicks on a specific table row, enabling me to retrieve and display their information. Below is the piece of code I am using: AJAX: $( ...