Display a particular div upon clicking a specific link, while concealing the other divs

As a beginner in the world of jQuery and coding, I'm encountering some difficulties that I need help with.

My goal is to have the 'Vlogging' link activated and show 'Details 1' when the page loads. Then, upon clicking on either 'Filmmaking' or 'Beme', 'Details 2 or 3 should be displayed while the previous one disappears.

I've managed to set everything up correctly so far, but I just need to figure out how to ensure that clicking on another link displays the corresponding 'Details' text.

Your assistance is greatly appreciated, and I currently have it all set up on a fiddle!

http://jsfiddle.net/t1huc43d/

Here is the code that requires adjustment:

$(function() {
   $("togglediv1").click(function() {
      $("#togglediv1").removeClass("display-start");
      $("li").removeClass("display");
      $(this).addClass("display");
   });
});

Answer №1

This piece of code is incredibly efficient and will undoubtedly save you a significant amount of time. By incorporating a custom attribute known as "data," the link is seamlessly connected to the tab that needs to be displayed. This coding gem simplifies the process of adding extra tabs, making your task easier and more streamlined. For detailed changes in the HTML and JavaScript, refer to the lower section.

<div id="wrap">

<ul id="divtoggle">
    <li><a class="link" data="1">Vlogging</a></li>
    <li><a class="link" data="2"> Filmmaking</a></li>
    <li><a class="link" data="3"> Beme</a></li>
</ul>


<div class="text">
    <div class="tab" data="1">Details 1</div>
    <div class="tab" data="2">Details 2</div>
    <div class="tab" data="3">Details 3</div>
</div>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$(function () {
  $(".link").click(function () {
    $(".active").removeClass("active");
    $(this).addClass("active");
    dataAttr = $(this).attr("data");
    $(".tab").hide();
    $(".tab[data="+dataAttr+"]").show();
  });
  $(".link:first").click();
});
</script>

Answer №2

$(function() {
   $("#togglediv1").click(function() {
      $("#one").removeClass("display");
      $("#one").addClass("display-start");
      $("#two").removeClass("display-start");
      $("#two").addClass("display");
      $("#three").removeClass("display-start");
      $("#three").addClass("display");
   });
});

$(function() {
   $("#togglediv2").click(function() {
      $("#one").removeClass("display-start");
      $("#one").addClass("display");
      $("#two").removeClass("display");
      $("#two").addClass("display-start");
      $("#three").addClass("display");
      $("#three").removeClass("display-start");
   });
});

...

Answer №3

Check out the updated jsfiddle here: http://jsfiddle.net/t1huc43d/3/

To better track which elements are clicked, I made use of the this keyword to identify the corresponding details.

Here's the revised javascript:

$(function() {
   $("li").click(function() {
      $("#togglediv1").removeClass("active-start");
      $("li").removeClass("active");
      $(this).addClass("active");
      let temp = $("#divtoggle").children();
            var index;

      for (let i = 0; i < temp.length; i++)
      {
        if (this == temp[i] )
        {
            index = i;
          break;
        }
      }

      $(".display-start").addClass("display");
      $(".display-start").removeClass("display-start");

          let text_children = $(".text").children()
      let the_child = text_children[index];
            $(text_children[index]).addClass("display-start");
      $(text_children[index]).removeClass("display");
   });
});

Answer №4

If you're looking for a simple and efficient way to achieve this using jQuery, here's what I recommend:

Start by assigning a unique id to each title element, incrementing them sequentially. Repeat the same process for the corresponding detail elements, like this:

<div id="wrap">
    <ul id="divtoggle">
        <li><a class="title" id="title-1">Vlogging</a></li>
        <li><a class="title" id="title-2"> Filmmaking</a></li>
        <li><a class="title" id="title-3"> Beme</a></li>
    </ul>

    <div class="text">
        <div class='display' id="detail-1">Details 1</div>
        <div class='display' id="detail-2">Details 2</div>
        <div class='display' id="detail-3">Details 3</div>
    </div>
</div>

Next, implement the jQuery functionality. Attach a click event handler to the title class. Upon clicking a title, extract its id and use it to display the related detail:

$(document).ready(function() {

   $(".title").click(function() {

     //*** get id
     var id = $(this).attr("id").split("-")[1];
     if (typeof id != "undefined") {

       //*** hide other descriptions and show yours
       $(".display").hide();
       $("#detail-" + id).show();
     }

   });

});

Check out the live demo here

Answer №5

Presenting a simplified version of your CSS setup. The code now toggles between an .active class for the top links and a .display class for the text divs. Upon clicking a link, the code utilizes the $.index() function to determine which text box should be displayed based on the index of the clicked link. For example, clicking on the 2nd link will reveal the content from the 2nd text box.

$(function() {
   $toggleLinks = $('#divtoggle a'),
   $displays = $('.text div');
   
   $toggleLinks.on('click', function(e) {
     e.preventDefault();
     $toggleLinks.removeClass('active');
     $(this).addClass('active');
     $displays.removeClass('display');
     $displays.eq($(this).closest('li').index()).addClass('display');
   });
});
li {
  color: grey;
  font: effra;
  font-weight: bold;
}

a:hover {
  color: #aaaaaa;
  cursor: pointer;
}

.active {
  color: orange;
}

.text div {
  display: none;
}

