Animate the leftward disappearance of a div to make it vanish

My goal is to create a user interface where users can navigate through different divs. Here is the HTML code:

<article id="realize" class="realizeBox">
    <div class="shown">
        <div class="heading">
            <h2>Realisations: <span>AGFA</span></h2>
        </div>
        <div class="centering">
            <aside class="left">
                <p>Maecenas laoreet est bibendum, dictum mi vel, cursus mi. Curabitur feugiat libero vitae lorem venenatis consequat. Donec luctus nisi cursus miet sapien blandit, quis congue massa tincidunt.</p>
            </aside>
            <aside class="right">
                <p>Maecenas laoreet est bibendum, dictum mi vel, cursus mi. Curabitur feugiat libero vitae lorem venenatis consequat. Donec luctus nisi cursus miet sapien blandit, quis congue massa tincidunt.</p>
            </aside>
            <div class="clear"></div>
        </div>
        <div class="button">
            <div class="centering"> <a href="#" class="next"></a> <a href="#" class="prv"></a> </div>
        </div>
    </div>
    <div class="notshown">
        <div class="heading">
            <h2>Realisations: <span>TEST</span></h2>
        </div>
        <div class="centering">
            <aside class="left">
                <p>Etiam porta sem malesuada magna mollis euismod. Nullam id dolor id nibh ultricies vehicula ut id elit. Etiam porta sem malesuada magna mollis euismod. Donec ullamcorper nulla non metus auctor fringilla.</p>
            </aside>
            <aside class="right">
                <p>Etiam porta sem malesuada magna mollis euismod. Nullam id dolor id nibh ultricies vehicula ut id elit. Etiam porta sem malesuada magna mollis euismod. Donec ullamcorper nulla non metus auctor fringilla.</p>
            </aside>
            <div class="clear"></div>
        </div>
        <div class="button">
            <div class="centering"> <a href="#" class="next"></a> <a href="#" class="prv"></a> </div>
        </div>
    </div>
</article>

In the article, I have multiple divs. The first one is displayed, while the others have the class notshown with CSS styling of display:none;.

There are two buttons for each div:

<a href="#" class="next"></a> 
<a href="#" class="prv"></a>

The JavaScript associated with this functionality is as follows:

$('.next').click(function(e){
    e.preventDefault();
    if($('.realizeBox .shown').next().length > 0)
    {
        $('.realizeBox .shown').removeClass('shown').addClass('notshown').next().addClass('shown').removeClass('notshown');
    }
});

$('.prv').click(function(e){
    e.preventDefault();
    if($('.realizeBox .shown').prev().length > 0)
    {
        $('.realizeBox .shown').removeClass('shown').addClass('notshown').prev().addClass('shown').removeClass('notshown');
    }
});

Currently, the transitions between divs are abrupt, and I would like to incorporate animated effects for smoother navigation. I've attempted using jQuery's animate function without success due to my limited JavaScript skills. Can someone provide guidance on how to achieve this?

Answer №1

If you prefer, you have the option to disregard this response, however, creating a carousel from scratch can be quite laborious. Luckily, there are already numerous solutions available for this problem that have been pre-coded and can be easily customized. Here are a few examples of what you're seeking:

$(document).ready(function(){
  $('.slider1').bxSlider({
    slideWidth: 200,
    minSlides: 2,
    maxSlides: 3,
    slideMargin: 10
  });
});

<div class="slider1">
  <div class="slide"><img src="http://placehold.it/350x150&text=FooBar1"></div>
  <div class="slide"><img src="http://placehold.it/350x150&text=FooBar2"></div>
  <div class="slide"><img src="http://placehold.it/350x150&text=FooBar3"></div>
  <div class="slide"><img src="http://placehold.it/350x150&text=FooBar4"></div>
</div>

I hope this information proves to be beneficial!

Answer №2

How to achieve the desired effect using CSS

@-webkit-keyframes disappear {
    from{transform: translate(0,0);}
    to{transform: translate(-100%,0);}
}
@keyframes disappear{
    from{transform: translate(0,0);}
    to{transform: translate(-100%,0);}
}    
.notshown{
    animation: disappear 2s;
    -webkit-animation: disappear 2s;
}

This CSS will impact the div when the specified class is added to it

Once the animation finishes, the div will return to its original position

If you use display:none, the effect won't be visible (as it will move while hidden)

To overcome this, remove disply:none in CSS and instead employ setTimeout with a delay time equivalent to the animation duration to prevent the div from immediately disappearing until the animation completes

