.toggleClass malfunctioning inexplicably

I've been struggling to make a div box expand when clicked and revert to its original size when clicked again. It seems like a simple task, but no matter what I try, I can't seem to get it right. I'm not sure where I'm going wrong, as the problematic part of the code is quite short. Thank you for your help!
https://jsfiddle.net/uL1r08am/

<div id='panelHolder'>
  <div id='panel1' class='panels'></div>
</div>

.panels {
  position:relative;
  border:2px solid silver;
  transition:transform 1.5s;
}

.panels:hover {
  transform:skewY(3deg);
}

#panel1.clicked{
  width:460;
  height:290;
}

$('#panel1').on('click', function() {
    $(this).toggleClass('clicked');
});

$(document).ready(main)

Answer №1

you need to add px after the numerical values for width and height

Change :

#panel1.clicked{
  width:460;
  height:290;
}

To :

#panel1.clicked{
  width:460px;
  height:290px;
}

Here is the updated code :

<!DOCTYPE html>
<html>
<head>
    <style>
        .panels {
                  position:relative;
                  border:2px solid silver;
                  transition:transform 1.5s;
                }

            .panels:hover {
              transform:skewY(3deg);
            }

        #panel1.clicked{
          width:460px;
          height:290px;
        }
    </style>
</head>
    <body>
        <div id='panelHolder'>
            <div id='panel1' class='panels'>DIV</div>
        </div>
        
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $('#panel1').on('click', function() {  
                $(this).toggleClass('clicked');
            })
        })
    </script>
    </body>
</html>
        

Answer №2

The dimensions remain constant because the unit px is absent from your width and height values. The toggle functionality is functioning properly.

Check out the revised demonstration here: https://jsfiddle.net/uL1r08am/2/

Answer №3

Make sure to enclose your javascript within the document ready function

$(document).ready(function() {
  $('#panel1').on('click', function() {
    $(this).toggleClass('clicked');
  });
})

Answer №4

Have you considered using the addClass and removeClass methods?

$('#box1').click(function() {
  if ($('#box1').hasClass('active'))
     $('#box1').removeClass('active');
  else
     $('#box1').addClass('active');
});

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

What is the best way to access the current webdriver instance using code?

Currently, I am in the process of creating an end-to-end test suite with Protractor. As Protractor is based on WebdriverJS, I am attempting to utilize some of its functionality. More specifically, my goal is to incorporate certain behaviors using Webdriv ...

What was the reason for needing to employ `toObject()` in mongoose to determine if an object contains a certain property?

From what I understand, there is no .toObect() function in JavaScript, but it is used in mongoose to convert mongoose documents into objects so that JavaScript built-in functions can be used. I sometimes struggle with when to use it. There are instances w ...

Delay reading body until npm request completes

My current challenge involves using npm request and cheerio to extract webpages and analyze their HTML structure. Everything works smoothly in scenarios where the HTML is available upon request. However, I am facing a problem when a website initially displ ...

Animating transitions when hovering (using jQuery)

As a newbie to jQuery, I am currently exploring how to create an animated transition for a headline. I stumbled upon this CodePen (http://codepen.io/ansac/pen/BHtkE) but it doesn't quite match what I have in mind. My main query is: How can I maintain ...

Enlarged text size disrupts alignment of ul menu items

After creating a fixed menu using unordered lists and extensive CSS, I added a custom class button that redirects back to the frontpage. However, I noticed an extra pixel of height in the menu causing alignment issues with the buttons. The big button stick ...

Customized Box with MaterialUI Styling

Currently, I am utilizing Material UI 5 for my project. To avoid repeatedly defining the same sx prop every time I create a box, I aim to build a custom box component that ensures all boxes have a consistent appearance. Upon going through the documentation ...

The nth-of-type function behaving similarly to the nth-child function

Reviewing my HTML snippet: <div class="itemContainer"> <div class="clearance"></div> <div class="productBox" ></div> <div class="clearance"></div> <div class="productBox" ></div> & ...

Understanding CSS classes in ReactJS Material UI componentsJust wanted to clarify some things

When it comes to styling Material UI components, the recommended approach is to utilize their useStyles function. Here's an example: const useStyles = makeStyles(theme => ({ root: { marginTop: '15px', display: 'f ...

Adjust the background color of the date and time selection tool

Trying to customize the background of a datetime picker created using jquery.pttimeselect.js. Despite linking the correct css file (jquery.pttimeselect.css), I am unable to change the background color. Any suggestions on how to successfully modify the ba ...

What is the process for creating a progress bar in PixiJS?

Can someone guide me on creating a progress bar similar to the one in PixiJS? Screenshot ...

Tips for eliminating white frames or borders on the Mapbox canvas map

In my current project using Angular 10, I have integrated Mapbox to display path routes. Following the standard Angular practice of splitting components, I separated the map rendering component and called it into the main map component. However, I encounte ...

Steps for detecting a 401 Unauthorized error in SignalR when the token has expired

I have created a dynamic page that continuously fetches real-time information from my Azure functions backend using SignalR. If I am on the page for an hour and experience a disconnect, the signalr client will attempt to reconnect automatically, which usua ...

NuxtJs: Oops! It looks like NuxtError is not defined in this context

Exploring NuxtJs is new to me. I decided to experiment with how nuxt-link functions by purposely setting up a nuxt-link to a non-existent route in order to trigger the default 404 page. Here's the line of code I added to the pages/index.vue file: < ...

Unable to authenticate an HTML form using PHP and Apache 2

In my website's footer, there is a form that I am trying to run using a PHP file located at 127.0.0.1/form.php on localhost. I learned that PHP code inside HTML is commented out, and according to the PHP Documentation, the PHP file needs to be run dir ...

ReactJS component state fails to update accurately

Let's say I have a component named Test import {useEffect, useState} from "react"; const Test = (props) => { const [Amount, setAmount] = useState(1); useEffect(()=>{ if(props.defaultAmount){ setAmount(prop ...

Utilizing ng-click within ng-repeat along with $index

I'm experimenting with using ng-click on a div that is part of an ng-repeat loop, utilizing $index as seen in the code below : HTML: <div class="elementContainer" ng-repeat="element in elements" ng-click="elementUrl($index)"> <h2>{{ ...

Executing Selenium WebDriver to interact with a hidden element

Hello, I am interested in learning how to interact with hidden elements and disable them using Selenium WebDriver. I've managed to achieve this with Selenium 1 by using the following code: selenium.click(id="idOfHiddenField"); Unfortunately, this a ...

The classification of rejected promises in Typescript

Is it possible to set the type of rejection for a promise? For example: const start = (): Promise<string> => { return new Promise((resolve, reject) => { if (someCondition) { resolve('correct!'); } else { ...

Ensure that the Bootstrap image element maintains its full height without resizing

While working on my Angular application, I encountered an issue with designing a side list-group of recent blogs using Bootstrap 4. When the aspect ratio is changed to mobile view, the images resize and become smaller to fit into the div as the title lengt ...

Using jQuery, send a post request to a page and then parse and handle

Recently, I attempted to make use of jQuery to post to a form and analyze the outcomes on the posted page. To demonstrate this process, I have put together a very basic example. $('#submit').click( function () { $.get('post.htm& ...