"Uncovering the mystery of the missing element in Jquery's open

I have developed a click-to-show feature that opens and closes a div from left to right. You can view the demo here on jsfiddle.net

In the demo, you will find a green-colored div. Upon clicking this div, another div opens from left to right.

An interesting aspect of this interaction is that when the green button is clicked, its class changes automatically along with the HTML text. (Click To Show Slide Left In to Close)

My goal is to make the green color div toggle the opening and closing of the left div - i.e., first click to open the left div and second click to close it with animation.

Can someone help me achieve this functionality? What am I missing in my demo?

This is the code snippet:

JS

$(".click_open_close").click(function(){
   var id = $(this).data("id");
    $(".left_in").animate({width:"100%"}, 200).find(".aa").animate({width:"100%"}, 200);
    $(".click_open_close").html("Close");
    $(".r").removeClass("click_open_close");
    $(".r").addClass("pp");
});
$(".pp").click(function(){
   $(".left").animate({width:"0%"},200);
   $(".left_in").animate({width:"0%"},200);      
});

HTML

<div class="test_container">
  <div class="left">
      <div class="left_in"><div class="aa">ss</div></div>
  </div>
  <div class="r click_open_close" data-id="100">Click To Show Slide Left In</div>
</div>

CSS

.test_container{
  /* CSS styles here */
}
/* Other CSS rules go here */

Answer №1

Why complicate things by constantly changing the class of your click? Take a look at this DEMO and refer to the code below.

To simplify, just include an HTML data-* attribute in your button to define its state like so:

<div class="r click_open_close" data-state="close" data-id="100">Click To Show Slide Left In</div>

JS

$(".click_open_close").on('click',function(){
       var id = $(this).data("id");
       var state=$(this).data("state");
       if(state==="close")
       {
           $(this).data("state",'open');
           $(".left_in").animate({width:"100%"}, 200).find(".aa").animate({width:"100%"}, 200);
           $(this).text('Close');
       }
       else
       {
           $(this).data("state",'close');
           $(".left_in").animate({width:"0%"}, 200).find(".aa").animate({width:"0%"}, 200);
           $(this).text('Click To Show Slide Left In');
       }
});

Answer №2

When you initially add the click event, your pp class is not within the DOM, so you should utilize .on instead:

$(".test_container").on("click", ".click_open_close", function(){
   var id = $(this).data("id");
    $(".left_in").animate({width:"100%"}, 200).find(".aa").animate({width:"100%"}, 200);
    $(".click_open_close").html("Close");
    $(".r").removeClass("click_open_close");
    $(".r").addClass("pp");
});
$(".test_container").on("click", ".pp", function(){
   $(".left").animate({width:"0%"},200);
   $(".left_in").animate({width:"0%"},200);      
});

Check out the updated fiddle here

Answer №3

When it comes to diversity, I opted for a more straightforward approach, even though there are more advanced methods available.

Give this a shot:

var isOpened = false,
    button = $('.r'),
    leftDiv = $('.left_in');
button.click(function () {
    if (isOpened) {
        close();
    } else {
        open();
    }
});


function open() {
    leftDiv.animate({
        width: "100%"
    }, 200).find(".aa").animate({
        width: "100%"
    }, 200);
    button.text("Close");
    isOpened = true;
}

