Switch between various height and width options using JavaScript

Is there a way to create a toggle that changes both the height and width of an element when it is clicked?

<div class="flexbox-container" id="main" onclick="staybig()">Create Account</div>
.flexbox-container {
    transition: height 0.5s, width 0.5s;
    height: 100px;
    width: 100px;
    display: flex;
    justify-content: center;
    text-align: center;
    align-items: center;
    background-color: #492ee4;
    border-radius: 50%;
    display: flex;
    margin: auto;
    margin-top: 200px;
}
let isBig = false
if (isBig) {
    main.style.width = "100px";
    main.style.height = "100px";
    isBig = false
} else {
    main.style.width = "113px";
    main.style.height = "113px";
    isBig = true
}

I have tried implementing this code but it does not produce the expected results. Can anyone provide assistance on how to fix this issue? Thank you.

Answer №1

After reviewing your problem description and the provided code snippet, it appears that you are defining the variable isBig within the event handler. This results in resetting the state of isBig to false every time the event is triggered, causing the element to only grow larger.

To resolve this issue, it is recommended to declare isBig outside of the event handler:

let isBig = false

function staybig() {
  if (isBig) {
    main.style.width = "100px";
    main.style.height = "100px";
    isBig = false
  } else {
    main.style.width = "113px";
    main.style.height = "113px";
    isBig = true
  }
}
.flexbox-container {
  transition: height 0.5s, width 0.5s;
  height: 100px;
  width: 100px;
  display: flex;
  justify-content: center;
  text-align: center;
  align-items: center;
  background-color: #492ee4;
  border-radius: 50%;
  display: flex;
  margin: auto;
}
<div class="flexbox-container" id="main" onclick="staybig()">Create Account</div>

Alternatively, a more efficient approach would be to define the styles in CSS and simply use toggle() to switch the class in the event handler, which should be bound in JavaScript rather than HTML. Here's an updated example with these improvements made:

const main = document.querySelector('#main');

main.addEventListener('click', () => main.classList.toggle('large'));
.flexbox-container {
  transition: height 0.5s, width 0.5s;
  height: 100px;
  width: 100px;
  display: flex;
  justify-content: center;
  text-align: center;
  align-items: center;
  background-color: #492ee4;
  border-radius: 50%;
  display: flex;
  margin: auto;
}

#main.large {
  width: 113px;
  height: 113px;
}
<div class="flexbox-container" id="main">Create Account</div>

Answer №2

It seems like there is an issue with the way your code is handling the isBig variable updates. It's important to ensure that the isBig variable is declared outside of the click event handler in order to maintain its state between different clicks. Below is a revised version of your code:

let isBig = false;
const element = document.getElementById('yourElementId'); // Make sure to replace 'yourElementId' with the actual ID of your element

element.addEventListener('click', function() {
    if (isBig) {
        element.style.width = "100px";
        element.style.height = "100px";
        isBig = false;
    } else {
        element.style.width = "113px";
        element.style.height = "113px";
        isBig = true;
    }
});

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

Launch Internet Explorer and input variable values (such as ScriptEngineMinorVersion)

I am looking to create a script that can open a file and inject values into it. Here is a basic example: Set WshShell = WScript.CreateObject("WScript.Shell") Return = WshShell.Run("iexplore.exe google.com", 1) However, I also need to modify some variab ...

What is the process for cancelling an interval when it is disabled in my configuration file?

