Slide toggle in jQuery reveals itself briefly before vanishing

Check out the codepen here: https://codepen.io/anon/pen/gRJEwx

Essentially, with jQuery toggle 'slide', the div slides in and right back out. It seems to only happen every second or third time the button is pressed. The first try never triggers it, but after clicking the back button, it tends to work on the second or third attempt.

$('#go').on('click', function() {
  $('#s1').fadeOut('slow', function() {
    $('#s2').toggle('slide', {
      direction: 'right'
    }, 800, function() {

      $('#s2 .back').on('click', function() {
        $('#s2').fadeOut('slow', function() {
          $('#s1').toggle('slide', {
            direction: 'right'
          }, 800);
        });
      });
    });
  });
});
body {
  overflow: hidden;
  width: 400px;
  background: gray;
  height: 400px;
}

#s1,
#s2 {
  width: 100%;
  height: 100%;
}

#s1 {
  padding: 20px;
  display: block;
  background: purple;
}

#s2 {
  padding: 20px;
  display: none;
  background: blue;
}

#s3 {
  display: none;
  background: black;
}

#go,
#go2 {
  width: 400px;
  padding: 10px 0;
  margin: 20px auto;
  text-align: center;
  font-weight: bold;
  background: white;
}

.back {
  background: white;
  font-weight: bold;
  width: 300px;
  padding: 10px 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="s1">
  <div id="go">GO TO SCREEN2</div>
</div>
<div id="s2">
  <div class="back">GO BACK</div>
</div>

On the initial attempt, everything works fine. However, when trying for the second time, the second screen briefly shows up and then disappears immediately. Any suggestions on how to make it slide and remain visible until the back button is clicked?

Answer №1

Every time you click on #go, a new click event for #s2 .back is being bound. It's better to move it out of the click event.

Also, remember how .on works. It should be bound to a static element, so the correct form is

$(staticElement).on(event, dynamicElement, callback)
. If your #go element is dynamically added and removed using JavaScript, the provided form will not work correctly.

$(document).on('click', '#go', function() {
  $('#s1').fadeOut('slow', function() {
    $('#s2').toggle('slide', {
      direction: 'right'
    }, 800);
  });
});


$(document).on('click', '#s2 .back', function() {
  $('#s2').fadeOut('slow', function() {
    $('#s1').toggle('slide', {
      direction: 'right'
    }, 800);
  });
});
body {
  overflow: hidden;
  width: 400px;
  background: gray;
  height: 400px;
}

#s1,
#s2 {
  width: 100%;
  height: 100%;
}

#s1 {
  padding: 20px;
  display: block;
  background: purple;
}

#s2 {
  padding: 20px;
  display: none;
  background: blue;
}

#s3 {
  display: none;
  background: black;
}

#go,
#go2 {
  width: 400px;
  padding: 10px 0;
  margin: 20px auto;
  text-align: center;
  font-weight: bold;
  background: white;
}

