Shift a div out of view (using margin: 0px auto)

How can I achieve a sliding effect for two horizontally centered divs, #box1 and #box2, when a button with the class .class is clicked? The desired animation involves moving #box1 to the left and off the screen, while #box2 slides into view from the right. I have seen examples for absolutely positioned divs, but I am curious how to achieve this effect without absolute positioning.

HTML Structure

<div class="button"><a href="#">Slide</a> </div>

<div id="container">

    <div id="box1" class="box">Box #1</div>
    <div id="box2" class="box">Box #2</div>

</div>

Failed attempt

$(".button").click(function() {
    $("#box1").css('margin-left', 0);
    $("#box1").css('margin-right', 0);
    $("#box1").animate({
            left: '150%',
        }, 'slow' );

});

Answer №1

Here's a potential solution for your desired effect: Check out this jsFiddle example.

Using jQuery:

$(".button").click(function() {
    $("#box1").css('margin-left', 0);
    $("#box1").css('margin-right', 0);
    $("#box1").animate({ left: '-500px' }, 'slow');
    $("#box2").animate({ left: '0px' }, 'slow');
});​

Applying CSS:

#box1, #box2 {
    margin: 5px auto;   
    border: 1px solid #999;
    position:relative;
}
#box2 {
   left:500px;   
}
#container {
    overflow:hidden;
}

​ HTML Structure:

<div class="button"><a href="#">Slide</a> </div>
<div id="container">
    <div id="box1" class="box">Box #1</div>
    <div id="box2" class="box">Box #2</div>
</div>​

Answer №2

To achieve a sliding effect on a dive, jQuery UI hide methods can be utilized.

$(".button").click(function() {
    $("#box1").hide('slide', {
        direction: "left"
    }, 2000);
});

Similar sliding functionality can also be applied for sliding in:

$("#box2").show('slide', {
    direction: "left"
}, 1000)

Answer №3

Give it a shot

$(".btn").on("click", function() {
    $("#container1").animate({
        marginLeft: "-150%",
    }, "slow" );
});

Answer №4

Repositioning the element to its original spot after the animation is a simple task.

let box = $("#box1");
let originalPosition = box.position();
let cssProperties = {
  'position' : 'absolute',
  'top' : originalPosition.top,
  'left' : originalPosition.left
}
box.css(cssProperties);

Answer №5

This solution may be effective for your needs.

$(".button a").click(function() {

    var $docWidth = $(window).width();
    var $boxOffset = $('#box1').offset();

    $("#box1").css('marginLeft', $boxOffset.left);
    $("#box1").animate({
        marginLeft: $docWidth
    }, 'slow');

});

CSS:

#container: { overflow: hidden; }

http://jsfiddle.net/aBCDE/

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

Encountering a timeout issue with the Sinch API within an Angular 2 project during the onCallProgressing

We successfully integrated Sinch into our angular 2 web application. Most functionalities are working perfectly, except for the user calling feature using the sinch phone demo. When the application is in the foreground, the call rings and connects withou ...

The command response.setHeader("Refresh", "0") failed to execute

