How can I implement a division animation with Javascript upon clicking a hyperlink?

I need help with animating a div when clicking on a link. Specifically, when clicking on the "About" link, the height of the div should change. Currently, the height is set to '0em' in the CSS file. I attempted to change the height using "document.getElementById('about-div').style.height = '';", but it resulted in a sudden jump instead of a smooth animation. I then tried the following code, but it doesn't seem to be working as expected:

CSS:

.about-div {position:absolute;top:100vh;left:0em;width:100vw;height:0em;z-index:10000;background:white;overflow:hidden;}

.open {
  -webkit-animation: open 1s ease-in 1 forwards;
  animation: open 1s ease-in 1 forwards;
}

.is-paused {
  -webkit-animation-play-state: paused;
  animation-play-state: paused;
}

@keyframes open {
  0%   {height:0em;}
  1%     {height:'';}
  100% {height:'';}
}

@-webkit-keyframes open {
  0%   {height:0em;}
  1%     {height:'';}
  100% {height:'';}
}

@keyframes close {
  0%   {height:'';}
  100% {height:0em;}
}

@-webkit-keyframes close {
  0%   {height:'';}
  100% {height:0em;}
}

HTML:

<a href="javascript:openAbout()">About</a>

<div class="about-div open is-paused">
   <p>Some Content</p>
</div>

...and the Javascript code:

function openAbout()  {
  <script>
    document.querySelector('.about-div').classList.remove('is-paused');
  </script>
}

Any suggestions on how to solve this issue?

Answer №1

Feel free to check out my fiddle.

One important thing to note is to take out the script tags from within your JavaScript function. Ensure that all JavaScript code is enclosed within the script tags as shown below.

<script>
function openAbout() {
    document.querySelector('.about-div').classList.remove('is-paused');
}
</script>

In addition, I find using animations to adjust height a bit complicated, so I opted for using transitions instead. You can view the demo below (I omitted the bottom positioning for better visibility, but you can re-add it as needed).

