Tips for resolving a double click issue with a jQuery slide up/down animation

When I click a button, there is an animation that makes a div slide up and then down again. It functions the way I want it to, but the first time you click it, it doesn't work; you have to click twice for it to respond.

Someone recommended using...

event.preventDefault() and event.stopPropagation()

...however, since I'm not very proficient in JavaScript, could someone guide me on where to incorporate this in my current code to solve the issue?

Check out the following demonstration and notice how you need to tap/click twice to trigger it when I only want to click once:

http://jsfiddle.net/8ZFMJ/46/

HTML

<div class="wrapper">

<div class="content-wrapper">
   <div class="padLeft">    
<h2>Project Title</h2> 
<div class="crossRotate"> Open </div>
</div>     
<div class="padLeft">
<p>Paragraph Goes Here</p>
<h3>Play Video</h3>
</div>
</div>    

</div>    

CSS

.wrapper {
width: 100%;
height: 200px;
position: absolute;
overflow: hidden;
margin: 0;
padding:0;
z-index: 1;
}

.content-wrapper {
position: absolute;
z-index: 999;
background: red;
bottom: -90px;
width: 100%;
-webkit-transition: bottom 1s;
-moz-transition: bottom 1s;
transition: bottom 1s;    
}

.crossRotate {
position: absolute;
background-color: blue;
z-index: 1;
cursor: pointer;
}

JS

var clicked=true, animation=false;
$(".crossRotate").on('click', function(){
if(clicked)
{
clicked=false;
$(".content-wrapper").css({"bottom": "-90px"});
}
else
{
clicked=true;
$(".content-wrapper").css({"bottom": "0"});
}
});

Answer №1

To switch the initial value of clicked, simply adjust the code as follows:

var clicked = true;
$(".crossRotate").on('click', function () {
    if (clicked) {
        clicked = false;
        $(".content-wrapper").css({
            "bottom": "-90px"
        });
    } else {
        clicked = true;
        $(".content-wrapper").css({
            "bottom": "0"
        });
    }
});

See demo here: Fiddle

The initial value for bottom is set to -90 via CSS and clicked is initially true. This setup causes the if block to run on the first click instead of the else block.


You might be able to simplify it like this:

var $wrapper = $(".content-wrapper");
$(".crossRotate").on('click', function () {
    $wrapper.css('bottom', function (i, bottom) {
        return parseInt(bottom) ? 0 : -90;
    });
});

Check out the updated demo: Fiddle

Answer №2

If you want to improve the appearance, it's recommended to use more than one element with a specific class:

Check out this DEMO on jsFiddle

$(".crossRotate").on('click', function () {
    $(".content-wrapper").css({
        "bottom": !$(this).data('clicked') ? 0 : "-90px"
    });
    $(this).data('clicked', !$(this).data('clicked'));
});

Another option for better aesthetics is:

View the DEMO on jsFiddle

$(".crossRotate").on('click', function () {
    $(this).closest('.content-wrapper').toggleClass('clicked');
});

CSS:

.content-wrapper.clicked {
    bottom: 0;
}

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

Customize the appearance of buttons and tabs located in the header section

Front end development is new to me and I'm trying to learn, but I've hit a roadblock. I have 4 components - 2 buttons and 2 tabs that I want to style in a header at the top of the page. Specifically, I want one button on the top left with padding ...

Leveraging the "dialogclose" event within jQuery Mobile

Is there a way to change an image once it is clicked and change back when the dialog it links to is closed? I found a potential solution on this site, but after modifying it for my needs, it doesn't seem to work. Can anyone help me figure out what I a ...

What is the best way to retrieve the outcome of a node-sqlite3 query beyond the scope of db.get()?

I'm attempting to validate whether the sha256 hash stored in my sqlite database corresponds with the sha256 hash of the password that the user transmitted to my NodeJS server. The Auth() method is meant to deliver either a true or false result. Is the ...

Navigating with React Router Dom and parsing objects in search parameters