To automate a bot, I want it to stop running an interval if the configuration file specifies "off" and continue running if it says "on". I attempted this: Using discord.js: config.Interval = setInterval(() => { WallCheck.send(WallCheckemb ...

What is the recommended approach for embedding scripts within Angular templates?

I am working on an Angular SPA that consists of multiple tabs, each served by templates. Depending on the tab, different scripts (both local and CDN) are required. Therefore, I am looking for a way to load these scripts only when they are needed, which mea ...

What is the best way to prevent useEffect from triggering when a modal is being rendered?

I'm currently developing a react movie application. I am facing an issue with the hero picture feature that displays a random popular movie or show. Whenever I click the button to open a modal, the useEffect function is triggered and changes the movie ...

Unable to display information from a repeated `textarea` in ngRepeat

Check out my code on Plunker: https://plnkr.co/edit/rBGQyOpi9lS0QtnCUq4L I'm trying to log the content of each textarea when typing, using the printStuff() function: $scope.printStuff = function(customize, item) { console.log(customize[item.inde ...

Utilizing Axios to filter response.data in an API request

Looking to retrieve the latest 8 products based on their date? Take a look at the code snippet below: const newestProducts= []; axios.get("http://localhost:3003/products").then(response => { let products = response.data.sort(fu ...

Constructing hierarchical objects in JavaScript

I am looking to create a complex nested object in JavaScript that follows a specific structure. const data = { name: 'Context 1', children: [ { name: 'Option 1', children: [ { name: 'Context&ap ...

What are some strategies for optimizing React performance when managing controlled input from numerous components?

Building a Parent component with multiple child components, each passing data to the parent for an API call. The structure is as follows: const MainComponent = () => { const [child1input, setChild1Input] = useState(""); const [child2input, setChild ...

Utilizing JavaScript Callbacks in HTML Image Tags

Currently I am working on a small application and looking to include a YouTube section. I have come across a method for obtaining the user's YouTube icon: This is included in the head section of my code: <script type="text/javascript" src="http:/ ...

Is it possible to generate various resolutions of an image simultaneously?

While trying to download wallpapers from a link on this website, I encountered an issue. Upon clicking the download button, a new page opened with the URL "https://images.wallpapersden.com/image/download/street-fighter-fortnite_bGtoaW6UmZqaraWkpJRmbmdlrW ...

Ways to perform a force click on a span element when clicking on a glyphicon

There is a table cell containing two span elements: <span contentEditable=true class="editspan"></span> <span class="pencilspan glyphicon glyphicon-pencil pull-right"></span>" When clicking on span1, an input box appears for editi ...

Querying data with parameters in a client-side rendered application with Next.js

Currently, I am developing a chat application using Next.js and Axios. One of the functionalities I implemented is a dynamic route called chat/:pid to fetch data using the provided pid. However, I encountered an issue where the values are coming back as un ...

Browsing through a jQuery JSON object in Chrome reveals a dynamic reshuffling of its order

Jquery + rails 4 Within the json_data instance, there is data with key-value pairs. The key is an integer ID and the value is an object containing data. However, when attempting to iterate over this data using the jQuery $.each function, the results are s ...

What is the method for accessing a selector within a foreach loop?

Whenever a user clicks on a date in the jquery datepicker, two ajax calls are triggered. The goal is for the second ajax call to populate the response/data into a paragraph with the class spots within the first ajax call, displaying available spots for th ...

The trouble with dynamicHelpers in Nodejs Express

Trying to make my app run smoothly, I've set up the following configurations: app.configure(function(){ app.set('views', __dirname + '/views'); app.enable('jsonp callback'); app.set('view engine', 'j ...

transferring data using react-router

I'm working on a code that displays four images, and when one of them is clicked, it should take up the entire screen. I am using React Router to implement this functionality. Here's the current code setup: App.js import React from 'react&a ...

Retrieve the maximum number of slots from a JSON file and implement them into the

I've encountered an issue with my upload form. After uploading and previewing an image, I want to add it to a list as long as the list still has available slots. Here's an example: If the maximum number of slots is set to 5, then you can add up ...

Trigger an animation function with JQuery once the first one has finished

I am attempting to create a step-by-step animation of a div in JQuery. Each animation is triggered by a click, followed by a double-click, and so on. My issue arises when the animations overlap. When I double-click the div, both the first and second anima ...

Changing the size of circles in text and adjusting the dimensions of SVG elements

As a novice JavaScript programmer, I am attempting to resize circles and SVG elements based on the window size. Currently, my code creates circles of varying sizes, but I haven't been able to adjust them in relation to text size. var width = 600; va ...

Dealing with functions that may not consistently return a promise

When dealing with a situation where a function does not always return a promise, how can it be best handled? The complexity of my current code prevents me from providing a detailed explanation, but essentially, the issue involves checking a condition and t ...