What is the reason for the malfunctioning of this button upon clicking?

Attempting to customize my personal website by making the sidebar width change when the sidebar button is clicked. I'm puzzled as to why it's not working as intended. I prefer to figure it out independently but any helpful tips would be appreciated. I'm still a beginner and don't want to get into complex changes that may be too advanced for my current level, as I've only been learning for a few weeks.

const sidebarBut = document.querySelector('.sideBarBut');
sidebarBut.addEventListener('click', animate);

function animate(){
    document.querySelector('.sidebar').style.width = "400px";
}
/*--------|--------*/
.sideBarBut {
    transform: scale(0.065);
    background-color: black;
    position: fixed;
    bottom: 742.5px;
    left: -235px;
    cursor: pointer;
}

.sideBarBut:hover {
    filter: brightness(80%);
}

.sidebarTitle {
    color: white;
    position: fixed;
    top: -50px; /*7px*/
    left: 95px;
    font-size: 28px;
    font-family: sans-serif;
    text-decoration: underline;
    text-underline-offset: 4px;
    text-decoration-thickness: 2px;
}

.sidebar {
    z-index: 1000;
    height: 100%;
    width: 0;
    position: fixed;
    top: 0;
    left: 0;
    background-color: black;
    border-right: 0px solid transparent;
}

.animate {
    animation-play-state: paused;
    animation-name: sidebarOpen;
    animation-duration: 1s;
    animation-fill-mode: forwards;
}

@keyframes sidebarOpen {
    0% {
        width: 0;
    }
    100% {
        width: 250px;
        border-right: 2px solid white;
    }
}

@keyframes sidebarClosed {
    0% {
        width: 250px;
    }
    100% {
        width: 0;
        border-right: 0px solid transparent;
    }
}

.projectLinks {
    width: 200px;
    position: fixed;
    top: 40px;
    left: -1000px; /*20px*/
    color: white;
    list-style: none;
    padding-left: 0;
}

.projects {
    text-decoration: none;
    color: inherit;
    font-size: 20px;
    font-family: sans-serif;
    line-height: 30px;
}

.projects:hover {
    color: rgb(200, 200, 200);
}
   <section>
            <div class="sidebar animate">
                <button type="button" class="sideBarBut"><img src="img/sidebar.png"></button>
                <span class="sidebarTitle">Projects</span>
                <ul class="projectLinks">
                    <li><a class="projects" href="projects/Tic Tac Toe Project copy/index.html">Tic Tac Toe Project</a></li>
                    <li><a class="projects" href="projects/color changer proj/index.html">Color Changer Project</a></li>
                </ul>
            </div>
        </section>
        <script src="sidebar.js"></script>

Answer №1

I noticed an error in your code. Instead of using animate, you should be using animate() instead. To avoid confusion, simplify

document.querySelector('.sidebar').style.width = "400px";
into something more understandable and functional. Here's an example:

