Clicking on a div will expand its size while simultaneously shrinking another div. Clicking on the same div again will

How do I create a function for my website where I have 5 divs in a container with a width of 20% each? When I click on one div, I want it to expand to 40% while the other divs shrink to 15%. Then, when I click on the expanded div again, it should return to its original size. Additionally, I want the transition between divs to be smooth.

Although I found an example online, I am new to JavaScript and struggling to understand it. Can someone provide me with a simple function that achieves the same effect?

Here is the example I came across:

Answer №1

An update on the previous answer by kdureidy: - The state does not toggle upon clicking again - It does not consider the number of "boxes" in the calculation

Check out this revised version:

$('body').on('click', '.box', function(e) {
  var $target = $(this)
    , targetIsActive = $target.hasClass('active')
    , $boxes = $('.box')
    , boxesCount = $boxes.length
    , inactiveWidth = 100 / boxesCount
    , activeWidth = inactiveWidth * 2
    , othersActiveWith = (100 - activeWidth) / (boxesCount - 1)
    ;
  if(!targetIsActive) {
      $boxes.removeClass('active').css('width', othersActiveWith + '%');
      $target.addClass('active').css('width', activeWidth + '%');
  } else {
      $boxes.removeClass('active').css('width', inactiveWidth + '%');
  }
});

https://jsfiddle.net/xw1e34yy/

Answer №2

Here's a different approach: In order to reset the width of all divs, assign them the same class. Then, utilize JavaScript to target the clicked div and adjust its width. To add smooth animation effects, implement transitions.

$(".element").on("click", function(event) {
  $(".element").css("width", "20%");

  $(event.currentTarget).css("width", "50%");
})

https://jsfiddle.net/98v7pxq1/

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

Feature for jotting down notes, creating a break between lines without any information present

I'm currently working on implementing a note-taking feature for my web application. However, I have encountered two issues: Firstly, I am struggling to identify line breaks within the text. While I can hardcode text with line breaks, when a user clic ...

I'm having trouble seeing the values displayed above the bars in Chart.js

Recently, I started learning about chart.js and encountered an issue where the bars were not displaying the values on top, along with a question on how to add a percentage sign after the value. I'm using chart.js version 3.3.2 from a CDN. Any assistan ...

Arrangement of JavaScript objects based on timestamp key

In JavaScript, there are specific rules that dictate the order of object properties. One interesting example caught my attention. When a timestamp in milliseconds is used as an object property key, the ordering does not function as expected. However, if ...

Tips on uploading information from a PDF document onto a website

My goal is to develop a program or script that can extract data from PDF form fields and automatically input it into the corresponding textfields on my website, all done through the front end. The problem I'm facing is not knowing where to begin with ...

Obtain the hidden field value when clicking on each image retrieved through jQuery/AJAX

Implementing a feature on my website to display images using jquery and php, where each image has a hidden field input containing the file name. The goal is to click on an image and have the value of the hidden field appear in a text box. Here's a sn ...

Setting attributes on an AngularJS Directive element in real time

My goal is to create a directive in AngularJS with a template that can contain other AngularJS directives. All of my directives require an "id" attribute, so I must set the "id" on the directive within the template. However, no matter how I attempt this, A ...

Issues with the functionality of jQuery append and AngularJS ng-if not functioning

In my application using checkboxes, I control the visibility of charts with the ng-if directive and implement drag-and-drop functionality with angular-Dragula. The use of ng-if is essential for me as it allows me to manipulate visible div IDs and organize ...

Is it possible to efficiently utilize Map/Set in TypeScript/JavaScript when working with objects?

I'm currently transitioning from Java to TypeScript and I've encountered an issue with working with objects in hashmaps and hashsets. In Java, I would simply override the hashCode method to easily manipulate these data structures. Is there a simi ...

Storing dropdown values in variables using AJAX and JQuery

In my code snippet, I have the following:- <script> $("#country").on("change", function(){ var selected = $(this).val(); $("#results").html("<div class='alert-box success'><span><img src='images/ ...

Updating Kendo by modifying the Angular model

While working on a project with Angular, I recently discovered the Kendo-Angular project available at . I successfully integrated Angular-Kendo into my project and it seems to be functioning well, except for updating models in the way I am accustomed to. ...

Retrieving a designated set of attributes for elements chosen using an element selector

Is there a way to retrieve specific attributes for the first 10 <p> elements in a document using jQuery? I know I can easily get the first 10 elements with $('p').slice(0,10), but I only need certain attributes like innerText for each eleme ...

Check if the element with the ID "products" exists on the page using JQuery. If it does, then execute a certain action

Is there a way to create a conditional statement that executes if the element with the ID "products" is present in the HTML code? Thanks in advance for your help! Pseudo code using JavaScript (JQuery) if ( $('#products').length ) { // do s ...

Enhance user experience with Jqgrid hyperlinked user format

I am currently utilizing jqgrid with JSON data that is structured as follows: {"my_id" : 12345, "doc_number" : 9786} My objective is to implement an hlink formatter that displays the doc_number, while passing the my_id as a parameter to my JavaScript func ...

Trouble aligning CSS Nav Bar to the right with Flexbox

Having some trouble with implementing "flex" in CSS. My nav bar just won't move to the right no matter what I try. Spent hours adjusting margins, displays, and floats but it's stuck in the middle... Still learning, so any help is appreciated! If ...

What is causing the 'info' object to be undefined?

transporter.sendMail(mailOptions,(error,info)=>{ if(error) console.log(error) console.log('Message Sent: '+info.messageId) console.log('Preview URL: '+nodemailer.getTestMessageUrl(info)) res.redirect('contacts', ...

What are the steps to ensure the equalizer start button functions properly?

I have created an application that mimics the functionality of an equalizer by displaying changes in audio frequencies. https://i.sstatic.net/W7Fzi.png Issues with animation arise when you click the "Start" button again. The animation resets and begins ...

Is it possible for issues to arise when serving a web app using the "Globals" module in the Mean Stack?

Looking to transfer a variable (a constructed filename) from one file to another within an API can be quite challenging. One solution that comes to mind is utilizing globals, but with my current code structure, it seems like the only viable option. To addr ...

Navigating with React Router: Maintaining user data persistence during route changes

As I develop a React Router application, my focus is on mastering authentication. Here is an overview of the key components: Login component (login.jsx) Verifies user credentials on the backend Saves the authentication token in local storage Returns t ...

Node.js continually throwing 503 errors

After successfully installing and running Node.js for a while, I attempted to execute a standard Hello World program. The code snippet looked something like this: var http = require("http"); http.createServer(function (request, response) { response.w ...

Is there a method to generate TouchEvents or a similar functionality in Firefox?

I am currently developing a browser extension that is able to generate simulated TouchEvents. My project is functional in Chrome, but I have encountered an issue with Firefox not supporting the TouchEvents feature. When attempting to create a new TouchEven ...