function close() {
    leftDiv.animate({
        width: "0%"
    }, 200);
    button.text("Click To Show Slide Left In");
    isOpened = false;
}
.test_container {
    display: block;
    position: absolute;
    height: auto;
    bottom: 0;
    top: 0;
    left: 0;
    right: 0;
    max-width: 980px;
    min-width: 300px;
    margin-top: 20px;
    margin-bottom: 20px;
    margin-right: auto;
    margin-left: auto;
    background-color: #000;
    box-shadow: 0 1px 1px 0 rgba(0, 0, 0, .06), 0 2px 5px 0 rgba(0, 0, 0, .2);
    -webkit-box-shadow: rgba(0, 0, 0, 0.0588235) 0px 1px 1px 0px, rgba(0, 0, 0, 0.2) 0px 2px 5px 0px;
    border-radius: 3px;
    -webkit-border-radius: 3px;
    -o-border-radius: 3px;
    -moz-border-radius: 3px;
    min-height: 140px;
}
.left {
    display: block;
    position: absolute;
    float: left;
    width: 30%;
    overflow: hidden;
    padding: 0px;
    bottom: 0;
    top: 0;
    left: 0;
    background-color: red;
    border-right: 1px solid #d8dbdf;
    -webkit-border-top-left-radius: 3px;
    -webkit-border-bottom-left-radius: 3px;
    -moz-border-radius-topleft: 3px;
    -moz-border-radius-bottomleft: 3px;
    border-top-left-radius: 3px;
    border-bottom-left-radius: 3px;
    transition: opacity 2s, width 2s, left 2s, font-size 2s, color 2s;
}
.left_in {
    z-index: 999 !important;
    position: absolute;
    float: left;
    width: 0%;
    height: 100%;
    background-color: #f7f7f7;
    opacity: 0;
    -webkit-animation-duration: 0.9s;
    animation-duration: 0.9s;
    -webkit-animation-fill-mode: both;
    animation-fill-mode: both;
    -webkit-animation-name: slideLeft;
    animation-name: slideLeft;
    -webkit-animation-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
    animation-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
}
@-webkit-keyframes slideLeft {
    0% {
        -webkit-transform: translateX(25rem);
        transform: translateX(25rem);
        opacity: 0;
    }
    100% {
        -webkit-transform: translateX(0);
        transform: translateX(0);
        opacity: 1;
    }
}
@keyframes slideLeft {
    0% {
        -webkit-transform: translateX(15rem);
        transform: translateX(15rem);
        opacity: 0;
    }
    100% {
        -webkit-transform: translateX(0);
        transform: translateX(0);
        opacity: 1;
    }
}
.aa {
    background-color: #f7f7f7;
    /*background-color: #dfdfdf;
  background-image: -webkit-linear-gradient(top,#dddbd1,#d2dbdc);
  background-image: linear-gradient(top,#dddbd1,#d2dbdc);*/
    width: 0;
    top: 0;
    border-radius:0%;
    z-index: 1000;
    display: -webkit-box;
    display: -webkit-flex;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-orient: vertical;
    -webkit-box-direction: normal;
    -webkit-flex-direction: column;
    -ms-flex-direction: column;
    flex-direction: column;
    height: 100%;
    overflow: hidden;
    position: absolute;
    right:0;
}
.click_open_close {
    right:0px;
    padding:10px;
    color:#fff;
    position:absolute;
    background-color:green;
    cursor:pointer;
}
.pp {
    right:0px;
    padding:10px;
    color:#fff;
    position:absolute;
    background-color:green;
    cursor:pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test_container">
    <div class="left">
        <div class="left_in">
            <div class="aa">ss</div>
        </div>
    </div>
    <div class="r click_open_close" data-id="100">Click To Show Slide Left In</div>
</div>

You can also toggle a class and implement CSS transitions along with many other options. However, based on the provided code snippet, I chose to keep it simple for you.

Answer №4

Although jcubic has already corrected your Fiddle, I wanted to mention that there is a more efficient and elegant way to achieve the same result using toggleClass() and CSS transitions. Here is an alternative approach:

$('#button').on('click', function() {
  $('#banner').toggleClass('unfolded');
});
html,
body {
  position: relative;
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}
.wrapper {
  position: relative;
  height: 100%;
}
.banner {
  position: absolute;
  top: 0;
  right: -140px;
  transition: right 0.5s;
  width: 150px;
  padding: 12px;
  background-color: #000;
  color: #fff;
}
.button {
  cursor: pointer;
  font-weight: bold;
}
.banner.unfolded {
  right: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="wrapper">
  <div class="content">
    <h1>Some content</h1>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eius iusto, et modi nulla officiis repellat necessitatibus laborum, enim consectetur sunt doloribus tempora esse illum eum incidunt veritatis, quaerat, nostrum eos?</p>
  </div>

  <div class="banner" id="banner">
    <div class="button" id="button">>></div>
    <ul>
      <li>Link</li>
      <li>Link</li>
      <li>Link</li>
      <li>Link</li>
      <li>Link</li>
    </ul>
  </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

Navigating with Node.js: Understanding how to showcase the response data within a list structure

I am brand new to working with node.js and I'm looking to display the data I receive as a response on my webpage. Currently, I can see the output in my console. Is there a way to show this data on my actual page? GET Request: app.get('/bestell_ ...

How can I streamline a kendo UI MVC project by eliminating unnecessary components?

After switching my MVC 5 project to utilize Kendo UI, I've noticed a significant increase in the number of files being used. Since there is no need for supporting other cultures at the moment, can I confidently delete the files within the messages an ...

What is the best method for determining the ID or class of a div element dynamically?

My issue involves a scrolling div that dynamically loads data using ajax and json from an API as you scroll horizontally. Currently, I have multiple scrolling divs on a single page. The problem arises when I need to inform jQuery about the ID of the div b ...

CSS universal selector not applying to images

I have scoured through different resources and they all seem to echo the same information. Here is the code in question: *:not(img) { display: none; } Its intended purpose is to hide everything on the page except images. However, it seems to be hiding t ...

Generating dynamic div elements using jQuery

I am currently working on developing a button that will automatically generate pre-formatted divs each time it is clicked. The divs consist of forms with fields that should already be populated with data stored in JavaScript variables. Example: <d ...

Resize images within a button using table cell size in Bootstrap

I am looking to create a row of buttons within a table, where each button is represented by an image and has a transparent border/background. To achieve this, I placed each button in one of the 10 remaining cells of a table using <td class="col-sm ...

What is the best way to retrieve information from a local JSON file and store it in the state of

I am currently working on a project to develop a movies/series search app using Next.js and React based class components. I have successfully imported JSON content and displayed it using the map function as shown below: <div> {Appletv.shows.map(( ...

having difficulties retrieving the attribute value through jquery

I'm currently implementing this method on rowmouseevent. When I use $get(eventArgs.get_id()), the output is: <tr class="normal" data-value="normal" id="ctl00_ContentPlaceHolder1_UserGrid_grdusergrid_ctl00__0" style="height:30px;" /tr> How can ...

The bidirectional bindings within the component are malfunctioning

I just started learning Angular and I'm currently working on a small project. After following tutorials on two-way bindings, I attempted to implement it in my project. However, when I try to set values in the HTML for my component, it doesn't see ...

Increment by 1 until a specific number is reached instead of displaying all numbers within an array

I have an array of numbers and for each number in the array, a request is sent to an external website using the number as a URL variable. The webpage content is then displayed. Instead of manually listing the numbers (1, 2, 3, 4, 5, 6, 7, 8, 9) in the arr ...

Mapping JSON data containing a collection of objects as an observable, rather than as an observable array, is an

When developing my webpage, I needed to receive a viewmodel of a user account via Json. The data includes essential user details such as real name and email address. Additionally, I wanted to display (and modify) the groups that the user belongs to, along ...

I need assistance in locating an error; the error message states that $ is not defined and an object is expected

Issue with $ not being defined, object expected.. I am trying to verify if all sets of radio buttons are checked when a button is clicked! Please help. <script type="text/javascript> $(document).on('click', 'form', function () { ...

Centered horizontally are images that have been floated

How can I align images with different widths when they are all floated right? I want them to be aligned vertically below each other. For the best display, please view in fullscreen on your computer as the example window is small. .compressor{ height: 1 ...

When using the jQuery datepicker on dynamically generated input fields, the selected date automatically updates the first input field

I am currently integrating date inputs with attached datepicker functionality. The issue I am facing is that when I select a date in the first input and proceed to pick another date in the second or subsequent inputs, the last selected date appears in the ...

What is the best way to format a lengthy SQL query as a JavaScript variable?

I have a lengthy SQL query that needs to be converted into a JavaScript variable. The contact information is spread across separate rows using the + character. However, the SQLite plugin is displaying a parsing error: What is the correct way to format t ...

Having difficulty adding spacing between the border and the content of a label

I've designed labels to function as buttons for radio buttons. I'm struggling to figure out why I can't add padding between the border and the background color content. Should I reconsider the structure of the radio/label elements, or is th ...

The functionality of both P and H1 tags seems to be malfunctioning

Can someone help me with changing the font family and size of my paragraphs and headings (p and h1)? Any assistance would be greatly appreciated. Feel free to review my code for any other errors as it has been a while since I last coded. html, body { ma ...

"Classes can be successfully imported in a console environment, however, they encounter issues when

Running main.js in the console using node works perfectly fine for me. However, when I attempt to run it through a browser by implementing an HTML file, I do not see anything printed to the console. Interestingly, if I remove any mentions of Vector.ts fro ...

The CSS focus-within and hover properties are not functioning as expected

How can I make the search tags visible (the buttons above the text input field) when the search bar below them is clicked? I've tried using :hover, :focus, and :focus-within, but none of them seem to be working. Can someone help me figure out the issu ...

Looking for assistance with troubleshooting CSS issues specifically in Internet Explorer

Hey there! I've been working on a landing page and it's looking good in Safari, Firefox, and Chrome. The only issue is that the layout is all messed up in IE (any version). If any of you experts could take a look at it and give me some suggesti ...