Having trouble with jQuery toggle fade: Unable to make the div fade in/out when toggling

Is there a way to modify the functionality of my black button so that when clicked, the red div fades out while the blue div fades in? Right now, clicking the button switches between the two divs without any fading effect.

Fiddle: http://jsfiddle.net/ddac5391/1/

HTML

<a id="contact-button" href="#">Get in touch</a>

<div id="primary"></div>
<div id="contact-keebs"></div>

CSS

#contact-button {
    background: #000;
    background-size: 24px;
    color: #fff;
    text-decoration: none;
    text-transform: uppercase;
    font-weight: bold;
    padding: 10px 20px;
    position: absolute;
    right: 0;
    top: 0;
    z-index: 1;
}
#primary {
    background: red;
    height: 200px;
    position: absolute;
    width: 200px;
}
#contact-keebs {
    background: blue;
    display: none;
    height: 200px;
    position: absolute;
    width: 200px;
}

JS

var c = 0;
$('#contact-button').click(function (e) {

    e.preventDefault();

    if (c++ % 2 == 0) {

        $(this).addClass('work-button').text('Work');
        $('body').addClass('contact-content');
        $('#contact-keebs').stop().fadeIn(500).show();

    } else {

        $(this).removeClass('work-button').text('Get in touch');
        $('body').removeClass('contact-content');
        $('#contact-keebs').stop().fadeOut(500).hide();

    }
});

Answer №1

To ensure that the fadeIn/fadeOut animation completes before stopping, it is important to eliminate the use of .show() and .hide() functions. Instead, incorporate .finish() before calling .stop().

If .finish() is not utilized, the div elements may get stuck at varying opacity levels. Check out this Demo to see this issue in action (try clicking rapidly).

$('#contact-keebs').finish().stop().fadeIn(500);

and

$('#contact-keebs').finish().stop().fadeOut(500);

Updated Fiddle

Complete Demo:

var c = 0;
$('#contact-button').click(function(e) {
  e.preventDefault();
  if (c++ % 2 == 0) {
    $(this).addClass('work-button').text('Work');
    $('body').addClass('contact-content');
    $('#contact-keebs').finish().stop().fadeIn(500);
  } else {
    $(this).removeClass('work-button').text('Get in touch');
    $('body').removeClass('contact-content');
    $('#contact-keebs').finish().stop().fadeOut(500);
  }
});
#contact-button {
  background: #000;
  background-size: 24px;
  color: #fff;
  text-decoration: none;
  text-transform: uppercase;
  font-weight: bold;
  padding: 10px 20px;
  position: absolute;
  right: 0;
  top: 0;
  z-index: 1;
}
#primary {
  background: red;
  height: 200px;
  position: absolute;
  width: 200px;
}
#contact-keebs {
  background: blue;
  display: none;
  height: 200px;
  position: absolute;
  width: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a id="contact-button" href="#">Get in touch</a>
<div id="primary"></div>
<div id="contact-keebs"></div>

Answer №2

I have found a solution. You no longer need to include the show and hide functions after using fadeOut and fadeIn methods: http://jsfiddle.net/ddac5391/6/

if (c++ % 2 == 0) {

            $(this).addClass('work-button').text('Work');
            $('body').addClass('contact-content');
            $('#contact-keebs').stop().fadeIn(500);

        } else {

            $(this).removeClass('work-button').text('Get in touch');
            $('body').removeClass('contact-content');
            $('#contact-keebs').stop().fadeOut(500);

        }

Answer №3

Make sure to use

$('#contact-keebs').stop().fadeOut(500).show();

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

"Implementing jquery autocomplete feature with the ability to fetch data from

Currently, I am utilizing jquery's ajax functionality to retrieve data from an external php file. The retrieved data is then intended for use in the autocomplete feature. However, instead of displaying individual values from the array in the php file ...

Organizing a Vue.js SPA project: Implementing Vuex store and API calls efficiently

Here is how I have organized the structure of my Vue app: components/ article/ AppList.vue common/ AppObserver.vue NoSSR.vue layout/ AppFooter.vue AppHeader.vue ui/ AppButton. ...

The absence of underlines for <a href> and <u> is causing an issue

Below is a snippet of code that I am working with: echo "<form> <div id=\"error\"align=\"center\">"; echo "You've either entered the incorrect <b>username</b> or incorrect <b>passwor ...

