I am trying to build basic animation of two divs with jQuery .toggle() function.

The main concept is to toggle the visibility of two additional divs with map and contact form.

I made everything working as I wanted but noticed a bug.

Here is the link to the demo on Codepen -- Link

To see the bug just hit 'Location' then 'Get in touch' and again 'Location'.

I think that it could be fixed with simple if else function, but I can't come up with the right solution since I don't know JS that much.

Anybody, help me, please. Thanks in advance!

1 Answers

0
user1147618 On Best Solutions

How about something like this. Basically just keeping track of whether the form and map are showing, and only doing the animation when necessary.

$(document).ready(function() {

// toggle map visibility
$("#toggle-map").click(function() {
    $(".target-map").toggle('left');
});
// toggle contact form visibility
$("#toggle-form").click(function() {
    $(".target-form").toggle('left');
});

var showingMap = false
var showingForm = false

function animate() {
    var changeInLeft = !showingMap && !showingForm ? "0px" : "-245px"
    $(".left-part").stop().animate({ left: changeInLeft }, 100);
}

// hide one on click 
$(document).on("click", "#toggle-map", function(event) {
    $(".target-form").hide();
    event.preventDefault();
    if (showingForm) showingForm = !showingForm;
    showingMap = !showingMap;
    animate();
});

$(document).on("click", "#toggle-form", function(event) {
    $(".target-map").hide();
    event.preventDefault();
    showingForm = !showingForm;
    if (showingMap) showingMap = !showingMap;
    animate();
});

});