What is the best way to smoothly transition between three images, each appearing in a randomized position and size?

Looking to add a dynamic div that fades in and out randomly with varying sizes and positions?

You may have already tried displaying three images with fade-in and fade-out effects, but struggled with randomizing their placement and size.

Check out this example on jsFiddle for inspiration!

Here's the jQuery code snippet:

jQuery(function(){
    function random(n) {
        return Math.floor(Math.random() * n);
    }
    var transition_time = 2500;
    var waiting_time = 100;
    var images = $('div#block img');
    var n = images.length;
    var current = random(n);
    images.hide();
    images.eq(current).show();

    var interval_id = setInterval(function () {
        images.eq(current).fadeOut(transition_time, function () {
            current = random(n);
            images.eq(current).fadeIn(transition_time);
        });
    }, 2 * transition_time + waiting_time);
})

And here's the HTML code snippet:

<div id="block">
    <img src="http://mobler.com.tr/wp-content/uploads/2017/07/rand1.png">
    <img src="http://mobler.com.tr/wp-content/uploads/2017/07/rand2.png">
        <img src="http://mobler.com.tr/wp-content/uploads/2017/07/rand3.png">

</div>

Answer №1

Here is a solution that allows for specifying the range of image scale sizes, ensuring that the chosen position does not clip outside the container regardless of the scale. I hope this solution aligns with your requirements.

EDIT: The code has been updated to maintain proportions for non-quadrilateral images as well (as demonstrated by Phil Murray's examples).

If adjusting the size using CSS height/width proves unsuccessful, consider utilizing the CSS3 scaleX/scaleY property for smoother image scaling results.

For any additional queries, please feel free to ask in the comments section below.

jQuery(function(){
    function random(n) {
        return Math.floor(Math.random() * n);
    }
    var transition_time = 200;
    var waiting_time = 100;
    var images = $('div#block img');
    var n = images.length;
    var current = random(n);
    images.hide();
    images.eq(current).show();
    
    // Fetch container dimensions
    var boxHeight = document.getElementById('block').offsetHeight;
    var boxWidth = document.getElementById('block').offsetWidth;
    
    // Define possible image scales range
    var objectMaxHeight = 60;
    var objectMinHeight = 20;
    
    var interval_id = setInterval(function () {
        images.eq(current).fadeOut(transition_time, function () {
            current = random(n);
            
            // Get reference to selected image
            var $domImage = images.eq(current);
            
            // Generate random heights and widths for the image to be displayed
            var generatedHeight = 
            Math.floor(
                Math.random() * (objectMaxHeight - objectMinHeight)
                 ) + objectMinHeight;

// Assign values to the image
            $domImage.css('height', generatedHeight); 
            $domImage.css('width', "auto"); 
           
            var imageAutoWidth = $domImage.width();
            
            var generatedYLocation = Math.floor(
              Math.random() * (boxHeight - generatedHeight + 1)
            ) + 0;
     
            var generatedXLocation = Math.floor(
                Math.random() * (boxWidth - imageAutoWidth)
            ) + 0;
          
            $domImage.css('top', generatedYLocation);
            $domImage.css('left', generatedXLocation);
            $domImage.fadeIn(transition_time);
        });
    }, 2 * transition_time + waiting_time);
})
#block { 
  position: fixed;
  width: 300px;
  height: 300px;
  border: 1px solid red;
  background: yellow;
  overflow: hidden;
}