.text .display {
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrap">

  <ul id="divtoggle">
    <li><a class="active">Vlogging</a></li>
    <li><a>Filmmaking</a></li>
    <li><a>Beme</a></li>
  </ul>

  <div class="text">
    <div class='display'>Details 1</div>
    <div>Details 2</div>
    <div>Details 3</div>
  </div>

</div>

Answer №6

Retained as much of the original code while making necessary updates. View updated fiddle here.

I introduced a new custom attribute called data-controls to link each li element with its corresponding data div:

<li data-controls="one"><a id="togglediv1" class="active-start">Vlogging</a></li>
<li data-controls="two"><a id="togglediv2"> Filmmaking</a></li>
<li data-controls="three"><a id="togglediv3"> Beme</a></li>

Subsequently, I made adjustments to the JavaScript to handle the removal and addition of classes based on requirements.

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

What is the best way to compile TypeScript files without them being dependent on each other?

I have created a TypeScript class file with the following code: class SampleClass { public load(): void { console.log('loaded'); } } Now, I also have another TypeScript file which contains functions that need to utilize this class: // ...

How to make background image fade in with jQuery on hover

I want to create a row of menu buttons with transparent background-images that fade in on hover. Is it possible to achieve this effect using jQuery? Check out an example here! ...

Could a class method be accessed from outside a nested handler method in JavaScript?

I am trying to make an XMLHttpRequest to a server using JavaScript. In the handler function, I need to call a method from the surrounding class. Is there a way to achieve this? Understanding how this works in JavaScript can be confusing. I have experiment ...

Arranging the placement of the dropdown menu

I am struggling with positioning the items in my dropdown menu. The functionality itself is working perfectly, but the issue arises when it comes to aligning the dropped down items. Initially, I positioned them based on a smaller screen size, but when view ...

Investigating High Energy Usage on Vue.js Websites: Identifying the Root Causes

My Vue.js application has grown to be quite large with over 80 .vue components. Users have been complaining about their phone batteries draining quickly and Safari displaying a "This webpage is using significant energy..." warning. I have tried investigat ...

Using `v-if` with a Vuex getter

Currently, I am utilizing a vuex getters called isLoggedIn to verify whether a user is logged in or not. <div v-if="isLoggedIn" class="ml-2 py-2 group relative">...</div> data() { return { isLoggedIn: this.$store. ...

Transferring data from AJAX to PHP

I am currently developing a project in PHP. I have created an associative array that functions as a dictionary. Additionally, I have a string containing text with placeholders for keys from the array. My goal is to generate a new String where these key wor ...

Safari Browser does not currently offer support for MediaRecorder functionality

[Log] Webcam permission error Error: MediaRecorder is not supported I am facing an issue while trying to record audio. The Chrome browser allows audio recording without any problem, but Safari is throwing an error. global.audioStream = await navigator.m ...

Using a ForEach iteration to loop through a table in C# and jQuery

My generated table structure is as follows: <div class="row"> <div class="col-md-12"> <div id="calendar"></div> <table id="report" class="table"> <thead> <tr> <th> ...

Ways to navigate private property using the App Component in Angular 4

I have successfully implemented code in my app component to retrieve the current URL and display it in app.component.html. app.component.ts import { Component } from '@angular/core'; import { Router } from '@angular/router'; @Compone ...

What is the most effective way to eliminate just the last underscore in a string by employing the

I am currently facing an issue with table cell editing. I have the following code that removes all underscores (_) from a string if it contains "test_1_". However, my requirement is to only remove the last underscore and have the string appear as "test_1". ...

"The controller's $scope isn't being updated within the DIV following a routing change

My website contains ng-view partials that change based on routing updates in $routeProvider. anmSite.config(function($routeProvider, $locationProvider){ $locationProvider.html5Mode(true); $routeProvider //Home page route .when("/", { temp ...

Ensuring validity with Vuelidate for customizable fields

There's a form where fields are dynamically added on a click event. I want a validation error to appear when the field value is less than 9 digits after changing or blurring it. The issue is that since the fields are created dynamically with the same ...

Guide on making API calls in AngularJS using query strings

I am new to learning about AngularJS and recently came across a helpful article on connecting to an API and using its data in our app. The article specifically focuses on displaying weather information with AngularJS. The only downside is that the weather ...

Assign a value to an element based on a specific attribute value

I'm working with the following element <input type="text" size="4" name="nightly" value="-1"> My goal is to update the value to 15.9 specifically when name="nightly" Here's what I've attempted so far: document.getElementsByName(&ap ...

Is there a way to retrieve a particular object from the state and access one of its elements?

I have a component called Tweets.js: import React, {Component} from "react"; export default class Tweets extends Component { constructor(props) { super(props); this.state = {tweets: [], users: []}; } componentDi ...

Guide to selecting a specific year on a calendar using Selenium with JavaScript

While attempting to create a Selenium test using JavaScript, I encountered an issue with filling in calendar data through a dropdown menu: const {Builder, By, Key} = require('selenium-webdriver') const test2 = async () => { let driver = awa ...

How to position the figcaption within a card?

My card design features a masonry-style layout similar to what you can see here https://codepen.io/daiaiai/pen/VPXGZx I'm trying to add some additional information on top of the images using figcaptions, but my attempts with position:relative haven&a ...

Simulating server-side interactions in Node.js with TestCafe

I am currently working on a project where I need to figure out how to mock server-side requests. While I have successfully managed to mock client-side requests using request hooks, I am facing challenges when it comes to intercepting server-side requests ...

Customizing the step function of HTML5 input number with jQuery: A guide

Is there a way to modify the step value in HTML5 number inputs for my web application? I would like it to increment and decrement by 100 instead of 1. I attempted the following approach: $("#mynumberinput").keydown(function(e){ if (e.keyCode == 38) / ...