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

merge various useState functions for appending values to an array into a unified function in a React component

I am currently facing a challenge with code complexity. I have 8 arrays where I need to add items based on a button click. As of now, I have created 8 separate functions for each task. Is there a way to consolidate all these functions into one function tha ...

What is the best way to limit data loading when tabs are clicked in an AngularJS application?

My application has 2 tabs and all data is fetched from an API response. Initially, all data is loaded at once. The two tabs are: Tab 1 Tab 2 By default, Tab 1 is always active. I only want to load data for Tab 1 initially and not for Tab 2. When I c ...

Addressing a jquery.ajax relative path problem

I am a newcomer to this topic and I have been researching extensively online for more information. I would like some further insight into the following issue: I am attempting to retrieve a JSON file located one level down from the directory where `index.h ...

Optimizing CSS for printing with margins and overflow

After stumbling upon a helpful solution here, I wanted to print small cage cards in a neat format with some tweaks of my own. Currently, this is how it appears for me (Fiddle): /* CSS styles */ (styles modified here) * { -moz-box-sizing: border-b ...

Is it possible for Java Applets to interact with external sources with user consent?

My goal is to develop a platform where users can input external websites, and my application will modify the returned source before providing it back to the user. The challenge lies in the fact that HTML5 and flash sockets have limitations when it comes to ...

Guide on implementing automatic callbacks with AJAX

I am facing an issue with my index page that has one input tag and one division. There is an ajax function that retrieves data from the server, but I am encountering a problem. When I enter a single letter, it returns 3 records. Then, if I add another lett ...

Unable to import global CSS in React; however, local components are working fine

My React application is having trouble loading global CSS styles. While local components are able to access their own styled-components, the global CSS styles are not being applied across all components. I have tried various import paths and different file ...

Height adjustment for flexbox children

Can someone assist me with marking up a todo list? I am attempting to set the height of div.main-tasks equal to div.tasks so that the former fills the entire latter. Unfortunately, I am unsure how to achieve this. You can refer to the following image for c ...

Rearrange the entire div container by simply dragging and dropping it. (Shift the Pop-up Modal dialog box)

How can I make a Modal pop-up draggable and change the color of the "Ok" and "Cancel" buttons on hover using a single CSS class? .hidModal{ position: fixed; font-family: Arial, Helvetica, sans-serif; top: 0; right: 0; bottom: 0; ...

When receiving JSON and attempting to store the data in a variable, I encounter an issue where it returns the error message "undefined is not iterable (cannot read property Symbol

I'm currently integrating the Advice Slip API into my project. I am experiencing an issue when trying to store the JSON data in a variable like so: let advice; fetch("https://api.adviceslip.com/advice").then(response => response.json()). ...

Angular 2 template can randomly display elements by shuffling the object of objects

I am working with a collection of objects that have the following structure: https://i.stack.imgur.com/ej63v.png To display all images in my template, I am using Object.keys Within the component: this.objectKeys = Object.keys; In the template: <ul ...

Chrome: Box-shadow not visible on images with a background present

Recently, I have noticed an issue with the box-shadow not displaying on images with a background on my website. This problem started occurring in Chrome a few months ago, despite working perfectly fine around six months ago. To pinpoint the problem, I cre ...

What is the best way to eliminate the underline text decoration from a link element?

Take a look at this JS Bin. I want to change the link Project name in there. By default, it is underlined when hovered over. How can I remove that effect? I attempted using a class project-name: a:hover, a:focus .project-name { text-decoration: non ...

Reveal the inner workings of functions within the Vuex Plugin

I am currently working on setting up a Vuex plugin where I want to make the undo function accessible for use in my component's click events. // plugin.js const timeTravel = store => { // .. other things function undo () { store.commit(&a ...

extracting data from json using javascript

Here is the data in JSON format var testData = {text: '{"status":200}'}; I am attempting to extract the status using this code: console.log(testData.text.status); However, it returns undefined Could you please provide guidance on how to succ ...

What is the method to retrieve the string value from a JavaScript String object?

Is there a way to extend a method to the String prototype and manipulate the string value? I'm facing some difficulty in accessing the actual string value, as this, the current object context, seems to refer to the string object instead. String.pro ...

What could be causing my images to appear incomplete when using a background image with the style property?

Why are the images not appearing in full when I use the background-image URL style property? What is displayed on the page: https://i.sstatic.net/SwOGq.jpg body { background-image: url("../Bilder/ikkephotoshopped.jpg"), url(". ...

How can jQuery select an element by its id attribute by referencing the href attribute of a different element?

Whenever the user interacts with a div.nav element, jQuery switches its class to active. Presently, it applies display: block to all three of the div.content elements. I aim for jQuery to only apply the display: block property to the div.content elements t ...

What is the process for deploying a next.js application with a custom express backend to a VPS or Heroku platform?

Does anyone have advice on deploying a next.js application with a custom express backend to either a VPS or Heroku? ...

I need help with formatting a div to look like this

Looking to simplify my page by reducing the number of divs, wondering if this "tile" could be achieved without using one. Here's the example I have in mind: <a href="mks.html" class="big-tile big-tile-1"> <h1>town<br> libra ...