Utilize jQuery to display or toggle each element individually, ensuring that only one is visible on the screen at any given time

Here are some clickable links:

  1. About
  2. Portfolio
  3. Resume

Upon clicking 'About', I want the About section to appear while hiding the Portfolio and Resume sections (and vice versa)...

This is how my code is structured (relevant parts only):

HTML:

<section id="attCatch">
    <div class="container_12">
        <h1 class="attCatchText">The name's Jake. I like to make things.</h1>
        <nav id="topMainNav">
            <ul>
                <li><a href="#" title="#" class="aboutLink">About</a></li>
                <li><a href="#" title="#" class="portfolioLink">Portfolio</a></li>
                <li><a href="#" title="#" class="resumeLink">Resume</a></li>
            </ul>
        </nav>
    </div>
</section>
<section id="contentLoader">
    <div class="container_12">
    <section class="mn_pages">
        <article class="about_page">
            <h1>About stuff</h1>
        </article>

        <article class="portfolio_page">
            <h1>Portfolio stuff</h1>
        </article>

        <article class="resume_page">
            <h1>Resume stuff</h1>
        </article>
    </section>
    </div>
</section>

jQuery:

$(document).ready(function(){
     $('.mn_pages').hide();
     var i = 0;
     $('.topMainNav').each(function(){
         $(this).click(function(){ 
             $('.mn_pages:eq('+$(this).data('idf')+')').toggle('slow');
         });
         $(this).data('idf',i);
         i++;
    });
});

Although I expected my jQuery code to function correctly, it did not work as intended.

Link to JS fiddle: http://jsfiddle.net/MsYdJ/

Answer №1

Maybe you could do it like this:

TEST IT OUT ON FIDDLE

$(document).ready(function(){
   $('.main_content').find('section').hide(); // Hides sections on page load
   $('#mainNavigationLinks a').click(function(e){
      e.preventDefault();
      var section = $(this).text().toLowerCase();
      $('.main_content').find('section').hide(); // Hides currently opened section
      $('[class="'+section+'_section"]').show(); // Shows the clicked section
   });
});

Answer №2

If you want to hide the articles when the page loads, you can utilize this selector:

$('.main_pages > article').hide();

To show or hide the correct element, use the following code:

$('#navBar li').on('click', function(e) {
  e.preventDefault();
  $('.main_pages > article').hide().eq($(this).index()).show();
});

Take a look at this fiddle

Answer №3

Here is a unique approach that emphasizes the importance of keeping class/Id names constant while allowing flexibility in changing link names whenever needed-Check out the code snippet on this fiddle

$(document).ready(function () {
        $('#contentLoader .mn_pages').children().hide();
        $('#topMainNav li').each(function () {
            var targetClass=($(this).children().attr("class")).replace("Link","_page");
            $(this).bind("click",function(){
                $("#contentLoader .mn_pages").children().hide();
                $("#contentLoader .mn_pages ."+targetClass).show();
            });
        });
});

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

Are there ways to incorporate extra icons into NavMenu in Blazor 8?

I am exploring ways to incorporate extra icons into the NavMenu.razor component of my Blazor version 8 application. In the earlier version, Blazor 7, there was an iconset setup located in wwwroot/css/, which allowed me to include additional icons simply by ...

Load an external URL and load a file from the local directory using Electron

For an upcoming art exhibition, I have a video installation that consists of large videos (several GBs) and an online hosted web application. To conserve bandwidth during the exhibition, I am considering packaging the videos into an electron app. This way ...

Tips for assigning dynamic values to ng-model in AngularJS

When a user clicks, I am dynamically appending a div to the DOM. In order to capture the values entered by the user, I need to use ng-model for input fields. Since I cannot predict how many divs the user will append, I want to make the ng-model values dyna ...

Validating Doctype with jQuery

If the doctype is <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">, perform a specific action. Otherwise, perform a different action. Any suggestions on how to achieve this? Thank you. ...

