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

Troubleshooting MongoDB and Node.js: Issue with updating variables when inserting documents in a loop

As a newcomer to MongoDB, I'm facing a puzzling issue that has left me confused. In my dataset, I have an array of Employee objects structured like this: { "Name" : "Jack Jackson", "Title" : "Senior Derp Engineer", "Specialties" : [ "Kicki ...

Link that causes the regular expression test to hang

My goal is to create a regular expression that can accurately identify URLs. I found the code snippet for this on Check if a Javascript string is a url. The code looks like this: function ValidURL(str) { var pattern = new RegExp('^(https?:\/&b ...

Numerous social media sharing buttons conveniently located on a single webpage

Currently, I am working on a research database project where the goal is to allow users to share articles from the site on various social networks such as Facebook, Twitter, LinkedIn, and Google+. To achieve this, I successfully implemented share buttons ...

Leveraging strings as URLs to embed PDFs in Wordpress using PDF Embedder

I'm encountering an issue related to a Wordpress plugin called PDF Embedder, as well as concatenating/using a string with document.write. My goal is to make this code work: <script src="http://nooze.org/wp-content/uploads/scripts/dateGetter.js"> ...

Troubleshooting Bootstrap 3.0: Issues with nav-tabs not toggling

I have set up my navigation tabs using Bootstrap 3 in the following way: <ul class="nav nav-tabs pull-right projects" role="tablist" style="margin-top:20px;"> <li class="active"><a role="tab" data-toggle="tab" href="#progress">In Pr ...

Attempting to retrieve dynamically generated input fields and cross-reference them with structured length .json data

In the process of developing code, I've implemented a for loop to dynamically generate HTML input fields based on the length of some data in a .json file. My goal is to use jQuery to compare the text entered in each input field with the corresponding ...

The feature for sending posts in Angular.js appears to be malfunctioning

I have developed a rest-API for adding todos in a MongoDB database. When I use Postman with the setup below, I can successfully save instances: http://localhost:3000/api/addtodo x-www-form-urlencoded with values text="Test", completed: "false". However, ...

The issue of passing a local object from ng-repeat into a directive controller remains unresolved

I'm struggling to pass my local object from ng-repeat to a directive. My goal is to access the data from that object within the controller of the directive. The confusion arises with how the isolated scope and controller scope interact. I can't f ...

A Guide to Displaying HTTP Error Messages on the Angular Login Page

When encountering a form validation failure on my login page, I utilize ngMessage to display an error message. However, I now want this div to be displayed in the event of an HTTP 500 error. While I can retrieve the corresponding error message when an HTTP ...

Managing PHP and AJAX: Strategies for handling and transmitting error responses

There are three main components involved in this process: An HTML form The AJAX connection that transmits the form data and processes the response from the PHP script The PHP script, which evaluates the data received, determines if it is valid or not, an ...

Bootstrap5: Left-aligned Navigation Bar Pills and Right-aligned Text

I am trying to align all my navigation pills to the left, and then add a single text element that stays at the end of the navbar even when the page is resized. Navbar Image My attempt involved adding a div so that the navbar pills would take up 50% width ...

Using Material UI with React hooks

I'm encountering an error while trying to incorporate code from Material UI. The error message is: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons: 1. Mismatc ...

Allowing domain access when using axios and express

I have a server.js file where I use Express and run it with node: const express = require("express"); const app = express(), DEFAULT_PORT = 5000 app.set("port", process.env.PORT || DEFAULT_PORT); app.get("/whatever", function (req, r ...

Extracting numbers using regular expressions can be tricky especially when dealing with mixed

Currently, I am attempting to create a javascript regex that can extract decimal numbers from a string containing a mix of characters. Here are some examples of the mixed strings: mixed string123,456,00indeed mixed string123,456.00indeed mixed string123,4 ...

What is the procedure to change a matter body's isStatic property to false in matter.js upon pressing a key?

During my recent project, I encountered a challenge in trying to set the isStatic property of a Matter Body in matter.js to false when a key is pressed. if (keyIsPressed(UP_ARROW)) { this.body.isStatic(false) } Could you provide guidance on the correct ...

Develop a monitor for an entity that has not been created

Currently, I am tackling a feature that involves tracking an asynchronous request within a synchronous one. Let me elaborate. The code snippet I am working with looks something like this: const myObj = {}; function sendMessage(requestId, data) { kafkaP ...

What is the best way to transfer an argument from a parsed JSON value to an onclick function?

In our dataset, we have a specific table that contains valuable information. My main objective is to transfer an argument extracted from parsed JSON data to a separate JavaScript function known as newStory(value['stories']) using the onclick meth ...

How to temporarily toggle an event on and off using jQuery

Is there a way to control the activation and deactivation of a jQuery event? I currently have this functioning code that runs when the page is ready: $(".panzoom").panzoom({ $zoomIn: $(".zoom-in"), $zoomOut: $(".zoom-out"), $zoomRange: $(".zoo ...

Using React: Implementing conditional checks within the render() method of functional Components

When working with my usual React class Components, I typically perform some checks within the render() method before returning conditional html rendering. However, when using a react functional component, I noticed that there is no render() method availabl ...

The Chocolat.js Lightbox plugin is experiencing issues with jQuery as it is unable to detect the

I am in the process of integrating chocolat.js into a basic website. An issue I encountered was that the thumbnail was directly processing the anchor link, which resulted in the image opening in a new window instead of launching it in a modal on the screen ...