JavaScript script to modify the parameter 'top' upon clicking

Here is the pen I've made.

HTML

<div class = 'cc'>  
    <div class = 'bb'><div class = 'aa'> Some word </div></div>
</div>

CSS

.cc {
  width: 100%;
  min-height: 90px;
  margin: 0;
  padding: 0;
  border: 1px solid #999999;
  border-radius: 3px;
  padding-left: 20px;
  padding-right: 20px;
  font-family: "Calibri";
  font-size: 17px;
  color: #666666;
  background-color: rgba(0,0,0,.0);
}

.bb {
  height: 100px;
  width: 100%;
  background-color: rgba(0,0,0,.5);
}
.aa {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}

If a user clicks on class bb, I want the page to check the top value of class aa - if it's 50%, smoothly change it to 10% and vice versa.

To achieve this, I need to incorporate some JavaScript code. How can I accomplish that?

Answer №1

Just wanted to share that I gave it a try and it seems to be working fine. Please check it out!

let boxB = document.querySelector('.bb');
let boxA = document.querySelector('.aa');

boxB.addEventListener('click', event => {
  let topValue = window.getComputedStyle(boxA).getPropertyValue('top');
  if(topValue === '50px'){
     boxA.style.top = '10%';
  } else {
    boxA.style.top = '50%';
  }
})

Answer №2

Understood. All tests have been conducted and the solution appears to be functioning correctly.

let bb = document.querySelector('.bb');
let aa = document.querySelector('.aa');

bb.addEventListener('click', function(){

  if(window.getComputedStyle(aa).getPropertyValue('top') === '50px'){
     aa.style.top = '10%';
  }else{
     aa.style.top = '50%';
  }
})

To start, I utilized querySelector to locate elements with classes .bb and .aa.

Subsequently, I attached an event listener to bb. Within this listener, I used window.getComputedStyle() to retrieve the value of the CSS property top and evaluated if it was equal to 50px.

Lastly, depending on the result, I altered the value to either 10% or 50%.

This process was executed on CodePen, where you can view the demonstration here (please note that the style was modified from gray to white for better visibility within a black container).

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

Struggling with a minor glitch in a straightforward coin toss program written in JavaScript

I'm a newcomer to JavaScript programming and I am struggling with understanding how the execution flow is managed. I attempted to integrate an animation from "Animation.css" into a coin toss program, but encountered an issue. When trying to use JavaSc ...

How can I retrieve values from HTML5 data attributes using Selenium in Python?

How can I extract the value "165796011" from data-gbfilter-checkbox? I attempted to do so using the following code: element= driver.find_element_by_css_selector('#widgetFilters > div:nth-child(1) > div.a-row.a-expander-container.a-expander-inl ...

The background image within Bootstrap theme layouts appears to be missing from both the styles and divs

Encountering a peculiar dilemma here. Attempted to apply a background image to a custom style in order to override/extend a bootstrap column style. Additionally, tried embedding a style directly in the div attribute. Strangely, neither method seems to be e ...

Is it necessary to send form data back with Express, or is there an alternative solution?

I am facing a simple problem with my handlers for /login get and post requests. Here is the code: loginRender(req, res) { let options = { title: 'Login', layout: 'auth.hbs' } res.render('login', options) } logi ...

if a condition is not being properly assessed

Currently, I am working on a $.ajax call to retrieve data in JSON format. Within this JSON data, there is an element called "status." My code snippet checks if the value of `data.status` is equal to "success" and performs some actions accordingly. Despite ...

A script in PHP or JavaScript that dynamically generates two dual drop-down menus to assist with data selection

I have experience with php scripting, but I am facing challenges when trying to combine it with JavaScript. The issue arises when I have a form that includes dropdown menus for categories and subcategories. When a category is selected, the options in the s ...

Deleting all JSON files in a directory using NodeJs

Is there a way to delete only the json files within a directory (multiple levels) without specifying each file name individually? I thought fs-unlinkSync(path) might work, but I haven't found that solution yet. I attempted to use the following method ...

Sending Data from Browser to Node.js using Ajax

I've been struggling to send an AJAX post request to my Node server built with Express for a while now. Despite reading various solutions on similar issues, I couldn't figure out which files to edit. Initially, I attempted using `http.createServe ...

The masonry reorganization is behaving strangely

I've recently started using masonry for the first time and you can check it out here: Although I have managed to set it up, I am facing some issues with its positioning of boxes when dragging items in. For example, instead of placing a medium-sized ...

Is it possible to position two fixed divs side by side?

I am currently in the process of building my online portfolio. I am looking to create two fixed divs that will not scroll, each occupying the full height of the page. The content between these two divs should be scrollable while the bars on the left and ri ...

Displaying client-side filtered rows in a jqGrid with postData filter upon initial loading

Our website includes a jqGrid that initially retrieves its rows using the built-in ajax fetch feature, returning a json object. We then apply filtering and searching on the client side by creating custom functions to generate postData filters. However, we ...

What is the best way to handle a large number of nested AJAX GET requests?

My task involves making numerous AJAX GET requests, which must be nested because each request depends on variables from the response of the previous one. Although I was able to make multiple requests with the example below, it becomes impractical when dea ...

What measures can be taken to prohibit a user from accessing a client-side HTML file using express?

I am currently developing a task management application called "todolist." In my node.js code, I utilize express and grant it access to my directory named Client: var app = express(); app.use(express.static(__dirname + "/Client")); The contents of my Cl ...

AngularJS Expression Manipulation

I am looking to implement a functionality similar to the one below: HTML <mydir> {{config = {type: 'X', options: 'y'}} </mydir> <mydir> {{config = {type: 'a', options: 'b'}} </mydir> JS Dir ...

Webpack is unable to locate a specific custom JavaScript file

Currently, we are in the process of transitioning from grunt to webpack for our project. Within our project, we have a JS file named boiler that is used to define the core classes which are frequently accessed. __boiler__.js define(function (require) { ...

Is there a way to insert a secured page right before accessing the dashboard?

I am trying to create a locked page that will display a message when users access the web app from a mobile device and load a mobile layout page displaying a message like mobile is not supported. I was considering using document.addEventListener('DOMC ...

What is the method for displaying data from a JSON file that is associated with the wallet address of the authenticated user in next.js?

I am currently working on a claim page using next.js, where logged in Metamask addresses can perform the following tasks: Access data from a local .json file to check eligibility for claiming an item and display the claim page. Submitting a form to update ...

How can I preloaded self-hosted fonts in Next.js without receiving a console warning for not using the resource within a few seconds?

I am working on a project in Next.js and I want to preload my self-hosted fonts. In my code, I have the following setup: Inside my _app.js file: <Head> <link rel="preload" href="/fonts/leira/Leira-Lite.t ...

Dynamic loading of lists necessitates encapsulating nested lists

I'm currently working on a 3-level dropdown list that pulls content from a database for my project. I want the top level to resemble a tab menu, with a border surrounding the area underneath where the additional lists will appear. However, I am facing ...

I'm struggling to grasp the concept of State in React.js

Even though I'm trying my best, I am encountering an issue with obtaining JSON from an API. The following error is being thrown: TypeError: Cannot read property 'setState' of undefined(…) const Main = React.createClass({ getInitia ...