The code has been tested on Chrome, Firefox, and IE 11 browsers

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
    $(document).ready(function(){
        $(".notshown").css('display','none');
        $('.next').click(function(e){
            e.preventDefault();
            if($('.realizeBox .shown').next().length > 0)
            {
                $('.realizeBox .shown').removeClass('shown').addClass('notshown').next().addClass('shown').removeClass('notshown');
                setTimeout(function(){
                    $(".shown").css('display','');
                    $(".notshown").css('display','none');
                },2000);
            }
        });

        $('.prv').click(function(e){
            e.preventDefault();
            if($('.realizeBox .shown').prev().length > 0)
            {
                $('.realizeBox .shown').removeClass('shown').addClass('notshown').prev().addClass('shown').removeClass('notshown');
            }
        });
    });
</script>
<style>
    @-webkit-keyframes disappear {
        from{transform: translate(0,0);}
        to{transform: translate(-100%,0);}
    }
    @keyframes disappear{
        from{transform: translate(0,0);}
        to{transform: translate(-100%,0);}
    }
    .notshown{
        animation: disappear 2s;
        -webkit-animation: disappear 2s;
    }

</style>
<a href="#" class="next">next</a><br/>
<a href="#" class="prv">prv</a>
<article id="realize" class="realizeBox">
    <div class="shown">
        <div class="heading">
            <h2>Realisations: <span>AGFA</span></h2>
        </div>
        <div class="centering">
            <aside class="left">
                <p>Maecenas laoreet est bibendum, dictum mi vel, cursus mi. Curabitur feugiat libero vitae lorem venenatis consequat. Donec luctus nisi cursus miet sapien blandit, quis congue massa tincidunt.</p>
            </aside>
            <aside class="right">
                <p>Maecenas laoreet est bibendum, dictum mi vel, cursus mi. Curabitur feugiat libero vitae lorem venenatis consequat. Donec luctus nisi cursus miet sapien blandit, quis congue massa tincidunt.</p>
            </aside>
            <div class="clear"></div>
        </div>
        <div class="button">
            <div class="centering"> <a href="#" class="next"></a> <a href="#" class="prv"></a> </div>
        </div>
    </div>
    <div class="notshown">
        <div class="heading">
            <h2>Realisations: <span>TEST</span></h2>
        </div>
        <div class="centering">
            <aside class="left">
                <p>Etiam porta sem malesuada magna mollis euismod. Nullam id dolor id nibh ultricies vehicula ut id elit. Etiam porta sem malesuada magna mollis euismod. Donec ullamcorper nulla non metus auctor fringilla.</p>
            </aside>
            <aside class="right">
                <p>Etiam porta sem malesuada magna mollis euismod. Nullam id dolor id nibh ultricies vehicula ut id elit. Etiam porta sem malesuada magna mollis euismod. Donec ullamcorper nulla non metus auctor fringilla.</p>
            </aside>
            <div class="clear"></div>
        </div>
        <div class="button">
            <div class="centering"> <a href="#" class="next"></a> <a href="#" class="prv"></a> </div>
        </div>
    </div>
</article>

Answer №3

To achieve this effect, consider utilizing CSS transitions.

Assuming you haven't provided the CSS for the notshown and shown classes, it could look like this:

.shown{
  opacity:1;
}

.notshown{
  opacity:0;
}

You can easily create a smooth in-and-out animation by adding the following code:

#realizeBox > div{
  -webkit-transform: translateZ(0);
  -moz-transform: translateZ(0);
  -ms-transform: translateZ(0);
  -o-transform: translateZ(0);
  transform: translateZ(0);
  
  /* Trigger GPU instead of CPU for animations just for fun */
  transition: opacity 200ms linear;
}

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

Animate the jQuery element to fade in after it has been hidden with the slide effect

