Solutions for concealing the current div when clicking on a new div that reveals a fresh one

Is there a way to hide the current div once you click on a new div that reveals another one? The code below toggles the display of the div, but what I am attempting to achieve is that when you click on a new item after clicking on the first one, the first item should hide. How can this be implemented?

function myFunction() {
  var x = document.getElementById("myDIV");
  if (x.style.display == "block") {
    x.style.display = "none";
  } else {
    x.style.display = "block";
  }
}

function myDIVS() {
  var x = document.getElementById("myDIVS");
  if (x.style.display == "block") {
    x.style.display = "none";
  } else {
    x.style.display = "block";
  }
}
<ul class="career-list">
  <li class="career-item"> <a href="#" onclick="myFunction()"> Foreman </a> </li>
  <li class="career-item"> <a href="#" onclick="myDIVS()"> Foreman </a> </li>
</ul>

<div class="col-md-8 Info-div" id="myDIV">
  <h3> SEND US YOUR RESUME </h3>
</div>
<div class="col-md-8 Info-div" id="myDIVS">
  <h3> SEND US YOUR RESUME TWO </h3>
</div>

Second Code (Doesn't close when clicking the same item)

HTML

<ul class="career-list">
  <li class="career-item"> <a href="javascript:void(0);" data-id="myDIV"> Foreman </a> </li>
  <li class="career-item"> <a href="javascript:void(0);" data-id="myDIVS"> Foreman </a> </li>
  <li class="career-item"> <a href="javascript:void(0);" data-id="myDIVSS"> Foreman </a> </li>
  <li class="career-item"> Foreman </li>
</ul>

Javascript

$(document).ready(function() {
  $('ul li').click(function() {
    $('.Info-div').hide();
    $('#' + $(this).find('a').data('id')).show();
  });
});

Answer №1

To conceal another division in the else section:

document.getElementById("myDIV").style.display = 'none';
document.getElementById("myDIVS").style.display = 'none';
function myFunction() {
    var x = document.getElementById("myDIV");
    var y = document.getElementById("myDIVS");
    if (x.style.display == "block") {
        x.style.display = "none";
    } else {
        x.style.display = "block";
        y.style.display = "none";
    }
}

function myDIVS() {
     var x = document.getElementById("myDIVS");
     var y = document.getElementById("myDIV");
     if (x.style.display == "block") {
         x.style.display = "none";
     } else {
         x.style.display = "block";
         y.style.display = "none";
     }
 }
<ul class="career-list">
  <li class="career-item"> <a href="#" onclick="myFunction()"> Foreman </a> </li>
  <li class="career-item"> <a href="#" onclick="myDIVS()"> Foreman </a> </li>
</ul>

<div class="col-md-8 Info-div" id="myDIV">
  <h3> SUBMIT YOUR RESUME HERE </h3>
</div>
<div class="col-md-8 Info-div" id="myDIVS">
  <h3> SUBMIT YOUR OTHER RESUME HERE </h3>
</div>

Answer №2

Writing functions for every <a> tag is not necessary...

  • Begin by gathering all the <a> tags in an array using querySelectorAll

  • Next, utilize javascript forEach to attach a click event to each <a>

  • Use a for loop to assign display:none to all the divs

  • Then, set the display:block to the div with the same id as the data-id on <a> click

  • To toggle the same div, employ an if condition and if it evaluates to true, exit the function using return

Stack Snippet

var anchor = document.querySelectorAll("a[data-id]");
var div = document.querySelectorAll(".Info-div");
anchor.forEach(function(elem) {
  elem.addEventListener('click', function() {
    var dataID = elem.getAttribute('data-id');
    var divID = document.getElementById(dataID);
    //to toggle the div
    if (divID.style.display === "block") {
      divID.style.display = "none";
      return;
    }
    //for all divs
    for (var i = 0; i < div.length; i++) {
      div[i].style.display = "none";
    }
    //for currentDiv
    divID.style.display = "block";
  })
})
.Info-div {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="career-list">
  <li class="career-item">
    <a href="javascript:void(0);" data-id="myDIV">Foreman</a>
  </li>
  <li class="career-item">
    <a href="javascript:void(0);" data-id="myDIVS"> Foreman </a>
  </li>
  <li class="career-item">
    <a href="javascript:void(0);" data-id="myDIVSS"> Foreman </a>
  </li>
</ul>

<div class="col-md-8 Info-div" id="myDIV">
  <h3> SEND US YOUR RESUME ONE</h3>
</div>
<div class="col-md-8 Info-div" id="myDIVS">
  <h3> SEND US YOUR RESUME TWO </h3>
</div>
<div class="col-md-8 Info-div" id="myDIVSS">
  <h3> SEND US YOUR RESUME THREE </h3>
</div>

If you prefer a jQuery solution, implement the use of toggle() to show/hide the specific div and hide() to hide other divs

Stack Snippet

$(".career-list li a").on("click", function() {
  var clickedItemId = "#" + $(this).data("id");
  if (!$(clickedItemId).is(":visible")) {
    $(".Info-div").hide();
  }
  $(clickedItemId).toggle();
})
.Info-div {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="career-list">
  <li class="career-item">
    <a href="javascript:void(0);" data-id="myDIV">Foreman</a>
  </li>
  <li class="career-item">
    <a href="javascript:void(0);" data-id="myDIVS"> Foreman </a>
  </li>
  <li class="career-item">
    <a href="javascript:void(0);" data-id="myDIVSS"> Foreman </a>
  </li>
</ul>

<div class="col-md-8 Info-div" id="myDIV">
  <h3> SEND US YOUR RESUME ONE</h3>
</div>
<div class="col-md-8 Info-div" id="myDIVS">
  <h3> SEND US YOUR RESUME TWO </h3>
</div>
<div class="col-md-8 Info-div" id="myDIVSS">
  <h3> SEND US YOUR RESUME THREE </h3>
</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

Is it possible to access the service and 'self' directly from the HTML template?

When working with Angular 6, one method to access component properties from a service is to pass 'self' to the service directly from the component. An example of this implementation is shown below: myComponent.ts public myButton; constructor(p ...

Activate text-entry fields after a button has been pressed on polymer 1.0

I am currently developing a project focused on creating a list of doctors using the Polymer 1.0 framework. Within the doctor-list, I have integrated a Vaadin grid called doctors-grid.html to display data sourced from a JSON file. Upon double-clicking on a ...

What could be causing this error to appear when using Next.js middleware?

The Issue at Hand Currently, I am in the process of setting up an authentication system using Next.js, Prisma, and NextAuth's Email Provider strategy. My goal is to implement Next.js middleware to redirect any requests that do not have a valid sessio ...

Tips for overcoming a script error within the body of a Next.js project

I encountered an error in my _document.js file when trying to add a script to the body of my document. Here is the specific error message that was returned: https://i.stack.imgur.com/QG5zb.png ./pages/_document.js Error: x Expected '}', got &a ...

CSS styling for the dropdown list in the content/option section

Can someone help me with a simple question I've been researching for hours without success? I'm trying to figure out how to style the content/option/popup of a dropdownlist on the right side of the 'open button' like in this screenshot ...

When the tooltip component is triggered in a React application, the cursor is automatically directed to

I have been working on creating an input field that allows users to enter time as input. Here's the code snippet I am using: <InputMask mask="99:99" onBlur={handleOnBlur} onChange={(e) => { const ...

Row within a table displaying link-like behavior

Here is the code I'm currently using: $('.table-striped tr').click( function() { var link = $(this).find('a').attr('href'); if(link != 'undefined') { window.location = link; } }).hover( func ...

Utilizing YouTube API information with AngularJS

I am currently working on a project where I need to fetch all the playlists from a specific channel and then display the name of each playlist in my AngularJS application. var myApp = angular.module('app', ['ngResource']); myApp.facto ...

How to utilize a Multidimensional JSON Array in a jQuery Function

I'm struggling with passing a PHP array to a jQuery function and accessing values from a multidimensional JSON array. When I try to retrieve the value of 'lat' using the code below, I receive an error stating Cannot read property 'lat&a ...

Display the checkbox as selected using AngularJS

I have already submitted a form with a checkbox value. Now, I am trying to display the checkbox as "checked" using AngularJS based on the value retrieved from the data source. Can someone guide me on how to achieve this? ...

The ultimate guide to personalizing group titles in Angular UI-Select

Is there a way in Angular ui-select to customize the group label? I want to make it larger than the selection items as shown in the image below. https://i.stack.imgur.com/ofcak.png The list is currently grouped by country, but how can I adjust the size o ...

Upon clicking the 'Add Image' button, TINYMCE dynamically incorporates an input

I am in search of creative solutions to address an issue I'm facing. Currently, I am utilizing TINYMCE to incorporate text into my webpage. However, I would like to enhance this functionality by having a feature that allows me to add an image along w ...

Personalizing Web Push Alerts (Google Chrome)

I successfully implemented a web push notification for Google Chrome using Google Project and Service Worker. One thing I'm curious about is how to customize or style the push notification. The plain message box doesn't quite cut it for me – I ...

JavaScript on the client side or the server side?

I am faced with a challenge on my report page where I need to filter customers based on specific criteria and highlight certain details if their registration date falls after a specified date, such as 1st January 2011. With around 800 records to showcase, ...

The horizontal overflow in the HTML code was unsuccessful

I stumbled upon an interesting issue where I applied a div with specific styling: overflow-x: scroll However, the outcome was not as expected. Instead of overflowing, the content simply started on a new line. Here is the source code for reference: & ...

Automatic Numeration in Jquery with Ordered Lists

I am in the process of using JQuery to automatically number an OL list. My goal is to create a list that looks like this: apple 1.1 green apple 1.2 red apple 1.3 red apple orange 2.1 orange juice 2.2 etc Please assist me in achieving this. $(&a ...

Leveraging the keyword 'this' within an object method in node's module.exports

My custom module: module.exports = { name: '', email: '', id: '', provider: '', logged_in: false, checkIfLoggedIn: function(req, res, next){ console.log(this); } }; I inclu ...

What is the best way to trigger an event using vue-chartjs?

I am using vue js to display a graph with chartjs. I have implemented an onClick function on the graph to emit an event in the parent component and retrieve data. However, the event is not working as expected. Can you help me identify the issue? Component ...

What's the most effective method for identifying a pattern within a string of text?

For the sake of honing my skills, I undertook a practice task to identify patterns of varying lengths within a specified string. How can this function be enhanced? What potential issues should I address in terms of optimization? function searchPattern(p ...

Tips for displaying a refresh indicator while making an ajax call for refreshing data:

I have successfully implemented jQuery code that refreshes a specific div every 10 seconds without reloading the entire page. However, during this refresh process, the user does not visually perceive any changes happening in the browser. While there are n ...