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

Tips for concealing overlay when the cursor hovers

Can anyone help me with a code issue I'm having? I want to hide an overlay after mouse hover, but currently it remains active until I remove the mouse from the image. Here is the code: .upper {position: absolute; top: 50%; bottom: 0; left: 50%; tra ...

Effortlessly refresh a data object in Vue.js without relying on a function

I need assistance with the following: <Checkbox label="View" :initialState="data.something" @updateStatus="updateCheckbox" > </Checkbox> The variable data.something is a b ...

The session becomes obsolete when redirecting back to the previous page

When attempting to redirect using the http referrer after storing a value in Session in php, I noticed that the Session becomes null. Is there a method to maintain the session even when utilizing the http referrer? ...

Burger menu floating above container block element

I have set up a bootstrap container with the following styling: .container { margin-top: 12em; font-family: 'Amatic SC', cursive; border-bottom: 1px solid; border-color: #800000; } The purpose behind this is to have my navigatio ...

Generating modal pages on the fly

One thing that's been on my mind is creating modals for my page. Typically, I would include the HTML code for my modal directly in the page like this: <div class="my-modal"> <form action="/home/index"> <input type="text" class="txt- ...

Did I incorrectly associate the function with the button causing it to always be executed?

I am working on a PHP page, where I have some initial content followed by session initialization code: <?php session_start(); ?> The requirement is to display a disconnect button only if the user is logged in, indicated by the presence of $_SESS ...

Is it possible to update the text within a button when hovering over it in Angular?

I'm looking to update the text displayed inside a button when hovering over it, similar to the examples in these images. I have already implemented the active state, but now I just need to change the text content. <button type="submit" ...

Encountering a series of frustrating 404 errors when attempting to submit a React form multiple times

I've been working on developing a new forum using Express and React, but I'm facing challenges with saving form data to the database. Currently, my goal is to store topic titles in a MongoDB collection, with plans to expand to include message con ...

What is the best way to share specific links on LinkedIn articles?

When the LinkedIn button is clicked, the entire link does not get passed when the image is clicked. However, the Facebook link works perfectly fine. The LinkedIn button used to work before, has anything changed since then? <div align="center"> < ...

How can you quickly navigate to the top of the page before clicking on a link in the same window/tab?

Could someone assist me with a coding issue I am facing? I would like to be able to go to the top of the page when clicking on a link and have the link open in the same tab. I attempted to implement this functionality using the following code, however, I ...

What is the best way to display a button only during office hours from 9am to 5pm using React.js or JavaScript?

If I want a button to only be visible from 9am to 5pm, how can this be achieved where the button is hidden outside of that time frame? ...

Managing numerous range sliders in a Django form

My Request: I am looking to have multiple Range sliders (the number will change based on user selections) on a single page. When the sliders are moved, I want the value to be updated and displayed in a span element, as well as updating the model. The Issu ...

Determining the cursor location within a character in a div that is content editable using AngularJS

I am facing challenges with obtaining the cursor caret position within a contenteditable div. Currently, I am utilizing the following function : onBlurArea (field, ev) { ev.preventDefault() const editable = ev.target.childNodes[1].childNodes[2] ...

Creating dynamic buttons based on a list: A step-by-step guide

Is there a way to dynamically generate and display buttons based on the number of elements in a list? I currently have a hardcoded implementation, but sometimes my list only contains two elements (button 1 and button 2) so I don't need the additional ...

Troubleshooting CSS Display Problem on Chrome and Firefox

While working on the design of a website offline, everything seemed to be running smoothly. However, upon uploading it to the server, various issues began to arise. Initially, the file loaded correctly upon first visit. Unfortunately, after reloading the ...

The Backbone.js template does not automatically inherit attributes from the model

Hey there, I'm currently working on setting up a simple SPA using Backbone for testing purposes. However, when I try to render my view, the Underscore template doesn't seem to be picking up any attributes from my model. I've been trying to t ...

Hover Effect for Instagram Feed (Web Application)

Recently, I created an app using the Instagram API to bring Instagram images into a webapp. As part of this project, I have been diving into CSS to implement a rollover effect where a heart icon appears when users hover over an image. This heart will event ...

Ensure that the container div is filled by the image if the image exceeds the dimensions of

I have a footer menu with a background image that is larger than the div itself (2000x168). Even though I have set the width to 100%, it seems like the whole image isn't displaying. Instead, only a portion of it is visible, matching the size of my sc ...

Is it feasible to transform HTML into EditorJS JSON format?

Is there a way to display an HTML string in editorJS? Show me from the following code example: <h1>The video src attribute</h1><video width="320" height="240" controls src="movie.ogg">Yourbrowser does not su ...

Customizing CSS for Internet Explorer browsers

I am looking to target specific CSS styles for Internet Explorer only, without affecting other browsers. Initially, I tried using conditional comments: <!--[if lt IE 7 ]><html class="ie6 ie"> <![endif]--> <!--[if IE 7 ]><html cl ...