How to make a div in Javascript smoothly slide out when it appears

Looking to add some smooth sliding animation to this basic JS code instead of the glitchy appearance it currently has.

I've experimented with different options but haven't had any success, any suggestions? Here's the code snippet along with the Jsfiddle link:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<style>
body{margin:0;}
#foo{min-width:400px; height:100%; background-color:#9C0; display:none; position:absolute; right:0px; top:0px;}

</style>
<body>
<a href="#" onclick="toggle_visibility('foo');">Click here to toggle visibility of element #foo</a>
<div id="foo" >

</div>

<script type="text/javascript">
<!--
    function toggle_visibility(id) {
       var e = document.getElementById(id);
       if(e.style.display == 'block')
          e.style.display = 'none';
       else
          e.style.display = 'block';
    }
//-->
</script>
</body>
</html>

JsFiddle

Answer №1

I have updated your fiddle using VanillaJS. You can view it here and see that it works perfectly.

document.getElementById('bar').onclick = (function()
{
    var that, interval, step = 20;
    var id = document.getElementById('foo');
    var handler = function()
    {
        that = that || this;
        that.onclick = null;
        id = document.getElementById('foo');
        interval = setInterval (function()
        {
            id.style.right = (parseInt(id.style.right, 10) + step) + 'px';
            if (id.style.right === '0px' || id.style.right === '-400px')
            {
                that.onclick = handler;
                clearInterval(interval);
                if (id.style.right === '-400px')
                {
                    id.style.display = 'none';
                }
                step *= -1;
            }
            else
            {
                id.style.display = 'block';
            }
        }, 100);
    };
    return handler;
}());

Explanation of the code:

  • The click handler is attached in JS to allow dynamic unbinding/binding
  • Instead of directly assigning a handler, a closure is used for the interval and DOM references
  • handler is the event handler that assigns its context (the clicked element) to that, allowing reference in the interval callback and unbinding the handler
  • The interval moves the element by step pixels (adjust to desired value)
  • If the div is at position 0 or -400, the interval is canceled, click handler is rebound, step *= -1 inverts the animation
  • Adjust the display property accordingly

The interval occurs every 100ms, but adjusting set to 10 and interval to 50 can smoothen the animation

Answer №2

If my interpretation is correct, you would want to utilize jQuery for implementing sliding effects.

Check out the example on JsFiddle.

JavaScript:

$("a").on('click', function() {
    $("#foo").slideToggle();
});

Answer №3

Here is the updated fiddle with jQuery implementation: http://jsfiddle.net/wRWHw/2/

   function toggle_visibility(id) {
        $("#" + id).slideToggle("slow");
    }

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

Sending a JWT token to a middleware with a GET request in Express Node.js - the proper way

Struggling with Js and web development, I've scoured the web for a solution to no avail... After completing a project for a small lab, my current challenge is creating a login page and generating a web token using JWT... I successfully created a use ...

How can I align the text in a dropdown menu to the center on Safari?

How can I center the option text in a drop down menu using CSS? display: block; height: 60px; margin-left: 10%; margin-right: 10%; margin-top: 10px; min-height: 60px; text-align: center; The option text is centered in Firefox browser, but not in Safari. ...

Converting Cyrillic characters to ASCII codes using JavaScript: A step-by-step guide

Is there a reliable method to convert characters from the CP1251 table to ASCII codes ranging from 0 to 255? So far, I have only come across the charCodeAt() function which is limited to codes up to 128. It returns a Unicode number for codes above that r ...

A guide on styling JSON key values within HTML

