Creating a slide animation that moves horizontally within an HTML document

I have seen this question asked many times, but I can't seem to find an answer that fits my needs.

In essence, what I am looking for is to slide a box horizontally from the right side (invisible) of the screen to the left, and then back from the left to the right.

The HTML/CSS/JS code below demonstrates exactly what I am trying to achieve:

<html>
<head>
  <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<style type="text/css">
#box-1 {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 80em;
  background-color: #f00;
}
#box-2 {
  position: absolute;
  top: 0;
  right: -100%;
  width: 100%;
  height: 4em;
  background-color: #0f0;
}
#viewport {
  overflow: hidden;
  position: relative;
  height: 100em;
}
#container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
}
</style>
</head>
<body>
<div id="viewport">
  <div id="container">
    <div style="position: relative">
      <div id="box-1">
      </div>
      <div id="box-2">
      </div>
    </div>
  </div>
</div>
<script type="text/javascript">
$("#box-1").click(function () {
    $(this).parent().parent().animate({left: "-100%"});
});
$("#box-2").click(function () {
    $(this).parent().parent().animate({left: "0"});
});
</script>
</body>
</html>

However, there are two key issues with this code:

  • I want the outer viewport to automatically adjust its height based on the highest item in the container, rather than having a fixed height
  • When scrolling down to the bottom of the page while the red box is visible and clicking it, the green box appears within the viewport but at the bottom. I would prefer the green box to be directly in view. Additionally, once the green box is in view, clicking on it should bring the red box back into view at its previous scroll position.

While there are other limitations in this example (such as the default animation function provided by jQuery), I believe these can be addressed later.

Considering the constraints of the solution I've presented here, I suspect I may need to rethink my approach but I'm not sure where to start.

Answer №1

To ensure that you are taken to the top of the div when clicking on the box, you can use the following code snippet:

$(function() {
    var maxHeight = Math.max($("#box-1").height(), $("#box-2").height());
    $("#viewport").height(maxHeight);
});
$("#box-1").click(function () {
    $(this).parent().parent().animate({left: "-100%"});
    $('html,body').animate({
       scrollTop: $("#box-1").offset().top
    });
});
$("#box-2").click(function () {
    $(this).parent().parent().animate({left: "0"});
    $('html,body').animate({
       scrollTop: $("#box-2").offset().top
    });
});

I have also made updates to the JS Fiddle for your reference: http://jsfiddle.net/Av7P3/1/

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

Strategies for resolving duplicate jQuery code in my project

Trying to simplify my jQuery code that handles video selection and playback functionality. Users can click on a thumbnail or button to play a specific video, with the title of the video changing accordingly. Despite achieving the desired outcome, the cur ...

Retrieve the selected value from a specific div element

Having some issues with retrieving the selected value from a Bootstrap chosen select field within a div. Any ideas on what might be causing this problem? $('#content_' + id).find('#GroupID > option:selected').text() // returns blank ...

Retrieving information from MongoDB to populate the Redux store

Currently, I have successfully set up my Node API and MongoDB. My next focus is on integrating Redux into my application. Below are some code snippets that I would like to share: The Server Order controller is functioning as expected : const getTotal = as ...

Issue with fluid layout in CSS - Unable to specify height in pixels and minimum height property not functioning as expected

While working on a liquid layout, I have set all my width and height values in percentages. However, during the design process, I needed to check how my CSS was rendering so I temporarily set the height in pixels. Eventually, the height in percentage wil ...

Tips for invoking a JavaScript class method from an HTML document

