Attempting to reduce the width of the dig when it reaches 400

I have a square element with a click event that increases its size by 50 pixels on each click. However, once it reaches a size of 400 pixels, the size decreases by 50 pixels with every click instead.

Additionally, when the size of the square reaches 100 pixels, it starts to grow again in the same pattern.

This results in the square's size progressing like this: 100, 150, 200, 250, 300, 350, 400, 350, 300, 250, 200, 150, 100, 150, 200...

Thank you to all who can provide assistance with this task.

Below is the code snippet:

<div class="square" onclick="onSquareClick()">

function onSquareClick() {
    var squareSize = 100;
    var sizeStep = 50;
    var square = document.querySelector('.square');

    squareSize = squareSize + sizeStep;
    
    if (squareSize >= 400) {
        squareSize = squareSize - sizeStep;
    }

    square.innerText = squareSize;
    square.style.width = squareSize + 'px';
    square.style.height = squareSize + 'px';
}

Answer №1

Check out this code snippet that demonstrates the solution! As suggested by @kipy, make sure to reverse the direction once the thresholds are reached. This code also includes a state variable to keep track of the current size and step.

const MIN_SIZE = 100;
const MAX_SIZE = 400;
const STEP = 50;

const state = {
  currentSize: MIN_SIZE,
  currentStep: STEP
};

const onBall2Click = (e) => {
  const ball = e.target;
  const { currentSize, currentStep } = state;
  const newSize = currentSize + currentStep;
    
  ball.style.width = `${newSize}px`;
  ball.style.height = `${newSize}px`;
  
  state.currentSize = newSize;
  
  if (state.currentSize >= MAX_SIZE || state.currentSize <= MIN_SIZE) {
    state.currentStep = -state.currentStep;
  }
};

const ball = document.querySelector('.ball');
ball.addEventListener('click', onBall2Click);
.ball {
  width: 100px;
  height: 100px;
  
  background: red;
  border-radius: 50%;
}
<div class="ball"></div>

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

Performing a function inside a JSON structure

I am dealing with a JSON object that contains a list of functions I need to access and run like regular functions. However, I'm struggling to figure out how to achieve this. Here is what I have attempted: Bootstrapper.dynamic = { "interaction": f ...

problems encountered when including next.config.js for sitemap creation in a nextjs application

Just recently, I made an update to my next.config.json file in hopes of boosting SEO performance. However, this change has caused some issues with the next-sitemap module, preventing me from building or starting my app. //next.config.js const withSitemap = ...

Implementing AJAX to seamlessly add comments in real time!

I have set up a commenting system on my website using two PHP files: index.php and insert.php. The index.php file contains a form where users can input their comments, which are then displayed on the page through an echo statement after being stored in the ...

Tips for saving an array of objects in local storage and transferring it from one file to another

Recently delving into the world of localstorage, I've encountered an issue while attempting to store JSON data in one file and retrieve it in another. The JSON data below was fetched from a URL, and my goal is to obtain all the feed objects in the oth ...

What causes certain event handlers to be activated when using dispatchEvent, while others remain inactive?

When it comes to event-based JS, there are two main APIs to consider: event listeners and event handlers. Event listeners can be registered using addEventListener, while event handlers are typically registered with an API similar to target.onfoobar = (ev) ...

How can I use jQuery to retrieve the total number of elements in a dropdown list?

I am working with a dropdown list that looks like this: <select id="ddlProjects"> <option value="315">resproject</option> <option value="320" style-"display:inline">newheavn</option> <option value="395" style="di ...

Post-installation of NPM, configuring CA certificates on Windows system

TLDR; Is there a way to seamlessly set NODE_EXTRA_CA_CERTS in a Windows environment for NPM packages' post-install scripts without requiring system changes, configuration file modifications, or admin-level permissions? Details This issue has been f ...

AngularJS and synchronized queueing of API requests

I am attempting to develop a synchronized queue for API requests using AngularJS. class x { public y() { ... restRequest(); } } I have this class, along with a whiteboard canvas. When I drop an entity onto the canvas, the method &a ...

Ways to shift placeholder text slightly to the right within a select dropdown?

Struggling with this issue for hours, I can't seem to figure out how to: Adjust the position of the placeholder text (Search) by 10 pixels to the right in my select component Reduce the height of the field (maybe by 5px) without success. Could someo ...

In React development, a div (button) is visible, but in the production build, it becomes hidden from

I have been working on a website for my job, and I have added a "Gallery" button on top of two slideshows. Everything works perfectly fine on the development build, but when it comes to the production build, the button doesn't show up for some reason. ...

CSS Media Query Assistance - optimizing text display for mobile responsiveness

I am currently facing an issue with my CSS code where the content is displaying as one long sentence on mobile devices, requiring users to scroll to read it. I am trying to modify it so that it displays as two lines on mobile. <!-- promo banner --> ...

Enhanced jQuery Pop-Up Panel

A few issues to address: 1) My goal is to optimize the efficiency of this script. 2) When a user clicks on either pop-out button, it opens a window and hides the element. (Currently using .detach() to remove the embedded video player because in Firefox . ...

Multiplication and Division with Unit-ed Values in CSS calc() Function

Can you perform multiplication or division with unit-based values using calc() (such as 100%, 5px, etc)? For instance, I wanted to try something like this: width: calc(100% * (.7 - 120px / 100%)); Expecting it to result in something similar to (if 100% ...

Modify the background color of a particular TD element when clicking a button using JavaScript and AJAX

When I click on the "Active account" button inside the designated td with the <tr id="tr_color" >, I want the value "1" to be added to the 'active_account' column in the database. I have been successful with this functionality. However, I a ...

Implementing image caching in tvOS with React-Native: A step-by-step guide

Looking to Implement Image Caching in tvOS using React Native I'm trying to figure out how to cache images that I download from the internet on my Apple TV. I've experimented with various libraries, but none seem to be compatible with tvOS. Any ...

Organize three image links side by side using HTML layout

Hello there! I'm currently working on a website project and I'm struggling with arranging some image links in a specific layout. The grey rectangles you see represent where the images should be placed, all of them are uniform in size (275 x 186) ...

Populate your HTML with JSON data

I need some guidance on how to achieve a specific task. I have a PHP file that retrieves data from a MySQL database and returns it in JSON format. Now, I want to display this data in HTML with "data_from_json" replaced by "18.5". Any assistance would be gr ...

Tips for effectively utilizing an if/else structure to animate fresh content from the right while smoothly removing old content by sliding it to the left

document.getElementById("button1").addEventListener("click", mouseOver1); function mouseOver1(){ document.getElementById("button1").style.color = "red"; } document.getElementById("button2").addEventListener("click", mouseOver); function mous ...

Exploring the Information Within HTML Forms

When my HTML form sends data to the server, it looks like this: { r1: [ '1', '2', '3' ], r2: [ 'Top', 'Greg', 'Andy' ], r3: [ 'validuser', 'invaliduser', 'validuser&a ...

What is the best way to add a color swatch image using Javascript?

I'm facing a challenge in Shopify where I need to assign corresponding background images to color swatches. Currently, my icons are set up with the correct links for each color, but they are missing their respective images, similar to this example. I ...