Currently, I am utilizing React Router Dom v6 and require the ability to retain object search parameters within the URL. My current approach involves: const [searchParams, setSearchParams] = useSearchParams(); const allSearchParams = useMemo(() => { ...

The JSON format in ASP.Net Core MVC does not have designated data fields

I am currently facing an issue with my JavaScript code related to cascading dropdowns. The setup involves having one dropdown for selecting a car brand and another dropdown for choosing a specific model under that brand. The functionality should work in su ...

Chrome debugging tool does not refresh page source

This issue has been lingering for quite some time and despite similar questions, I have not come across a satisfactory solution. The problem lies in the fact that the SOURCE used to step through the code does not refresh with every page load. Disabling the ...

Ways to transfer Material-UI FlatButton CSS to a different Button element

I've recently incorporated a loading button object into my website from (https://github.com/mathieudutour/react-progress-button), and now I want to customize it using the Material-UI FlatButton CSS. However, I'm not quite sure how to achieve this ...

Exploring the power of Blowfish encryption with Java and JavaScript

I am facing an issue where I need to encrypt data using Blowfish on a java-based server and send it to a client. Despite successfully encrypting the data, I am unable to decrypt it on the client side. Below is my Java code snippet: byte[] kd = key.getByt ...

Extracting and retrieving information from a complex data structure obtained through an API call

Struggling with this one. Can't seem to locate a similar situation after searching extensively... My goal is to determine the author of each collection associated with a user. I wrote a function to fetch data from an API for a specific user, in this ...

Tips for utilizing the standard search functionality of Select2 while also implementing a remote data source

Even though I am able to populate the dropdown from the data source, there is an issue with filtering the results using the search field at the top. If I make an AJAX request to the API, fetch the data, create <option> elements for each result, and a ...

Navigating through the text in between search restrictions of lookbehind and lookahead can be

Below is the text I am working with. Hello my name is Adam (age: 25) I live in US. Hello my name is Bill (age: 23) I live in Asia. I am trying to extract the age and location using lookahead and lookbehind. The desired output format should be as follows ...

Breaking a line within a list item will create additional spacing between the lines

Is there a way to break a line <br/> inside a <li> tag? For example: First line second line Second list item Third list item I've tried setting margin and padding to 0, but I still get an unwanted space between the lines. Any suggesti ...

JavaScript Transcriber

Hey there! I'm currently attempting to compile some JavaScript code that I have written in a textarea and get the output of this code. I've tried using the eval() method, but unfortunately, I haven't been able to get the complete response. C ...

"Vercel encounters a read-only file system when trying to change file

Hey folks, I've been using vercel for deploying my project. There's an issue with one of the dependencies in my NextJS project, which is located inside the node_modules folder. This dependency is supposed to read and write files within its own di ...

Ways to initiate SVG animations using Angular Component functions?

I am currently working on a project where I want to incorporate an animation that reflects the sorting process of an array of numbers. However, despite successfully sorting the numbers in the array, I am facing challenges with triggering the animations. I ...

The hover effect is not activated by the mouse movement event

I previously encountered an issue related to flickering with an absolute div when moving my mouse, which I managed to resolve by increasing the distance between my mouse pointer and the div. Now, I am working on the next phase of my project: My goal is t ...

Indeed, verification of an array - values are mandatory only when the array exceeds a length of 1

In my form, each row contains 2 dropdowns and I have the ability to dynamically add or remove rows except for the first one. My goal is to allow form submission only if there is one pre-rendered empty row, otherwise the form should not be able to submit if ...

Position the select tag adjacent to the textbox

Looking for assistance on how to arrange the <select> tag beside the "Desired Email Address" field within my email registration form. I believe a modification to the CSS code is necessary. Below you will find the HTML and CSS (snippet) related to th ...

After successfully building with Vite, an error occurs stating "TypeError: can't convert undefined to object." However, during development with Vite, everything functions flawlessly

Currently, I am utilizing Vite in conjunction with React and Typescript for my project. Interestingly, when I execute 'vite dev', the live version of the website works flawlessly without any errors showing up on the console. However, things take ...

Combining array objects in Node.js

Received an array in the request body: [ { "month": "JUL", "year": "2018" }, { "month": "JAN", "year": "2018" }, { "month": "MAR", "year": "2018" } ] The input consists of two parameters (month:enum and ye ...