What is the best way to ensure one div expands to full width while simultaneously hiding another div on the page?

Hey there, I'm looking for a way to expand the width of a clicked div while making the other div disappear from the screen simultaneously. It should also be toggleable, so clicking the button again will shrink the div and bring back the other one. For a better visual explanation, you can check out my CodePen demo here

const viewButtons = document.querySelectorAll(".view-now");

const clickHandler = event => {
  //add "expand" class to div that was clicked
  const propertyDiv = event.target.closest(".property");
  propertyDiv.classList.toggle("expand");

  //if class name = 'property' then display none. this gets rid of the other div on the screen
  const allProps = document.querySelectorAll(".property");
  for (i = 0; i < allProps.length; i++) {
    if (allProps[i].className == 'property') {
      allProps[i].style.display = "none";
    }
  }
};

viewButtons.forEach(item => {
  item.addEventListener("click", clickHandler);
});

Answer №1

To easily switch between viewing modes, you can create two classes: one to hide all properties by default using display: none;, and another to display the clicked property with added styles.

.property.viewing {
  display: none;
}

.property.viewing.active {
  display: block;
  width: 100%;
}

In your click event handler, simply toggle these classes - add .viewing to all properties and .active to the clicked one.

const clickHandler = event => {

  //toggle viewing class on all .property elements
  $(".property").toggleClass("viewing");

  //add "active" class to div that was clicked
  const propertyDiv = event.target.closest(".property");
  propertyDiv.classList.toggle("active");

};

Answer №2

There are 2 important tasks on our hands:

  • Firstly, when a property is clicked for the first time, we need to add the class expand to it and add the class hide to all other properties.
  • Secondly, if a property is clicked for the second time, we should remove the class expand from it and also remove the class hide from all other properties.

It seems like you were heading in the right direction. Just remember to utilize a class for display:none and use it to easily target the clicked element. You can then use parent() to navigate to the level where you want to add or remove classes.

$(document).ready(function() {

  $(".view-now").click(function() {

    /* Check if this property was already expanded */
    if ($(this).parent().parent().parent().hasClass("expand")) {

      /* If yes, remove the expand class */
      $(this).parent().parent().parent().removeClass("expand");

      /* Also un-hide any previously hidden properties */
      $('.property').each(function(i, obj) {
        if ($(this).hasClass('hide') == true) {
          $(this).removeClass('hide');
        }
      });

    } else {

      /* Expand this property */
      $(this).parent().parent().parent().addClass("expand");
      
      /* Hide all properties except for the one that was expanded */
      $('.property').each(function(i, obj) {
        if ($(this).hasClass('expand') == false) {
          $(this).addClass('hide');
        }
      });
    }

  });

})
@import url('https://fonts.googleapis.com/css?family=Muli:800|Open+Sans&display=swap');
body {
  background-color: #e9e9e9;
}

.container {
  max-width: 72em;
  margin: 20px auto;
  padding: 20px;
  background-color: #fff
}

.instructions {
  line-height: 1.4;
}


/**** Your Styles Here ****/

.logo {
  max-width: 300px;
}

.work-container {
  display: flex;
  justify-content: space-between;
}

.property {
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16), 0 3px 6px rgba(0, 0, 0, 0.23);
  border-radius: 5px;
  overflow: hidden;
  position: relative;
  top: 0;
  transition: top ease 0.5s;
  height: 100%;
  width: 300px;
}

.property:hover {
  top: -10px;
}

.property-text {
  padding: 15px;
}

.property-text p:nth-of-type(1) {
  font-family: 'Muli', sans-serif;
  font-size: 25px;
}

.property-text p:nth-of-type(2) {
  color: green;
}

.property-text p:nth-of-type(3) {
  margin-bottom: 30px;
}

.property-text p {
  font-family: 'Open Sans', sans-serif;
  line-height: 15px;
}

.property-text a {
  padding: 10px 25px;
  background-color: #2C64C0;
  box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.225);
  text-decoration: none;
  color: white;
  transition: all 0.3s;
}

.property-text a:hover {
  background-color: #1C4795;
}

.property img {
  max-width: 100%;
  transition: all 0.3s;
  display: block;
  width: 100%;
  height: auto;
  transform: scale(1);
}

.property img:hover {
  transform: scale(1.1);
  overflow: hidden;
}

.hide {
  display: none;
}