function animate(){
let sidebar = document.querySelector('.sidebar');
sidebar.style.width = '480px';

Answer №2

Fixing the Error

After analyzing the issue, it seems that if you want the sidebar's width to smoothly transition from 0px to 400px upon clicking a button, you can resolve it by removing the "animate" class from the HTML element

<div class="sidebar animate">
or from the corresponding CSS block.

.animate {
    animation-play-state: paused;
    animation-name: sidebarOpen;
    animation-duration: 1s;
    animation-fill-mode: forwards;
}

By eliminating the "animate" class, the animation will be controlled by the styles directly assigned to the "sidebar" class, allowing your code to function as intended.

Other Suggestions for Improvement

Personally, I advocate for a concise approach in writing JS code, particularly when the logic is simple and not meant for reuse. In such cases, keeping the code succinct and integrated within the event listener can be more effective.

const sidebarBut = document.querySelector(".sideBarBut");

sidebarBut.addEventListener("click", () => {

  const sidebar = document.querySelector(".sidebar");
  sidebar.style.width = "400px";

});

If your aim is to trigger the animation upon button click, it may be more appropriate to modify the .animate class instead of the .sidebar class. Here is an adjusted version of the JS code to achieve this:

const sidebarBut = document.querySelector(".sideBarBut");

sidebarBut.addEventListener("click", animate);

function animate() {
  const sidebar = document.querySelector(".animate");
  sidebar.style.animationPlayState = "running";
}

Alternatively, you can dynamically add or remove the animate class to the sidebar element to exclusively control the animation for the sidebar without affecting other elements. This method offers precise management over when the animation should occur. Here's an example JS code snippet:

const sidebarBut = document.querySelector(".sideBarBut");

sidebarBut.addEventListener("click", () => {

  const sidebar = document.querySelector(".sidebar");
  sidebar.classList.add("animate");

});

Remember to ensure the .animate class has the necessary properties like

animation-play-state: initial || running;
for proper animation execution. By toggling this class selectively, you can have better control over the animation while managing the appearance of other elements on the page.

I hope these suggestions assist you in resolving the issue!

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 dynamically retrieving a CSS file for an HTML page

With multiple html pages containing the same navbar, I made the decision to place the navbar in its own file called navbar.html and use ajax with jquery.get() to dynamically load it onto each page. This prevents redundant code across all pages. Currently, ...

Excess padding in Internet Explorer 7 when a table is nested within a div tag

I have exhausted all potential solutions found on the internet and still cannot seem to solve this issue. Here is an example page that highlights the problem: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/l ...

Unable to logout with ExpressJS passport-local

After pasting the passport-local app into my own, I noticed something interesting: I managed to successfully log in users, but for some reason, I can't seem to get them logged out. app.get('/logout', function(req, res){ req.logout(); r ...

When the user clicks, show a designated search result in a separate container

I've been developing my Angular cocktail application, and I've reached a point where I can display all the cocktails in my database (only showing names). Now, I want to implement a feature where if I click on a specific cocktail, its full content ...

D3 Chart: What is the best way to insert images into a node?

Within the jsFiddle demo provided in this query, there is code displayed. I am curious about how I can assign images to each node. var graph = { "nodes":[ {"name":"1","rating":90,"id":2951}, ] } You can access my jsFiddle Demo through this ...

Tips for utilizing jQuery Ajax data action

I've been trying to understand how to effectively utilize the data parameter in a $.Ajax call. However, I am facing confusion regarding the 'action' part within the data call. Is it meant to trigger an action in a controller? If so, how can ...

Is your MJML column layout not stacking properly on mobile devices?

I've been struggling with a basic 2-column design created using the online editor at mjml.io. I can't seem to get it to stack on mobile devices. The email looks identical on desktop (Outlook 365 for PC) and mobile (Outlook for iOS on iPhone 13) ...

Encountering a problem with AJAX 'post' method while trying to post HTML elements

Incorporating AJAX to transmit the content of a div to my C# MVC controller. The structure of the AJAX post is as follows: $.ajax({ url: '/Home/SaveContent', type: 'POST', data: { model: modelDataJson, activ ...

Which five key JavaScript concepts should I grasp in order to excel as an AngularJS developer?

Coming from a background of server-side coding, I am delving into the world of AngularJS now. This means I need to have a solid grasp of JavaScript before diving in. If I don't have enough time to master JavaScript completely at the moment, what are ...

Detecting server errors in Nuxt.js to prevent page rendering crashes: A Vue guide

Unique Context This inquiry pertains to a previous question of mine, which can be found at this link: How to handle apollo client errors crashing page render in Nuxt?. However, I'm isolating the focus of this question solely on Nuxt (excluding apollo ...

Explore the hidden route of the input components

HTML: <div id="quiz"> <div id="question"> <p id="quiz-txt">What is your favorite color?</p> <ul id="quiz-opt"> <div id="ans"> <input type="checkbox" id="Red" value="Red" class="options"> ...

In order to extract a value from a different webpage, I must first make a request to that webpage and extract the XML value from it

I have been working on a project that requires displaying currency exchange rates. To achieve this, I initially tried using AngularJS to call another webpage for the exchange rate values, but I encountered issues as AngularJS can only make JSON/Rest URL ca ...

jQuery page hanging during DOM update with large data set

I am currently using a jQuery post method with the following structure: $.post("/SearchCompetitor/Index", { username: _username }, StartLoading()) .done(function (data) { if (data !== "UsernameErro ...

Is it the correct method to query names within JavaScript arrays?

I am looking to create a dynamic list view using React JS without relying on any pre-built components. My goal is to incorporate a basic search function that can find users by their names, and I need to address this issue... For example, I have drafted th ...

What steps can be taken once the browser has completed all rendering processes?

I have a large form that functions on older PCs. This form is a component of a thin client system and is implemented using AngularJS to create a Single Page Application. One of the tabs on the SPA includes this form. Upon opening the form, requests are se ...

What steps should I take to implement the features I want using Node.js?

My request is as follows: I need to pass an array of IDs to a function that will perform the following tasks: Check if a document exists in MongoDB. If it does, move on to the next ID. If not, create a document with the specified ID. If all the IDs ...

Receiving JSON in a C# web service: A step-by-step guide

I created a JSON string using jQuery and now I want to send it to a C# web API controller. Here is an example of the JSON object: {"Name":"","Type":"4","Meals":["2","3"],"Excludes":["Beef","Chicken"]} I attempted to send it with a URL structure like thi ...

Event for terminating a Cordova application

We are looking for a way to send a notification to the user's device when our app is closed rather than just paused. On iOS, this occurs when you double click the home button and swipe up on the app, while on Android it happens when you press the Men ...

Building/Deleting the Vue Component using text search

In my App.vue file, I have the following setup: <template> <div id="app"> <input type="text" v-model="term"> <hello-world text="Button 1" v-if="term === ''"></hello-world> <hello-world ...

The symbiotic partnership between JSF bean and the dynamic capabilities of HTML

As I develop my project in JSF using Primefaces 4.0 and a Tomcat 7 server, I encounter the need to retrieve an image from a MS SQL database and apply clickable areas on it. The coordinates for each area are also obtained from the database. Unfortunately, t ...