Is it possible to determine which specific JavaScript function initiated the ajax call with jQuery's ajaxComplete function?

I currently have the .ajaxComplete event set up for a few elements in this manner: $("#ElementId").ajaxComplete(function (a, b, c) { }); The issue I am facing is that I have multiple $.ajax calls in my script triggered by different functions. I do not wa ...

Organize an array of objects in JavaScript into a structure with nested children

I am facing a challenge with organizing an array of objects based on parentId and sort values. I need to create a nested array with 'children' and ensure proper sorting. Consider the following data: [{ id: 1, sort: 2, parentId: null ...

Is there a advantage to using Angular's component style encapsulation for improved performance?

Recently, I came across the styling methods of Angular 2 which allows you to directly include your styles within the component. If you want to explore more on this topic, check out loading styles. There are two options for style encapsulation in Angular 2 ...

Tips for sending form data via ajax to a python script?

I'm running into an issue with a python program and an ajax request. I am attempting to retrieve data from my Javascript in the python program, but the usual method of using .getfirst(field name) isn't working, which I believe is due to the reque ...

Converting a string value into an object in Javascript using a command that functions similarly to eval in Python

When working with Python, the stringValue variable is often assigned as a string: stringValue = '{"DATA":{"VERSION":1.1, "STATE":True, "STATUS":"ONLINE"}}' To convert this string into a Python di ...

How can I resolve the issue of React not identifying the prop on a DOM element?

Currently, I am learning React and facing an issue with a warning message: "react-dom.development.js:86 Warning: React does not recognize the isSelected prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell i ...

If the height of the window changes, then update the CSS height accordingly

Here is the code that I am using: $(document).ready(function() { $('body').css('overflow', 'scroll'); var heightWithScrollBars = $(window).height(); $('body').css('overflow', 'auto') ...

"Creating a dynamic TreeList in Ignite UI by linking pairs of names and corresponding

I recently developed a drag and drop tree list inspired by the tutorial on IgniteUI website. The main tree list functions properly, but I encountered an issue with the child nodes displaying as undefined, as illustrated in the image below: https://i.sstat ...

Guide to looping through a map arraylist in JavaScript

Here is a sample map arraylist. How can I access this arraylist using JavaScript from within pure HTML? And how can I iterate over this list? <%@page import="org.json.simple.JSONObject"%> <%@page import="org.json.simple.JSONArray"%> <% JSON ...

Building an Angular module that allows for customizable properties: A step-by-step guide

I am in the process of developing an AngularJS module that will simplify interactions with my product's REST API. Since my product is installed on-premise, each user will need to provide their own URL to access the API. Therefore, it is essential that ...

Connect the front end files, including HTML, CSS, and JavaScript, to the Node.js backend

I'm a beginner in web development and recently completed an online course on node.js and express. However, the course didn't cover how to add HTML, CSS, and JS files when using Node. I attempted the following: var express = require('expres ...

The process of setting up React in the terminal becomes tricky when the VS code editor is directing to a non-existent path

Issue with VS Code editor not recognizing existing path Recently attempted to install React using the npx command in the terminal, following steps from various tutorials on YouTube. Despite trying all suggested methods, the installation didn't succee ...

jquery technique for toggling a single button

My goal is to use jQuery to toggle a button rather than the typical paragraph toggling. I want the button to appear and disappear when clicked, while also increasing the "score" upon each click and decreasing it when the button reappears. Can anyone guide ...

Is there a way to sort a table using a dropdown menu selection as a filter?

I am currently working on a project that involves a table with three columns, which are typically populated from a SQL database. My goal is to filter the third column based on the value selected from a dropdown menu. I came across a helpful tutorial on W3 ...

Removing element from database using php/ajax

My PHP script dynamically generates rows of <div> elements with 5 items per row. My next goal was to create a select form with dynamically generated options for deleting the selected item. However, I encountered an issue where the dynamically genera ...

Using cascading style sheets to switch a page into editing mode

Is it possible to change the view of a page after clicking a button without using javascript, and instead relying solely on CSS? I want to display a page with information where users can click an edit button and make changes within the same view rather th ...

The image wrapping feature within a div element will only function properly when there are more than one line of text present

I have come across a strange issue that I am struggling to solve. I have an image within a div with the float: left; attribute, but this styling only seems to work when the div has more than one line of text. When the div contains just one line, it ends ...