I need help organizing my JSON Document on an HTML page. Here is the JavaScript code I am using: xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { // Optionally, here you can update ...

Having trouble retrieving data using a custom URL in Axios with ReactJs

My knowledge of Reactjs is still new and I am currently working on a project using nextjs. I have a component called Trending.js that successfully fetches data from the URL "https://jsonplaceholder.typicode.com/users". However, when I try to change the U ...

Creating unique validation rules using VeeValidate 3 and vue.js

I have a form where I need to establish specific rules. For instance, consider the following code snippet: <label class="form-label">Price range from</label> <validation-provider rules="required_if:price_to" name="Price range from" ...

Why does the 401 error continue to persist while attempting to log in using Google Identity service on my Laravel application?

Trying to implement Google authentication services for user authentication. I've already integrated Laravel sanctum to allow users to log in and register successfully. This time, I want to add Google Identity services as an additional authentication ...

Develop a TypeScript class by incorporating a static function from an external library, while ensuring type safety

I am looking to enhance the capabilities of the rxjs5 Observable class by adding a static function. While this can be easily accomplished in plain JavaScript: var myStaticFn = function() { /* ... */ }; Observable.myStaticFn = myStaticFn; this approach w ...

React input field keeps losing focus during re-render operations

My current project involves using React to create an input text that displays a value from an in-memory data store and updates the store when the input value changes, triggering a re-render. However, I am facing an issue where the input text loses focus du ...

Please enter the text in the field provided at the bottom using IE10

Why is the text inside my input appearing at the bottom in IE10, while it displays in the middle on FF and Chrome? http://jsfiddle.net/PXN2e/2/ input.form-text { color: #999999; font-size: 14px; height: 30px; line-height: 30px; paddin ...

Is there a way to execute a PHP script using Ajax without needing any return values?

Currently, I am attempting to execute a php script with ajax without needing any output or echos. Is there a method to achieve this? Below is the approach I have taken: $('button')[1].click(function () { $.ajax({ met ...

Instead of using a computed getter/setter, make use of mapState and mapMutations to simplify

Currently, I am syncing a computed value to a component and using a computed setter when it syncs back from the component. I'm wondering if there is a more concise way to replace a computed getter/setter with mapState and mapMutations. How can this b ...

Is it possible for Susy to output a pixel-based span?

As a newbie to Susy, I hope you don't mind if I ask a seemingly silly question... I'm trying to figure out how to calculate responsive padding within a Susy grid. The standard formula is: (target / context) x 100. Is there a way for Susy to pr ...

What is the correct way to submit a formarray in an angular application following the specified format?

When submitting a form in Angular, I'm facing an issue where only the data from the first index inside the role menu is being passed. How can I ensure that all index data is passed on submit? { "roleMenu":[{ "menu":{ "menuId": 1 }, ...

Tips on Including a Custom Header in an Ajax Request for a Cross-Domain JsonP Call

Is there a way to add a custom header using an ajax call in jQuery for a cross-domain JSONP call? I am making a web service call in an HTML page using Ajax cross-domain call. I am currently using JSONP and now need to send some parameters in the header. ...

I experienced an issue with Firestore where updating just one data field in a document caused all the other data to be wiped out and replaced with empty Strings

When updating data in my Firestore document, I find myself inputting each individual piece of data. If I try to edit the tag number, it ends up overwriting the contract number with an empty string, and vice versa. This issue seems to stem from the way th ...

Utilize JavaScript to Forward Subdomain to Main Domain

Utilizing Apache envvars, I have created the MYDOMAIN and MYSUBDOMAIN variables to define 'mydomain.com' and 'sub.mydomain.com'. These variables are then used in the Apache sites-available conf files for website deployment. The 'su ...

Transfer a specific row from a dataTable to another dataTable on a separate php page

Within my programming project, I am working with two tables: table1.php and table2.php In my current setup, I have a script located in table1.php that allows me to pass data to a modal which then passes the data into table2.php. However, I am now facing a ...

Detect keypress within a BrowserWindow even when multiple BrowserView components are present

In my Electron application, I have a main BrowserWindow that contains the main user interface index.html, along with multiple BrowserView elements: browserWindow = new BrowserWindow({ width: width, height: height, frame: false }); browserWindow.webContents ...

Struggling to reveal concealed items on a webpage using jQuery and attempting to cycle through an array without success

Looking to display or hide certain sections on a page based on specific conditions. I want to only show the sections of the page that contain words from the conditionsToShow array. function hideWorkflowConditions() { // initially hide the elements ...