My webpage needs to be refreshed when the user session has expired or the connection is not active. Despite trying various codes, I have been unsuccessful in achieving this. The last code snippet that I implemented is as follows: if(session.getAttribute(" ...

Utilizing the request body value within the .withMessage() function of the Express validator chain

I am looking to showcase my express validator errors with the specific value entered by the user. For instance, if a user types in an invalid username like "$@#" (using a regex that I will provide), I want to return my error message as follows : { "er ...

Can someone please provide instructions on how to customize the textfield caret using JavaScript?

Is there a way to modify the appearance of a caret so that it resembles a letter or some other shape? Appreciate any suggestions. Thank you! ...

"Keep an eye on the server with Backbone.js by running periodic checks

In an effort to keep my backbone application constantly checking the server for model updates, I aim to create a system similar to Twitter's auto-refresh feature for new tweets. Currently, I am connecting to an external application through their API ...

Can you explain the purpose of ExpiresAbsolute?

In the process of converting an ancient and poorly written ASP page to ASP.NET, I stumbled upon this particular line in the "head" section: <meta http-equiv="ExpiresAbsolute" content="0" /> Despite searching on Google, I couldn't find any mean ...

The UPDATE query failed to make any changes to the data stored in the MySQL

Currently I am developing an application using express.js. In my project, I have incorporated the "mysql" add-on (https://www.npmjs.com/package/mysql). The issue I am facing is while sending an UPDATE query to the server and receiving a response that shows ...

Preview of webpage in Sublime Text is not rendering jQuery properly

I am encountering an issue while trying to set up a page with skrollr for parallax effect. It functions perfectly on platforms like CodePen, but when I attempt to preview it after setting up my page on Sublime Text, nothing seems to work. Could there be s ...

Getting URL parameters dynamically without reloading the page

Here's a particular issue I'm encountering: I've implemented the following function to fetch the GET Parameters from a URL. $(document).ready(function() { function getParam(variable) { var query = window.location.search.sub ...

Navigating to a precise element within a page in Angular with flawless redirection

I recently encountered an issue where I had to add a span element with a specific ID in my HTML code to ensure that clicking on the Reply button would navigate to it. However, this modification was only necessary for the last element on the page. While the ...

When does an xmlHttpRequest object parse serialized XML into a DOM during its lifecycle?

When a JavaScript code with xmlHttpRequest.responseXML() runs, it creates a DOM Document object from the XML-structured HTTP response body. Have you ever wondered at what moment the XML string is turned into the DOM Document by an xmlHttpRequest object? ...

How can we prevent an ajax call from being made when the user input is empty?

Currently, I am utilizing the keyup event for an Ajax call on an input field along with the f:validaterequired tag. Each time the Ajax event (keyup) triggers, f:validaterequired is being validated. However, I do not want to validate when the value is null. ...

How can I trigger a click event on a link using JQuery?

One of my links has the unique id: nyhedsklik There is a function associated with this link that activates when it is clicked: $('a.poplight[href^=#]').click(function() { var popID = $(this).attr('rel'); //Fetching Popup ...

Steps to generate a nested array of objects within a given array using JavaScript

I currently have an array called ExampleArray which contains different objects with properties like "No", "Name", and "subject". I want to transform this array into a new format where the "subject" property is an array of strings instead. var ExampleArray ...

The failure of the $getJSON function to execute properly

Having trouble with handling errors in the $getJSON .fail method: this.flickrPics = ko.observableArray(); ko.computed(function() { $.getJSON( 'https://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?', { ...

The div is unable to display data retrieved from the php file using Ajax

This is the function utilizing ajax $(document).ready(function() { $('#submit').click(function(e) { e.preventDefault(); $.ajax({ type: 'POST', url: 'searchphp.php&apo ...

What is the best way to check if a user input matches any of the items saved in an array?

I'm working on coding a hangman app and I have a question. How can I compare the user input "userGuess" to the array "array" that consists of letters split from the randomly selected word "word"? If the "userGuess" matches any of the values in the "a ...

How can you retrieve the component's state from a higher level without relying on useContext?

I have a question regarding creating expanding flex cards. I found an example on Codepen that showcases what I'd like to achieve: https://codepen.io/z-/pen/OBPJKK In my code, I have a component called HomeButtons that generates these flex cards. With ...

Decode my location and input the address before validating it

While I have come across numerous plugins that enable geolocation and display it on a map, I am searching for something unique. I am interested in implementing geocoding when a user visits the page with an option to "allow geolocation." If the user agrees ...

Removing a cookie in Javascript - step by step guide

Cookie Conundrum: I've encountered a curious scenario involving browser cookies. After entering an invalid login ID, an unauthorized cookie appears on my HTML page. Despite my attempts to display and expire the cookie, it stubbornly remains persistent ...