function openAbout() {
    document.querySelector('.about-div').classList.remove('is-paused');
}
body { background: #ddd; }
.about-div {
    position:absolute;
    left:0em;
    width:100vw;
    z-index:10000;
    background:white;
    overflow:hidden;
    transition: max-height 5s;
}
.open {
    max-height: 999px;
}
.is-paused {
    max-height: 0px;
}
<a href="#" onclick="openAbout()">About</a>

<div class="about-div open is-paused">
    <p>Some Content</p>
</div>

Answer №2

The script should be placed outside the function, not inside the function tags.

<script>
function showInfo() {
    document.querySelector('.info-div').classList.remove('hidden');
}
</script>

Answer №3

Initially:

The 'href' attribute is not meant for invoking functions. Most HTML elements come with an 'onclick' attribute for that purpose.

<a href="#" onclick="openAbout()">About</a>

Make sure to remove the '' characters as advised, so your code appears as follows:

function openAbout() {
    document.querySelector('.about div').classList.remove('is-paused');
}

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

Adjust the alignment of text on both ends of the HTML5 canvas

Is there an easier way to align text on both sides of a canvas element besides using CSS? The link below might provide some insight: https://github.com/nnnick/Chart.js/issues/114#issuecomment-18564527 I'm considering incorporating the text into the d ...

Setting elements relative to a div can be achieved by using CSS positioning properties

I'm currently learning HTML/CSS and facing a challenge in setting elements relative to a container. After reading about the differences between "relative" and "absolute" positioning, I understand that "relative" positions an element relative to where ...

Using AngularJS to extract data from a JSON feed that contains a namespace

Just diving into Angular and I'm loving it. Struggling with parsing a JSON feed that has namespaces, need some help: Here's an example from the JSON feed: "title": { "label": "Fuse" }, "im:name": { "label": "John Doe" }, "im:image": [ { ...

Issue: The login.component.html file failed to load

I attempted to utilize a custom-made HTML file with the templateUrl attribute in Angular2. Below is the content of my login.component.ts file: import {Component} from '@angular/core'; @Component({ selector: 'login' , template ...

Step-by-step guide on how to effectively send a NodeJS request and stream it into a separate response

Currently, I am in the process of developing an API to interact with a specific map service that requires the use of an API key. It is crucial for me to keep this API key private. To achieve this, I plan to make internal calls within my server's own A ...

Error encountered: "Jest error - TypeError: Unable to access property 'preventDefault' because it is undefined."

I encountered an issue while testing the function below, resulting in the error mentioned above. function toggleRecovery = e => { e.preventDefault() this.setState( { recovery: !this.state.recovery }, () => { ...

Generate JSON with a distinct structure

My goal is to send a JSON via POST request to an API in the following format: "answer" => { "name"=>"Test", "email"=>"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3d49584e497d49584e49135e52">[email  ...

add the AJAX response to the specified div element

I'm currently using an ajax call to retrieve movie data from the IMDb API for 'The Shawshank Redemption'. My goal is to display this data within the designated div element. <div id="movie-data"></div> Here's my current Jav ...

Utilize Javascript to access Django Rest Framework API and obtain a Token

I've successfully set up an API with Django Rest Framework that functions well when accessed through cURL, HTTPie, or the browsable API. The API utilizes token authentication, requiring initial credentials to obtain a token. To achieve this using HTTP ...

Struggling to integrate a JavaScript sdk with an Angular2 application due to missing dependencies

I've been struggling to incorporate the Magic: The Gathering SDK library into my Angular2 application. I've tried various methods, but nothing seems to work seamlessly. When I attempt to import the library using TypeScript like this: import { } ...

Using jQuery to dynamically insert variables into CSS styles

I am attempting to use jQuery 3 to modify the CSS of a class and change the background color. My first step is converting an rgba color code (properties.color) to a hexadecimal code, which is functioning correctly. Next, I try to change the background co ...

Creating a vertical scrollbar with CSS flexbox for columns set at 100% height in a row for FF, IE, and

I am currently working on an HTML application that needs to fit perfectly within a designated space without causing any page level scrollbars. I have utilized flexbox styles extensively to achieve this, but unfortunately, I am facing compatibility issues w ...

Having trouble getting jQuery autocomplete to recognize the JavaScript data file

Struggling to use a JQuery UI widget to call in a JS file containing string data. I keep getting 'no results found' with no console errors. It seems like I'm not referencing the file correctly, as my knowledge of jquery/js is limited. Any gu ...

The jQuery Ajax Error is consistently being triggered

I'm puzzled as to why my custom callback error function keeps getting triggered. When I remove this callback function, the success callback works just fine. Some sources online suggest that it could be an encoding issue, but I don't think that&a ...

When should vuex be used for storing data instead of relying on local component data?

Currently I am tackling a complex project that is built using Vue. Our team has opted to use Vuex as our state management system, however there are certain components where the data is not needed elsewhere. Should I follow convention and store this data ...

Merge two separate Vue applications into one cohesive application

I have developed two separate Vue apps independently from each other. User Interface Admin Interface Each app has its own routes, store, configs, etc. I came across this helpful comment here which discusses treating each app as a component within a mai ...

The ontrack listener for WebRTC peerConnection fails to fire

Primarily, the challenge I'm facing is unique from what I have come across in my research on "google". My setup involves using Spring Boot as a signaling server to establish connections between two different tabs of the browser or utilizing two peerCo ...

What is the proper way to connect an external Javascript file to an html document within a Play Framework project?

Below is the content of my scala.html file: @() <!DOCTYPE html> <html> <head> <title> Spin To Win </title> <link rel="stylesheet" media="screen" href="@routes.Assets.versioned("stylesheets/styles.css")" ...

What sets apart an anonymous function from the => notation in node.js?

I was exploring how to read a file using node.js. Previously, I would use this code snippet: fs.readFile('/etc/passwd', function(err, data) { if (err) throw err; console.log(data); }); Node.js’s official documentation showcases the follo ...

Sending reference variable from Angular input type=file

I am currently learning Angular and I have implemented a feature where a list of PDF files is displayed using an array called pdfs. In my template, these PDF files are parsed into "card" elements for better visualization. The issue arises when I attempt ...