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

Performing a Search Operation using AJAX with Elasticsearch

I've been struggling to find the correct method for requesting data from elasticsearch using a jQuery AJAX call. I keep encountering parsing errors or getting all documents in the index instead of my intended results. $(document).ready(function() ...

Ways to display a checked or unchecked checkbox in react depending on a boolean value obtained from an API

Is there a way to display a checked or unchecked checkbox in react jsx depending on a boolean value retrieved from an api? ...

DevExpress popup remains contained within the iframe and does not overflow beyond its boundaries

My dilemma involves incorporating a FilterControl within an iframe popup. My issue arises when using the column selector (or any other DevExpress combobox), as the popup remains confined within the frame without extending beyond its borders. I am seeking a ...

Unusual activity observed in HTML5 contenteditable functionality

Within a list item, I have a span element. <ul> <li>text part 1 <span class="note">this is a note</span> text part 2 </li> <li>text part 3</li> </ul> When you double click on th ...

List arranged in order with a hyperlink in the center and an image positioned on the right side

I am trying to create an ordered list with a link to an article in the middle and a small png image file positioned directly to the right of it. For reference, here is an image depicting the exact type of list that I am aiming to achieve: https://i.stack. ...

Ways to merge values across multiple arrays

There is a method to retrieve all unique properties from an array, demonstrated by the following code: var people = [{ "name": "John", "age": 30 }, { "name": "Anna", "job": true }, { "name": "Peter", "age": 35 }]; var result = []; people. ...

Overlap bug with Flash content

In both Google Chrome (16.0.912.75 m) and Safari (5.1.1), I am encountering the well-known flash / html overlay issue. Despite setting the wmode attribute to transparent as suggested here and here, along with trying opaque, the problem persists. Following ...

Using jQuery AJAX to dynamically update two sections of a webpage by executing scripts embedded in the server response

I'm currently utilizing jQuery AJAX to load and update a specific section of my webpage. Below is the jQuery function in my main page: function updateCategories(){ catList = $('#cat_list'); catList.hide(); //sending the post re ...

Looking for a way to easily swipe through videos?

My mobile phone viewport displays a series of pictures and videos, with the swipeleft/right function enabled for browsing. However, I noticed that while the swipe feature works fine for images, it stops functioning when a video is displayed. Can anyone p ...

Stop Ajax from activating jQuery function

Upon examining our Drupal site, we discovered a straightforward jQuery script that inserts a div class containing content: (function($) { Drupal.behaviors.myHelpText = { attach: function (context, settings) { //code begins //adjusting placeholder ...

Applying custom CSS designs to images using Thymeleaf

Currently working on a web application using Spring MVC and Thymeleaf for templating. I'm struggling to figure out how to apply rules to an image, especially when using an external CSS file. I have tested code that works: page.html <a class="nav ...

Mongooses do not clutter the array with unnecessary lines

I need help generating a sorted list from the database. Here is my current code: const subs = await Sub.find({}, {userName: 1, score: 1, _id: 0}).sort({ score: 'desc' }); The output I am getting looks like this: { userName: 'test1', ...

What is the method for assigning a maximum value of 300 to a bootstrap progress bar?

I'm in the process of creating a progress bar with a maximum value of 300, but I'm struggling to set it at 300. It currently works for a maximum value of 100, but I want it to be 300. Here's what I've attempted: <div class="mt-3 pr ...

Running the command "nexrjs create next-app" successfully generates all the necessary directories for the

After trying to install NextJS using both methods npm install next react react-dom and npx create-next-app appname, I noticed that my project directories are different from what they are supposed to look like: Instead of having pages, api(_app.js, index.j ...

What is the best way to connect a line from the edge of the circle's outermost arc?

I am attempting to create a label line that extends from the outermost point of the circle, similar to what is shown in this image. var svg = d3.select("body") .append("svg") .append("g") svg.append("g") .attr("class", "slices"); svg.append("g") ...

Identifying the server control ID on the master page with the help of jQuery

My Asp.net Master Page includes an adrotator element. <asp:AdRotator ID="adr" AdvertisementFile="~/Adrotator.xml" Width="180px" Height="200px" runat="server" Target="_self" /> I have implemented a jquery script to rotate the ADS, b ...

Creating a table with a static first column and vertical text positioned to the left of the fixed column

To create a table with the first column fixed, refer to this fiddle link: http://jsfiddle.net/Yw679/6/. You also need a vertical text to be positioned to the left of the fixed column in a way that it remains fixed like the first column. The disparities be ...

Drop down list not showing array values

I am attempting to populate a dropdown list with elements from an array using the Document Object Model (DOM) within a for loop. However, I keep encountering an error stating that the dropdown list is null. Here is the JavaScript code I am using: var st ...

Showing data from a MySql database using an HTML table

I am currently working on a pop-up form that captures user data and stores it in a MySQL phpmyadmin table. My goal is to have this data displayed in an HTML table once the popup form is closed. After submitting the form, I am redirected back to the homepag ...

Issue with custom page not displaying summary image in Moodle

Whenever I try to fetch a summary image on my customized page, it does not show the image's name and instead displays a small icon image. echo format_text($course->summary); Click here for an example image ...