The text within the button disappears when in the :before state

After implementing the code from this codepen, I decided to use the 3rd button design. .btn { line-height: 50px; height: 50px; text-align: center; width: 250px; cursor: pointer; } .btn-three { color: #FFF; transitio ...

Is Passport.js' serializeUser and deserializeUser functions never triggering?

Encountering an issue with Passport-local. It seems that neither serializeuser nor deserializeUser are being invoked. Upon researching similar problems on SO, it appears that many others facing this problem were not properly including bodyParser. Below is ...

Injecting resolve into Angular controller and encountering undefined value in logging operation

My setup involves the following: .state('posts', { url: '/posts/{id}', templateUrl: 'posts.html', controller: 'postsController as postsCtrl', resolve: { post: getSinglePostWrapper ...

Extract HTML href links that correspond to a specific string from a given list of strings using Beautiful Soup

I am currently working on extracting specific URLs from a webpage that contains a list of various links. My goal is to only retrieve the URLs that match certain strings in a predetermined list. These strings are a subset of the text found within the links ...

What are the best practices for effectively utilizing the nodejs Stream API?

I am currently working on an application that reads input from various sources, including files, sockets, and other parts of the same program that produce buffers or strings. While I have successfully handled sockets and files using node's Stream API ...

Error updating model: The `teams` model cannot be modified once it has been compiled

After spending hours researching on StackOverflow, I came across numerous articles related to my issue. However, I am still unable to identify what mistake I have made here. Here is my code: models/Team.js const mongoose = require('mongoose'); ...

the integration of shapes in three.js is malfunctioning

There has been a dynamic change in the path. The previous render function was as follows (where LENGTH, getPosition(), RADIUS, MATERIAL, and SCENE have already been set) var prevPosition = getPosition(); for(var i =0; i < LENGTH; i++) { drawPath(g ...

Tips on merging HTML node lists from various `getElement`s

Is there a way to combine HTML elements and extract values using array methods? I am struggling to merge them as a nodeList. I tried using get elements and array.unshift to consolidate elements into one variable. var elemsLabel = document.querySelecto ...

The following code automatically triggers the loading of a modal, which contains a checkbox upon loading

What is the best way to prevent the modal from showing again if the user checks the checkbox and clicks the close button? function popUp() { $("#LoadModal").show() var modal = document.getElementById('LoadModal') var closeBtn = document ...

How come sinon fails to identify my stub?

Imagine a scenario where I have a module that is exported in the following way: module.exports = mymodule; Now, in my testing file, I require this module and then proceed to stub it. var mymodule = require('./mymodule'); describe('Fetchi ...

Meteor - Utilizing If Statements in HTML Documents

Currently, I am utilizing an FS Collection named "MyUploads" for storing user-uploaded files. Within the HTML structure, there exists a submit button that needs to be displayed conditionally. The question at hand is: how can I create an if statement so tha ...

Ajax Post Response Redirect

I seem to be facing a major issue with redirecting my ajax response for reasons that are beyond my comprehension. Can anyone provide assistance? Below is the code snippet in question: (function($){ function processForm( e ){ $.ajax({ ...

The ultimate guide to disabling iframe scrolling on Internet Explorer 8

After extensively searching for a solution, I realized that most answers focused on removing scrollbars rather than completely preventing the page from scrolling. My issue involves embedding an index.php file in an iframe on my website. Within the index.ph ...

Does Eslint's no-restricted-imports rule only limit imports from the package's root directory?

For example, I'm looking to limit the usage of importing react-use, while still permitting react-use/lib/usePrevious. I attempted this: rules: { 'no-restricted-imports': [2, { patterns: [ 'react-use', ] }], }, As ...

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 ...

Cookie information will always be visible in the information box

When I click on my button, the page reloads and the box disappears. However, no cookie is set when I click, and it also does not check if a cookie is set or not. The current problem is: No cookie is added It does not check if the date today is more than ...