I am trying to create a div that slides out of the viewport and then fades in at the same spot with a different background image. However, currently it only slides out and does not fadeIn: $('#myDiv').hide('slide').queue(function() { ...

Preventing Javascript array elements from being overwritten: Best practices

My challenge lies with the addToClients() function, which is designed to add a new value to the clients array whenever a button is pressed. The issue I am facing is that each time I press submit, the previous element in the array gets replaced by the new o ...

Troubleshooting Bootstrap Social Buttons: Background Color and Hovering Challenges

I've been working with Bootstrap to design social buttons for Facebook and LinkedIn. However, I'm facing an issue where setting the background color to white for the buttons doesn't cover them properly. The white background extends beyond th ...

Eliminate the blank choice from X-editable Select

Lately, I've been dealing with AngularJS and X-editable and one thing that has been troubling me is the fact that the select option always includes an empty first child. Here's the HTML <span editable-select="curuser.roles" e-name="roles" ...

Using jQuery in an external JavaScript file may encounter issues

As a newcomer to jQuery, I decided to try writing my jQuery code in an external js file rather than embedding it directly into the head of the HTML file. Unfortunately, this approach did not work as expected. Here is what my index.html looks like: < ...

Trouble with AJAX request when trying to connect to a distant server

I am facing an issue with my AJAX request. When I test it on localhost, everything works perfectly fine. However, when I upload the code to a remote server, the request fails without any error messages. Even after checking in Firefox and Chrome, there ar ...

JavaScript for validating dimension text input has unique functionalities

I am looking for guidance on validating an ASP textbox using JavaScript. My goal is to validate a user's input in the format of 4-1/2, 80-1/2, 6/8, or simply 5. Only these types of patterns should be allowed, and each input must contain only one numbe ...

Enhance the functionality of Jquery UI drag and drop to be responsive even when in a zoom

I came across this drag and drop demo for Jquery UI that was working perfectly at a regular zoom level. However, when I zoomed out to 50%, things started acting strange. Can anyone provide suggestions on how to fix the demo? Link to Demo Any help would be ...

Map Loader for GeoJson Leaflet Integration

Although my English skills are not perfect, I will do my best to explain my issue. I have some knowledge of javascript / html / ajax and I have created a webgis using Leaflet. The problem arises when loading a large geojson file onto the map - it takes qui ...

Issues with React router arise once the app has been built

I am new to utilizing react and react-router in my project. I have built the application using create-react-app and now I am facing an issue with routing between two main pages. After trying different approaches, I managed to get it working during develop ...

Mapping an array based on specific conditions

When using my photo gallery app, I faced a challenge in mapping an array of images based on the user-selected album name. The current setup works perfectly for the 'Cambodia' album where all images are correctly logged in the console after mappin ...

Script tag for Next.js reloading functionality

I have been facing a challenge while trying to integrate third-party commenting scripts like (disqus, remark42, hyvor) into my next.js application. The issue I encountered is that the script only loads on the initial page load. Subsequently, I need to refr ...

Why am I encountering a type error in NodeJS when utilizing the ping module?

I'm currently working on creating a simple app for pinging an IP address. The HTML form I've created has one input field for the IP address, which is then sent to NodeJS for processing. I am utilizing the ping module to retrieve the results. Ever ...

Utilizing nested observables for advanced data handling

Consider the following method: public login(data:any): Observable<any> { this.http.get('https://api.myapp.com/csrf-cookie').subscribe(() => { return this.http.post('https://api.myapp.com/login', data); }); } I want to ...

Searching for values in JSON using jQuery's autocomplete feature

I have implemented jquery autocomplete with a json request in my code. Here is the code snippet for the autocomplete feature: $("#company_name").autocomplete({ source: function( request, response ) { $.ajax({ url: "https://ur ...

Following the recent update to IntelliJ IDEA 2022.1.3, the use of ::ng-deep has been marked

After updating the version of IntelliJ, I noticed that the ::ng-deep angular material selector is now marked as deprecated. Here's an example: <mat-form-field class="register-custom-select"> <mat-select formControlName="gende ...

Retrieving subscriber count from Feedburner using jQuery and JSON

Is there a way to showcase the total number of feedburner subscribers in a standard HTML/jQuery environment without using PHP? The code snippet should be functional within a typical HTML/jQuery page. Perhaps something along these lines: $(document). ...

Ways to showcase various data on a single PHP page without relying on the GET method

I'm currently working on a project to create a website where users can set up their own profiles and share their profile link for others to view. Instead of having separate pages for each user, I want to streamline the process by using just one page t ...

Can WebSocket messages be encoded?

Is there a way to encrypt or obscure the data I transmit via websockets? For example, the message looks like this: var encryptedMsg = { type: "message", data: { message: "Hello world!" } } I require the ability to send this message in ...

React is indicating that returning functions is not appropriate as a React child. This issue may arise if you accidentally return a component instead of <Component /> within the render method

Check out the main game.js and app.js files: //Here is the code in game.js// import React, { Component } from "react"; class Game extends Component { constructor(props) { super(props); this.state = { num: 0 }; this.numPicker = this.numPi ...