img {
  position:relative; 
  top: 0;
  left: 0;
  height: 100px;
  width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="block">
    <img src="http://mobler.com.tr/wp-content/uploads/2017/07/rand1.png">
    <img src="http://mobler.com.tr/wp-content/uploads/2017/07/rand2.png">
    <img src="http://mobler.com.tr/wp-content/uploads/2017/07/rand3.png">
    <img src="https://www.fillmurray.com/g/200/500">
    <img src="https://www.fillmurray.com/g/500/200">
</div>

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

Displaying JSON data after a successful AJAX call

I am currently facing an issue with my controller. I have a query that returns data in JSON format, and I'm trying to display this data in the view using AJAX and jQuery. However, every time I try to output the data, it shows as [object Object]. I sus ...

What is the best way to arrange two images next to each other using HTML and CSS in order to effectively utilize a specified width?

I am trying to display two different images side by side within a DIV element that is exactly 800px wide. The images may have varying widths and heights, with some being wider than tall and others taller than wide. I have attempted to place both images i ...

Arranging elements within an outer array by the contents of their inner arrays

I need help organizing an array based on the alphabetical order of a specific value within the inner arrays. For example: I want to sort this array by the prefix "old," so old A, old B, etc. const array = [ { personName: "Vans", personTags: ["young", " ...

Why do query values disappear when refreshing a page in Next.js? [Illustrative example provided]

In my current project, I am developing a simple Next Js application consisting of just two pages. index.tsx: import React from "react"; import Link from "next/link"; export default function Index() { return ( <di ...

Which specific scoped CSS selector should I use to modify the width of the mdDialog container?

Is there a way to override the max-width of 80vw set on .mat-dialog-container in an Angular Material dialog? I want to create a truly full-width dialog. The issue lies with scoping--Angular-CLI compiles component CSS using scope attribute selectors. This ...

I'm currently in the process of creating a snake game using HTML5. Can you help me identify any issues or problems that

I am experiencing an issue where nothing is appearing on the screen. Below are the contents of my index.html file: <html> <body> <canvas id="canvas" width="480" height="480" style="background-color:grey;"></canvas> <script src=" ...

Utilizing AJAX to Invoke a Method in a CS Page: A Step-By-

I am trying to utilize AJAX to call a method in my CS page. Below is the design code I am using: <!-- Name --> <input type="text" name="name" id="name" required="required" class="form" placeholder="Name" /> <!-- Email --> <input type= ...

What causes jquery height and javascript height to both be returned as 0?

I'm facing an issue with a visible div on my screen - despite being visible, its height always returns as 0. I've attempted various jQuery and JavaScript methods to retrieve the height, but it consistently shows as 0. Here's the structure of ...

Make sure that the TextBox OnTextChanged event in ASP.NET triggers a "setTimeout" function before the OnClick event is fired

Imagine the following situation: <asp:TextBox ID="txt" runat="server" AutoPostBack="true" OnTextChanged="txt_TextChanged"></asp:TextBox> <asp:Button ID="btn" runat="server" OnClick="btn_Click" CausesValidation="false" UseSubmitBehavior="fal ...

Trigger event when clicking on child elements inside parent element

Is it possible to target the parent element onclick from within the parent itself? Imagine having several instances of this scenario on a single page <div class="parent"> <div class="some-text">text</div> <div class="some-ima ...

Z-index problem occurring with rotateY on Safari and Chrome Mobile

https://jsfiddle.net/nxbg7rq3/ I've been struggling to get the .mask completely on top of the .screen in this example. It works fine in most browsers, but Safari and Chrome Mobile are giving me a hard time. I've experimented with various solutio ...

jQuery asynchronous treeview collapse issue

I have implemented an async jQuery treeview to create a dynamic tree structure. The tree is populated based on the selection from a dropdown list. Initially, everything works perfectly when the treeview is loaded for the first time. However, upon changing ...

Automatically resizing textures in Three.JS with WebGL

Seeking assistance to overcome a challenge :) I am using Three.JS to showcase high-resolution equirectangular images on a sphere (20000x10000 pixels). Image quality is crucial for my web application, and bandwidth is not a concern. My issue is that ThreeJ ...

The issue persists where Tailwind Inline color decorators are unable to function properly alongside CSS variables

In my current project using Tailwind CSS with CSS variables for styling, I have noticed a peculiar issue. The color previewers/decorators that usually appear when defining a color are not showing up in my class names. These previewers are quite helpful in ...

Incorporating JavaScript for modifying Less files

Is it feasible to modify Less documents using JavaScript? I am attempting to adjust a property of a Less file with JavaScript. Here is my code: document.getElementsByClassName('content-main--inner').style.border = '1px solid yellow!importan ...

Mediawiki version 1.26.2 experiencing loading issues with Stylesheet

I recently updated my Mediawiki installation to the latest version 1.26.2, but I've encountered an issue with the stylesheet not loading correctly. Strangely enough, in a previous version (1.23.5) installed on the same server, everything was working f ...

What is the method for retrieving the name of the 'Autocomplete' component in Material UI?

Currently, I am faced with the challenge of working on multiple Autocomplete MUI components and am in the process of creating a "generic" event handler that will utilize the useReducer hook to manage the state. The issue lies in the fact that the onChange ...

"Integrating JQuery Validation with an AJAX post request for seamless form submission

I'm fairly new to JQuery and I have a question regarding email validation and ajax post. Initially, I was able to validate an email address using a JQuery plugin with the following code: $(document).ready(function () { $("#email").click(function ...

Implement the maskmoney library in your input fields

In the form below, I am automatically adding inputs using a JavaScript function like this: $('.Preco1').maskMoney({ decimal: '.', thousands: ' ', precision: 2 }); $('.Preco1').focus(); $('#sub').maskMon ...

Are JQuery functions affected when navigating between pages in smart-tables?

Apologies if this question has been answered before or seems obvious. I couldn't find a solution after searching, and as someone new to web development, I might be going in circles here. Issue: I've integrated the smart-table extension () into ...