Show divs in identical position when clicking

There are 4 section divs that need to be displayed in the center of the page when clicked, but the last one appears further down. This is likely due to the flex box nature. What is the best way to ensure all sections appear at the exact same location?

Another JavaScript question - Is there a more efficient way to write this script? It seems cumbersome for its purpose and I'm looking for suggestions on how to simplify it.

function about() {
  var about = document.getElementById("about");
  var contact = document.getElementById("contact");
  var work = document.getElementById("work");
  var blog = document.getElementById("blog");
  if (about.style.visibility === "hidden") {
    about.style.visibility = "visible";
    contact.style.visibility = "hidden";
    work.style.visibility = "hidden";
    blog.style.visibility = "hidden";
  } else {
    about.style.visibility = "hidden";
  }
}
/* Remaining JavaScript functions go here */
* {
  margin: 0;
  padding: 0;
}

html {
  font-size: 100%;
}

body {
  height: 100vh;
  width: 100vw;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
/* CSS styling continues here */
<main>
  <section id="about" style="visibility: hidden;">
    <p>Developer, providing modern and responsive web development.</p>
  </section>
  <section id="contact" style="visibility: hidden;">
    <a href="mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="87eae6e4e3e2f1efc7e0eae6eeeba9e4e8ea">[email protected]</a>"><a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c0ada1a3a4a5b6a880a7ada1a9aceea3afad">[email protected]</a></a>
     /* HTML content continues here */
    </section>
</main>

Answer №1

Here is a rewritten version:

If you prefer not to take up unnecessary space, consider using display none/block instead of visibility.

Pure JavaScript

window.addEventListener("load",() => {

  document.querySelector("header").addEventListener("click",(e) => {
    const tgt = e.target;
    e.currentTarget.querySelector("a.active").classList.remove("active")
    tgt.classList.add("active")
    if (tgt.tagName === "A") {
      const id = tgt.href.split("#")[1];
      [...document.querySelectorAll("main section")].forEach(section => {
        section.classList.toggle("show",section.id === id)
      })
    }
  });
  document.querySelector(".active").click()
})
* {
  margin: 0;
  padding: 0;
}

html {
  font-size: 100%;
}

body {
  height: 100vh;
  width: 100vw;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

header {
  position: absolute;
  top: 5%;
  width: 100%;
  display: flex;
  justify-content: center;
}

header a {
  margin: 1rem;
}

main {
  width: 100vw;
  display: flex;
  flex-direction: column;
  align-items: center;
  align-items: center;
}

section {
  position: static;
  top: 50%;
}

@media (min-width: 640px) {
  body {
    font-size: 1rem;
  }
}

@media (min-width: 960px) {
  body {
    font-size: 1.2rem;
  }
}

@media (min-width: 1100px) {
  body {
    font-size: 1.5rem;
  }
}

section { display:none  }
a { text-decoration:none }
.active { text-decoration: underline }
.show { display:block }
<header>
<a href="#about" class="active">About</a>   <a href="#work">Work</a>  <a href="#blog">Blog</a>
</header>
<main>
  <section id="about" >
    <p>Developer, providing modern and responsive web development.</p>
  </section>
  <section id="contact">
    <a href="mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b5d8d4d6d1d0c3ddf5d2d8d4dcd99bd6dad8">[email protected]</a>"><a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f49995979091829cb49399959d98da979b99">[email protected]</a></a>
    <div id="social">
      <a href="https://instagram.com/machooper">I</a>
      <a href="https://twitter.com/mac_hooper">T</a>
      <a href="https://gitlab.com/macdevh">G</a>
    </div>
  </section>
  <section id="work">
    <div class="card">
      <img id="card-img" src="https://via.placeholder.com/150">
      <p id="card-title">Portfolio</p>
    </div>
  </section>
  <section id="blog">
    <div class="card">
      <img id="card-img" src="https://via.placeholder.com/150">
      <p id="card-title">Blog</p>
    </div>
  </section>
</main>

jQuery

$(function() {
  $("header").on("click", "a",function(e) {
    const $parent = $(this).closest("header");
    $("a",$parent).removeClass("active")
    $(this).addClass("active")
    const id = this.href.split("#")[1];
    $("main section").each(function()  {
        $(this).toggle(this.id === id)
    })
  });
  $(".active").click()
})
* {
  margin: 0;
  padding: 0;
}

html {
  font-size: 100%;
}

body {
  height: 100vh;
  width: 100vw;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

header {
  position: absolute;
  top: 5%;
  width: 100%;
  display: flex;
  justify-content: center;
}

header a {
  margin: 1rem;
}

main {
  width: 100vw;
  display: flex;
  flex-direction: column;
  align-items: center;
  align-items: center;
}

section {
  position: static;
  top: 50%;
}

@media (min-width: 640px) {
  body {
    font-size: 1rem;
  }
}

@media (min-width: 960px) {
  body {
    font-size: 1.2rem;
  }
}

@media (min-width: 1100px) {
  body {
    font-size: 1.5rem;
  }
}

section { display:none  }
a { text-decoration:none }
.active { text-decoration: underline }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<header>
<a href="#about" class="active">About</a>   <a href="#work">Work</a>  <a href="#blog">Blog</a>
</header>
<main>
  <section id="about" >
    <p>Developer, providing modern and responsive web development.</p>
  </section>
  <section id="contact">
    <a href="mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f49995979091829cb4919b95dd90838e93">[email protected]</a>"><a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f69b97959293809eb6919b97df808893">[email protected]</a></a>
    <div id="social">
      <a href="https://instagram.com/machooper">I</a>
      <a href="https://twitter.com/mac_hooper">T</a>
      <a href="https://gitlab.com/macdevh">G</a>
    </div>
  </section>
  <section id="work">
    <div class="card">
      <img id="card-img" src="https://via.placeholder.com/150">
      <p id="card-title">Portfolio</p>
    </div>
  </section>
  <section id="blog">
    <div class="card">
      <img id="card-img" src="https://via.placeholder.com/150">
      <p id="card-title">Blog</p>
    </div>
  </section>
</main>

Answer №2

For achieving these functionalities, my go-to tools are typically jQuery and custom HTML5 attributes.

In my CSS file, I define a class named "hide":

.hide { display: none !important; }

Within your HTML code, you can add an extra attribute (like data-toggleable) to sections:

<section id="work" class="hide" data-toggleable="true">

Then, in the JavaScript part, you can hide all elements with the data-toggleable attribute set to true using a single jQuery command:

$(this).find('[data-toggleable="true"]').addClass('hide');

This line targets all HTML elements with the data-toggleable attribute value as "true" and hides them. The advantage is that it won't redundantly apply the 'hide' class if it's already present on the element. Lastly, you can specifically display the section ID that needs to be visible:

$('#work').removeClass('hide');

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

Generating a JSON download link using AngularJS

I'm attempting to generate a link that will enable the download of a JSON file in this way Controller $scope.url = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(obj)); View <a href="url" download="download.json">downlo ...

I am looking to retrieve data from the Graph API JSON and gradually refine my search to achieve successful

I am looking to retrieve data from the "fb_page_categories" endpoint, which provides an array of categories a page can be categorized under. The format for this request is as follows: GET graph.facebook.com /fb_page_categories? Once this request is mad ...

Confirmation of numerous checkbox selections

I am facing a challenge with a form that contains multiple questions answered through checkboxes. I need to validate that at least one checkbox is selected in all the questions, otherwise an alert message should pop up. Is it possible to achieve this val ...

Ways to insert HTML text into an external webpage's div element without using an iframe

Is it possible to generate HTML and SVG code based on the position of a Subscriber on a web page or within a specific div? I would like to provide some JavaScript code that can be inserted inside a particular div on the page. Using an iframe is not ideal ...

Updating Angular JS views in real-time using database changes

I am currently in the process of building a social networking application using AngularJS. I have come across an issue regarding data binding. In my app, there is a timeline div where all the recent posts are displayed, along with a status updater at the t ...

Save information on users' Google accounts

Utilizing this resource, I successfully implemented a login feature on my website. The implementation includes functions such as onSignIn, signOut, and auth2.isSignedIn.get() to manage user authentication. Now, I am looking for a way to extract specific d ...

The hide and show buttons seem to be missing when utilizing the datatable API

For my current project, I referenced this example: https://datatables.net/extensions/responsive/examples/styling/bootstrap.html Despite trying various datatable API examples, I'm still unable to display the expand/collapse buttons. The required CSS a ...

What is the best method for designing a filtering menu with a "Narrow By" option?

Looking to create a sidebar menu similar to the functionality on mcmaster.com. This specific feature allows users to efficiently filter products and toggle through different options dynamically. Upon selecting the "metric" option, the entire page adjusts t ...

Searching patterns in Javascript code using regular expressions

I am dealing with two strings that contain image URLs: http://dfdkdlkdkldkldkldl.jpg (it is image src which starts with http and ends with an image) http://fflffllkfl Now I want to replace the "http://" with some text only on those URLs that are images. ...

Dealing with lag problems while feeding a massive dataset into the Autocomplete component of Material-UI

In my React project, I have integrated the Autocomplete component from Material-UI to enhance user experience. However, when attempting to pass a large dataset of 10,000 items to the Autocomplete component as a prop, there is a noticeable delay of approxim ...

"Encountering errors during npm installation due to a failed preinstall

Having identified security vulnerabilities for knexnest > knex > minimist, I encountered an issue where the minimist version did not update using npm audit fix or a simple npm update. Following the steps outlined in this informative article resolved the vu ...

Encountering an error while attempting to launch an AngularJS application on Node.js? Let's

Currently, I am in the process of learning Angular. Whenever I attempt to run my code, an error message pops up: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1f7a737a7c6b6d70715f2b312f3115">[email protected]< ...

Is there a way to transition an element from a fixed layout position to an absolute layout position through animation?

I am looking to create a dynamic animation effect for a button within a form. The goal is for the button to move to the center of the form, while simultaneously undergoing a horizontal flip using a scale transform. During the midpoint of this animation, I ...

Grouping items by a key in Vue and creating a chart to visualize similarities among those keys

I am working with an object that has the following structure; { SensorA: [ { id: 122, valueA: 345, "x-axis": 123344 }, { id: 123, valueA: 125, "x-axis": 123344 }, { id: 123, valueA: 185, "x-axis": 123344 }, { ...

Set HTML form elements to be shown in 'display only' mode, without any interactivity

In the process of developing a dynamic form builder, I am allowing users to add various blocks of content like buttons, text inputs, paragraphs of text, and images to a page. They can later publish this as a simple HTML form for their use. When it comes t ...

How can I position four DIV elements to the right of each other inside a parent DIV?

I am attempting to align 4 divs next to each other within a parent div at specific positions. The proposed div structure is as follows (referred to as the maindiv): <div> <div>1</div> <div>2</div> <div>3< ...

Incorporating ajax and jquery into html: Step-by-step guide

Previously, I inquired about implementing a show/hide functionality for a div that only renders when a specific link is clicked. (View the original question) Following some advice, I was provided with jQuery and AJAX code to achieve this: function unhide() ...

Implementing conditional button visibility in Angular based on user authorization levels

I've been experimenting with the following code snippet: <button ng-if="!isAuthenticated()" ng-click="deleteReview()">Delete</button> In my JavaScript, I have: $scope.isAuthenticated = function() { $http.get("api/user ...

Navigate the user to various pages in a Node.js application based on login status

Looking for guidance on a login system within my application? I need to redirect users based on their roles. Below is the code for the login controller, along with node.js snippets and the login HTML page. Any help would be appreciated. Login.html - < ...

Control Over Fluid Grid Layouts

Apologies for reaching out, as I usually try to figure things out on my own. However, after spending hours reading through countless pages with no success, I am at my wit's end. I'm struggling to create a 4-column 'home' landing page f ...