JavaScript function that adjusts the top position when toggling

When the user clicks on a div, it expands or closes. I also want to adjust the top position of another fixed div based on the state of the original div.

For instance: If the original div is expanded, I want the second div to have top:10px

If the original div is closed, I want the second div to have top:0

Below is the current toggle function for expanding or closing the div:

<a href="#" class="toggle" onclick="dropDownMSG(); this.parentNode.classList.toggle('open');return false;">
                    <img src="/Static/images/header-logo-top.png" alt="Informa logo"/>
                </a>

Then below I have:

function dropDownMSG() {
         document.getElementById("mySidenav").style.top = "10";
    }

However, this only sets top:10px on click. So when toggled again to close the div, the top does not reset to 0.

I need a way to specify:

if toggle is open then

document.getElementById("mySidenav").style.top = "10";

Else

document.getElementById("mySidenav").style.top = "0";

Answer №1

To determine the current top value, you can check it within an if-else block and update it accordingly.

function dropDownMSG() {
    const element = document.getElementById("mySidenav");
    if (element.style.top === '10') {
        element.style.top = '0';
    } else {
        element.style.top = '10';
    }
}

For improved performance, I recommend utilizing classes instead.

function dropDownMSG() {
    const element = document.getElementById("mySidenav");

    if (element.className.indexOf('expand') === -1) {
        element.className += 'expand';
    } else {
        element.className = element.className.replace('expand', '');
    }
}

Remember to add a CSS class:

.expand{top:10px;}

Answer №2

To assign the state, utilize HTML data-attribute and then adjust it in your script when clicked.

HTML

<a href="#" class="toggle" onclick="toggleState(this)">
   <img src="/Static/images/header-logo-top.png" alt="Informa logo"/>
 </a>

CSS

function toggleState(elem){
    if(elem.dataset.state === "open"){
      elem.dataset.state = "close";
      document.getElementById("mySidenav").style.top = "10px";
    }
    else{
      elem.dataset.state = "open";
      document.getElementById("mySidenav").style.top = "0";
    }
  }

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

The updates made to data in Vue.js are not reflecting on the screen

<template> <div class="parent"> <div class="container"> <h1 class="start" @click="start_timer"> {{ timerText }} </h1> </div ...

Exploring Request Data in Node.js: A Guide

A Node.js route has been set up to send back text and log the request: app.post('/registerUser', function (req, res) { res.send('Hello World post!') console.log(req); }) The route is then accessed using curl like this: curl --dat ...

Add owl carousel to your npm project in any way you see fit

After struggling for a while, I finally wanted to implement owl-carousel, but couldn't figure out how to connect it using npm and webpack. The official NPM website states: Add jQuery via the "webpack.ProvidePlugin" to your webpack configuration: ...

In vue.js, when utilizing the select all method for checkboxes, it is important to ensure that disabled checkboxes are not

I am working on a project where I have a table containing a list of checkboxes. When I click on the select all function, it selects all checkboxes including the disabled ones. However, I need to exclude the disabled checkboxes from being selected. ...

Automatically increase the dates in two cells once they have passed

Summary: Although I'm not a programmer, I've managed to incorporate some complex coding into a Google Sheets document for tracking my team's projects. This includes multiple-variable dropdown menus and integration with Google Calendar to mo ...

Which event occurs first for a4j:jsFunction, reRender or oncomplete?

After running a jsFunction, I want the javascript to execute once the re-rendering is completed. I assume that the "oncomplete" javascript function is triggered after the re-rendering process, but I'm not entirely certain. Any insights on this? Appre ...

What is the best way to save the IDs of selected items from a dropdown menu into an array?

I have a dilemma with storing multiple items selected from a dropdown box inside an array. Currently, I only have one form with the select dropdown list, and each time I choose an item from the list and submit the form, it replaces the previous selection. ...

Electron-Updater identifies a new update, yet refrains from downloading it

The concept: electron-updater is designed to automatically update my electron software whenever a new version is released. The issue: electron-updater identifies the new version, but fails to download and install it. I utilize <a href="/cdn-cgi/l/ema ...

Scrolling infinitely within the side menu using ion-infinite-scroll

I'm encountering an issue with using Ion-infinite-scroll within ion-side-menu, as the load more function is not being triggered. Is it permitted to utilize ion-infinite-scroll inside ion-side-menu? Although I have added the directive, the method "lo ...

Steps for determining the grade earned by an individual

Seeking assistance with my Homework assignment as I am struggling to calculate it accurately. The code provided is what I have so far, and this is the task outlined by my teacher: Develop a webpage that displays the heading "Student Grades" and allows in ...

Utilizing the Mouse Hover feature to target various <div id> elements within a single Vue.js function

I have created two div IDs in an HTML file where I have specified the mouseover property. <div id="app"> <img class="img-responsive img-full" v-bind:src="imgData" @mouseover="imgData = imgData_1"> </div> <div id="app1"> <img cl ...

Python allows for the color coding of numbers using a method that is comparable to the conditional

Looking for a Python module or workaround to color code numbers from 0 to 100, transitioning from red to green. I want to visually represent a score by changing the font color based on the number without starting from scratch. Considering creating a dictio ...

To dismiss the Div, simply click on any area outside of it. Leveraging the power of SVG, D3

I need a way to hide my div by clicking outside of it. My SVG has a background and a graph with nodes on top of that. I have a special node (circle) on the graph, clicking on which makes a box appear. To show the box, I use the following code: d3.select ...

AngularJS Error: $element.find(...) does not support iteration

I'm attempting to utilize a datatable in my AngularJS application. Below is the HTML code I've implemented: <div ng-app="datatable"> <div ng-controller="voucherlistcontroller"> ...

Serve static assets files based on the route path instead of using absolute paths

Within Express, I have set up the following route: app.get('/story/:username', function(req, res){ res.render('dashboard.ejs'); }); Prior to that, I am serving any static files located in /public: app.use(express.static(__dirname ...

Enclose Words Inside Unconventional Outline

Place text within a uniquely shaped border… I am attempting to achieve this goal in the most responsive and backward compatible way possible. I understand that compromise may be necessary. I have made progress with the help of this thread, but the svg ...

Utilizing Angular to parse a JSON string generated with json.dumps

I am having trouble finding a solution that works for me. Currently, I am using python 3.6 (Django Rest Framework) on the server side and Angular 5 on the client side. This is the code on the server: class TypesView(APIView): def get(self,request): ...

Troubleshooting: Angular 2 component directive malfunctioning

I am new to Angular 2 and I'm trying to get my first app up and running using TypeScript. I have the app.component.ts file where I created a directive to another component called todos.component, but I'm encountering this error during compilation ...

Tips for designing a Quasar page that dynamically loads content as the user scrolls

I am attempting to develop a component that will render multiple elements as the page is scrolled. I am utilizing the Quasar framework for Vue.js. Below is the code required to render a single block containing information from a JSON file: Quasar comes wi ...

What are the best circumstances for applying JavaScript in ASP.NET?

As someone who is just starting out in ASP.Net, I have been exploring Validation Controls. However, I am curious about the specific scenarios in which JavaScript would be more appropriate to use. Can anyone provide insight on this? ...