I've created a Typescript class that dynamically inserts an HTML element to a page after it's loaded. Here is the code snippet: const calcElement: string = ` <div class="container"> <span class="cc-title">Field</span> ...

Dealing with the challenges posed by middleware such as cookie access and memory leaks

Utilizing express with cookieParser() where my client possesses the cookie named: App.Debug.SourceMaps. I've crafted a middleware as follows: app.get('/embed/*/scripts/bundle-*.js', function(req, res, next) { if (req.cookies['App ...

Complete the JQuery code by closing the div and ul tags, then proceed to open a

Need help with structuring HTML <div class="content"> <p>Lorem ipsum dolor sit amet</p> <ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </ul> <span>Dolor set amet conse ...

What are the top JavaScript widget libraries for a measurement reporting web application?

Embarking on a new venture to develop a web application tailored for engineers in need of reporting measurements. The key elements that form the backbone of this project include: grids charts maps After thorough research, I have delved into various java ...

Step-by-step guide on launching a modal popup window in asp.net

Below is the JavaScript code that I have written: <script> $('#<%= btnOpen.ClientID %>').click(function (e) { e.preventDefault(); $('#content').modal({ onOpen: function (dialog) { dialog.overlay.fade ...

"Developing my custom long-polling solution as a more efficient alternative to the

I have been doing some extensive testing on long polling/comet implementation for my website. After gaining a basic understanding of how it works, I ran some tests here. While examining how gmail and facebook use long polling in Firebug, I noticed that gm ...

Guide on Updating the ColModel Dynamically in JAVASCRIPT/HTML using clearGridData, setGridParam, and reloadGrid Functions

I am trying to figure out how to dynamically change the colmodel of my grid using a function that is called by a SELECT. The reason for this is because my grid has different periods and needs to display either cost or tons based on user selection. Below i ...

In what ways can CSS be used to create a smoother edge effect on images?

After attempting to add an image to my website, I noticed that its edges appear quite rough. https://i.sstatic.net/Xol9R.png(Note: In the image above, you can observe the jagged surface around the berry). This issue arose when I eliminated the background ...

Withdrawal of answer from AJAX request

Is there a way to create a function that specifically removes the response from an AJAX call that is added to the inner HTML of an ID? function remove_chat_response(name){ var name = name; $.ajax({ type: 'post', url: 'removechat.php ...

issue with retrieving data from PHP script via ajax

My attempts to use AJAX to call a PHP script have been unsuccessful. I added an echo alert statement in my deleteitem.php script to ensure it was being called, but no matter what I tried, it never executed. Both the PHP script and the JS script calling it ...

Unable to reach controller action with Ajax request

I've been encountering issues trying to make a Get request to hit the specified URL. Initially, I attempted inputting the URL parameter manually in a separate JS file, then transitioning all my JS to cshtml to test out Razor. However, I am still facin ...

Leveraging trustAsHTML with an array of object elements

I'm facing a challenge in passing an array of objects from an Angular Controller to the ng-repeat directive. The objects within the array have multiple properties, some of which may contain HTML that needs to be displayed using the ng-repeat. I' ...

Changing the context results in the entire component being re-rendered

Currently, I am encountering a challenge where I have two different components within my Layout.js component that need to "share" props with each other. To address this issue, I introduced a ContextProvider named IntegrationProvider. However, a new proble ...

Creating a table dynamically using JSON data can be easily achieved with a jQuery function

Is there a way to extract a JSON object from a local file and present it in a table using jQuery? Take a look at the JSON file content below (jsondata.json): { "scores" : [ ["3/1/2011", 610],["4/1/2011", 610],["5/1/2011", 610],["6/1/2011", 610], ["7/1/2 ...

What is the recommended method for choosing text colors when creating GUI for app development?

Currently preparing PSDs for the development of both an iOS and Android app. When it comes to coloring text, should I: 1) Utilize #000000 for black text, adjusting opacity to achieve various shades of gray for primary and secondary text? 2) Or opt for a ...

Trouble with CSS and jQuery: Is document.height accurately reported? Why won't the div stretch vertically?

Surprisingly, I haven't been able to find anyone else facing this issue. O_o Check out the code on Pastebin here The code is causing a gap between the end of #main and the end of the actual page on IE, Chrome, and Safari, but not on Firefox. The ba ...