.back {
  background: white;
  font-weight: bold;
  width: 300px;
  padding: 10px 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div id="s1">
  <div id="go">GO TO SCREEN2</div>
</div>
<div id="s2">
  <div class="back">GO BACK</div>
</div>

Answer №2

Make sure to separate the click event listeners for better organization and readability:

$('#go').on('click', function(){
    $('#s1').fadeOut('slow', function(){
        $('#s2').toggle('slide', {direction: 'right'}, 800);
    });
});

$('#s2 .back').on('click', function(){
    $('#s2').fadeOut('slow', function(){
        $('#s1').toggle('slide', {direction: 'right'}, 800);
    });
});

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

Tips for increasing a numerical value with jQuery within a footnote extension for redactor.js

Currently, I am in the process of developing a plugin for redactor.js that will enable users to include footnotes. The end goal is to have these footnotes stored in a separate table in the database; however, as of now, it's just a mockup for a larger ...

What is the best way to adjust Material UI Grid properties according to the screen size?

I am working with Material UI and have a grid on the homepage that needs to maintain certain properties regardless of screen size. However, I want to apply a negative margin when the screen reaches 1200px or larger (lg). Currently, the grid is set up like ...

The Javascript class is throwing a syntax error because it's not okay

I'm using this code snippet: Class Addition { constructor () { } add (a = 1, b = 1) { console.log(a+b) } } but it's giving me an error Uncaught SyntaxError: Unexpected identifier ...

Is there a way to implement a css/javascript property specifically for a div that is selected in the url?

Take for instance the scenario where I possess the URL example.com/#foo. In this case, CSS styling will be directed to the div with the id foo. If achieving this solely in CSS is not feasible, what methods in JavaScript or jQuery can be used efficiently ...

Why does the page reload before reaching the server-side processing page? Any thoughts on what might be causing this?

Utilizing a JSON object and multiple ajax calls to a webmethod for data insertion into the database, we encountered an issue where the page reloads before processing the data. This results in errors indicating that certain parameters are required but not s ...

Positioning the box in the middle of pages

I have a website page at the following link: However, the content is not centered on the screen. Here are the codes I'm using: <div class="section_inner"> <div class="container"> <div class="row"> <?ph ...

Is it possible to prevent the text from appearing in the text box when a button is

I have successfully implemented a feature where clicking on the button (click on me) in HTML displays a textbox along with another button (show) on the screen. The text written in the textbox is visible when the show button is clicked. However, after the i ...

CORS blocking Axios POST request to Heroku causing a Network Error 503

Using the MERN Stack, everything was functioning correctly until modifications were made to the UI (such as relocating code to different components and altering styles). The issue lies with a specific POST request, while other requests that utilize Axio ...

Is it preferable to include in the global scope or the local scope?

When it comes to requiring a node module, what is the best approach? Should one declare the module in the global scope for accuracy and clarity, or does declaring it in the local scope make more sense? Consider the following examples: Global: let dns = r ...

Passing Props in Material-UI v5xx with ReactJS: A Beginner's Guide

Struggling with the fact that useStyle() isn't functioning properly in my material-UI v5xx version, I found myself at a loss on how to pass props in this updated edition. In Material-UI v4, it was as simple as: const Navbar = () => { const [open ...

Navigating a JSON message received from a websocket: Best practices

How can I cycle through various types of JSON messages received from WebSocket and trigger a function based on the type to modify observables in MobX? Can anyone assist with this? For instance, one of the simple messages looks like this: { name: "as ...

Creating various layouts in Ember.js allows for flexibility and customization in

Currently working on an emberjs project and aiming to incorporate two distinct layouts - one for the main application template and another for specific templates. I prefer not to have all views rendered within the application template, similar to how you ...

Generate a visual representation in JavaScript/Angular by counting from 0 to 1000

Here are my numbers: https://i.sstatic.net/S31aX.jpg I am trying to count from 0 to 1,000 using images and want to separate them with commas. For instance, when the number is equal to 1, I want to display 1.png. What's the most efficient way to ac ...

The function firebase__webpack_imported_module_2__.auth.createuserwithemailandpassword does not exist

I'm facing an issue with my Firebase setup in my code. The browser console is showing that auth.createUserWithEmailAndPassword() is not a function. Can someone help me troubleshoot this problem? Here's the relevant code from login.js import React ...

jQuery append() is ineffective

I am having trouble with the append() function in all browsers. My goal is to have the "next" span display the text "Next hello" with a blue background when the page loads. (This code serves as a test to confirm that my jQuery is functioning properly. In ...

Choose an option within a row of a table

Is there a way to display the div element with the .mynote class when clicking on the input that has an id of title? I attempted the code below, however, it does not seem to be functioning as expected. $("#title").click(function() { $(".mynote").show( ...

What could be causing my ul list to not be populated by ajax?

To populate the ul list with data from PHP code on page load, you can use the following ajax function. I appreciate any help in advance, and please forgive me if my explanation is not precise as I'm new here. This post contains mostly code snippets. ...

What is the counterpart of Ajax.updater in Jquery?

Could you please advise on how to achieve the same functionality as the prototype code below but using Jquery? var myAjax = new Ajax.Updater('abc', '/billing/add_bill_detail', { method: 'get', parameters: pars, ...

PHPBB authentication system

After experimenting with the script based on the guidance I received from you all, I've encountered another issue. When I click 'login' on the login form, it displays this message: The page isn't redirecting properly. Firefox has detect ...

Executing PHP queries with the help of jQuery

Currently, I am developing a webpage that involves checking a checkbox to trigger a PHP function which queries the table for user existence. If the user exists, a button is displayed allowing them to proceed to the next page. I have made an attempt at thi ...