.expand {
  width: 100%;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>


<div class="container">

  <div id="your-work-goes-here">
    <div class="work-container">
      <img class="logo" src="https://www.airtightdesign.com/do_not_delete_images_for_coding_test/logo.svg">

      <div class="property">
        <img src="https://www.airtightdesign.com/do_not_delete_images_for_coding_test/property1.jpg">
        <div class="property-text">
          <p>Villa in Cul-de-Sac</p>
          <p>$707 avg/night</p>
          <p>5 BR / 3 BA</p>
          <p>
            <a class="view-now" href="#">View Now <i class="fas fa-chevron-right"></i></a>
          </p>
        </div>
      </div>

      <div class="property">
        <img src="https://www.airtightdesign.com/do_not_delete_images_for_coding_test/property2.jpg">
        <div class="property-text">
          <p>Villa in Jennings</p>
          <p>$456 avg/night</p>
          <p>3 BR / 2 BA</p>
          <p>
            <a class="view-now" href="#">View Now <i class="fas fa-chevron-right"></i></a>
          </p>
        </div>
      </div>
    </div>
  </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

"Exploring the possibilities of integrating Typescript into Material-UI themes: A step-by

I'm experiencing some issues with Typescript pointing out missing properties in the palette section. Although adding //@ts-ignore resolves the problem temporarily, I would prefer to find a cleaner solution. As a newbie to Typescript, here is my attemp ...

Issues with NextJS detecting environmental variables

I recently encountered an issue with my NextJS app running on Next.js v12.2.5 where it appears to be ignoring the environment variables I've configured. To address this, I created a .env.local file with the following content: NEXT_PUBLIC_SERVER_URL=h ...

The POST request is unsuccessful because the GET request is restricted

I'm encountering an issue with a WebMethod in my code behind that I am calling using AJAX. The method functions properly when using a GET request, but I would like to switch to using POST instead. Additionally, I am unsure why the POST request is not ...

What is the best way to ensure the default style is applied when validating?

input { background: white; color: white; } input:in-range { background: green; color: white; } input:out-of-range { background: red; color: white; } <h3> CSS range validation </h3> Enter your age <input type="number" min="1" max= ...

Locate the final element within an array using JavaScript

Provided with a file path like new/lib/java.exe, I am looking to eliminate the root folder 'new' and structure the new path as lib/java.exe. Challenge: After my attempts, I am left with the path as lib/java.exe/ which includes an unwanted "/". I ...

Finding the following index value of an object within a foreach loop

In my code, I have an object called rates.rates: { AUD="1.4553", BGN="1.9558", BRL="3.5256"} And I am using the following $.each loop: $.each( rates.rates, function( index, value ){ console.log(index); }); I have been attempting to also log the n ...

What is the preferred method for updating a variable value - Ajax or PHP?

I'm in the process of creating a dropdown survey for new visitors using cookies to collect data, but I'm a bit confused on how to implement it. If a button is clicked, the onClick event will trigger var answer1 = answer1 + 1 , or something simil ...

Alert: Unauthorized hook call and Exception: Cannot access properties of null (reading 'useState')

I am currently working on a project using ASP.NET Core with React. To bundle my code, I have opted to use Webpack 5. Within the index.jsx file, I have the following code: import { useState } from "react"; function App() { const [value, setV ...

Is there a simple way to create a row of triangle-shaped divs using Bootstrap, similar to the design shown

Is it possible to have a white section and background image in the same row? I am aiming for a layout similar to the example shown https://i.stack.imgur.com/J0S2t.jpg ...

Adding a Timepicker to a Datepicker on a jsp webpage with javascript

I am working on a JSP page that includes a date picker. I want to enhance this datepicker by adding a start time and end time within the calendar itself. How can I achieve this? Additionally, I need to implement validation ensuring that the start time is a ...

Strange outcomes observed with array created from HTML code

html : <input type="text" name="ps[part1['test']]" value="testing multiple array"> Current result : [ps] => Array ( [part1['test'] => testing multiple array ) Expecting result : [ps] => Array ( ...

Using JSON as HTML data within Flexbox for interactive hyperlink rollovers

Utilizing JSON to extract HTML data with unique html tags within Flex has presented a challenge. The limited support for HTML in Flex has made it difficult to implement a basic font color rollover effect on links. While Flex only allows for a few HTML tags ...

Optimizing mobile page layouts with CSS

I'm putting in a lot of effort to ensure that my simple form page is optimized for mobile devices. Although the form is visible, I find myself having to zoom in quite a bit in order to read it. Here's an example: ...

Transmitting HTML and CSS code to the server for seamless conversion into a PDF file

I recently started using a tool called GemBoxDocument that allows me to convert HTML files into PDFs. Their website provides sample code demonstrating how to convert an existing file on a server (source): using System; using System.Linq; using System.Tex ...

Is it possible to achieve the same functionality as :first-child by employing :nth-of-type without a selector?

Currently tackling a console warning related to MUI5/emotion (I believe) I have noticed that the pseudo class ":first-child" might pose potential risks during server-side rendering. It may be worth considering replacing it with ":first-of-type". I wonder ...

Error encountered while implementing onMutate function in React Query for Optimistic Updates

export const usePostApi = () => useMutation(['key'], (data: FormData) => api.postFilesImages({ requestBody: data })); Query Definition const { mutateAsync } = usePostApi(); const {data} = await mutateAsync(formData, { onMutate: ...

Switch out the rowspan attribute in HTML for a CSS alternative

Hello there, I've been experimenting with replacing my table layout with divs and CSS, but I'm struggling to find a way to replicate the behavior of the rowspan attribute. Here is the original code snippet: <table> <tr> <td> ...

Adjust the content of an iframe based on the size of the screen

Hi there, I'm currently facing an issue with an ad that can't be resized. The support team suggested using two different ads - one for mobile and one for desktop. The dimensions of the ads are 720 x 90 and 300 x 100. I would like the ad to automa ...

Interactive PDFs that launch a new browser tab rather than automatically downloading

I am facing an issue with my web API that is returning a JSReport as an encoded byte array. Despite multiple attempts to read the byte array, I keep encountering either a black screen or an error message indicating "failed to download PDF". Interestingly, ...

Remove background image when input form field is in focus

I am currently experimenting with the following approach: $('input').on('click focusin', function() { $('.required').hide(); }); However, it appears that this logic is not functioning as intended. Here is an ...