Generating replicated elements at varying positions

After discovering that my previous question, which can be found here, is currently not feasible due to limitations with html2canvas only taking 'snapshots', I have chosen to approach the problem differently.

The new approach involves making an object disappear when clicked, and then having multiple smaller versions of it scattered randomly across the screen. For example, let's say we have an image of a cat (cat.jpg): when clicked, it should appear as if it explodes into three smaller cat.jpg images that are tossed around the screen. Meanwhile, the original cat.jpg remains hidden.

Here is the code that now works properly:

$('#cat').click(function() {
    $(this).hide();
    for (var j = 1; j <= 3; j++) {
      $('#content').append('<span><img class="cat" src="cat.jpg" /></span>');
    }
    $('#cat').css("position", "relative");
    $('img.cat').each(function(i) {
      var newTop = Math.floor(Math.random()*500)*((i%2)?1:-1);
      var newLeft = Math.floor(Math.random()*500)*((i%2)?1:-1);
      $(this).css({position: "relative",
        top: 0,
        left: 0
      }).animate({
        top: newTop,
        left:newLeft
      }, 1000);
    });
  });

Although the current code does not reduce the size of the images, once the duplication and random positioning are achieved, adjusting their size based on the loop count will be straightforward. While this solution partially works, I am open to suggestions for a better or more elegant implementation.

Edit: I have updated the code with a version that closely aligns with my desired outcome. However, I welcome any suggestions or improvements. The answer will be rewarded to anyone who presents a method that surpasses the current solution.

Answer №1

Why not give this a shot:

// $(document).ready(function(){ - assuming you know where to add this code.

var contW = $('#container').width();
var contH = $('#container').height();
var explode;

$('.holder').click(explode=function() {    
    for (var j = 1; j <= 3; j++){        
       var sourceX = (Math.random()*contW)%(contW>>1);
       var sourceY = (Math.random()*contH)%(contH>>1);
       var nTop = Math.floor((Math.random()*contW)%contW);
       var nLeft = Math.floor(((Math.random()*contH)%contH));
       var $child = $(this).clone();       

       $('#container').append($child);
       $child.css({ top:sourceX, left: sourceY })
           .animate({ top: nTop+'px', left:nLeft+'px' }, 200)
           .click(explode);
    }

    $(this).hide();
});

A slight HTML modification:

<div id="container" style="width:400px; height:500px; background-color:yellow;">
    <div class="holder style="absolute; "><img class="cat" 
        src="http://jsfiddle.net/img/logo.png" 
        style="background-color:blue;" />
    </div>
</div>

Check out the JSFidle link here: http://jsfiddle.net/58YWM/8/

Let me know how it turns out!

Best wishes.

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

Difficulty maintaining list formatting in AngularJS and Bootstrap due to ng-repeat functionality

I'm currently working on a project where I need to display content from an array using ng-repeat in Angular. The content is originally in JSON format, but it has been stringified before being added to the array. The problem I am facing is that this c ...

Retrieve the element that is currently being hovered over within the same nested selector

I am facing a challenge in selecting the currently hovered element with a nested selector. The ".frmElement" class is used as the selector. When I hover over the ".frmElement" element at a certain level, all the previous selector elements display the hover ...

Ways to access a particular property of a child component object from the parent component

Is there a way to access a child component's "meta" property from the parent component without using the emit method? I am aware of the solution involving an emit method, but I'm curious if there is a simpler approach to achieving this. // Defau ...

Adjusting iFrame Height to Fit Content Completely

I am looking to create a website where I can have a banner at the top and display another website below it without needing an additional scroll bar within the page. I have tried using an iframe, but I can't seem to get it to display correctly. I want ...

Using JQuery to specify an attribute as "required" along with a value does not function as expected

Something seems off with this: $("#elementId").attr("required", "true"); In Chrome and Firefox, the DOM either displays required as the attribute (with no value) or required="" (empty value). Interestingly, it doesn't make a difference what value w ...

directive ng-click not responding

drawer-card.html (template) <div class="drawer-card-wrapper"> <div class="drawer-card-icon" ngClick="dcCtrl.toggle()"> <i class="icon--{{ icon }}"/> </div> <div class="{{'drawer-card ' + (classesToAdd || '&apo ...

Tips for incorporating theme colors in the "color" prop when employing MaterialUI components

Trying to utilize the colors from my Mui palette as values for the color property in this way: For example: <Tabs indicatorColor="primary.mainGradient" > <Tab /> </Tabs> However, this approach does not seem to wo ...

Numbering the items in ng-repeat directive

I am facing a challenge with my AngularJS directive that is recursively nested within itself multiple times. The issue lies in the fact that the names of items in ng-repeat conflict with those in the outer element, causing it to malfunction. To illustrate ...

Numerous Ajax requests triggering at various intervals on a single webpage

Summary: My task involves retrieving data from a service hosted on multiple servers using C#, and then displaying it to the user/s on a single page through an ajax call. The final output will include charts and progress indicators created with JQuery and s ...

Can I utilize p5.Vector.fromAngle() in Vue JS?

Incorporating P5 into a Vue application can be achieved using the following code snippet: let script = p5 => { p5.setup = _ => { this.setup(p5) } p5.draw = _ => { this.draw(p5) } } this.ps = new P5(script) While functions like ba ...

What is the process for importing the util module in Node.js?

I attempted to use the isDeepStrictEqual() method for object comparison but encountered this error: util.isDeepStrictEqual() is not a function After checking the official documentation, I found out that this method was introduced in Node.js v9.0.0 w ...

Adjusting the Direction of Flex Components

As someone who is new to css and html design, I recently started using flex in my bootstrap designs. My goal was to have the components sorted from left to right direction, similar to how it's done on this site. Now, I am looking to shrink the slider ...

The skipping of crucial text in tab focus is adversely affecting the accessibility of the website

My appbar contains an image link, a warning indicating the user's current environment, and details about the logged-in user. While testing accessibility with a screen reader, I noticed that tab focus skips over the user details in favor of a link in ...

Launching an HTML document with checkboxes already selected

I am attempting to load my HTML page with checkboxes already checked if they were selected on the previous page. The code I currently have is shown below: {% if job.activism %} checkbox logic goes here {% endif %} <br><input type="checkbox ...

How to retrieve JSON data in Angular.js

I'm having trouble accessing a json file in angular.js with the code below. I keep getting an error message and could really use some help! Here is my module : angular.module("demoApp", ['demoApp.factory','demoApp.controllers']); ...

Modify the css of the initial div following a live click

After clicking on the span.submit-comment, I am looking to modify the CSS of a specific div. Can anyone advise me on how to achieve this? I attempted to change the background color of the div in the success section of the script like so: $('div.new ...

Unable to apply margin right to React Material-UI table

I am struggling to add margin to the right of a mui table with no success. Below is the code I have used: <TableContainer> <Table sx={{ mr: 100 }} aria-label="customized table"> <TableHead> <Tabl ...

What is the reasoning behind excluding any JavaScript code between the <script> tags when our intention is solely to incorporate an external JS file?

It's puzzling to me why the author of the "Javascript & Jquery: the missing manual , second edition" recommends the following sentence: When including the src attribute to connect to an external JavaScript file, avoid placing any JavaScript cod ...

api for enhancing images in Laravel app through preview, enlarge, and zoom functionalities

As I work on my website, I aim to display images in a compact space, such as within a 300x300 <div>. What I envision is the ability for users to preview or enlarge these images upon clicking, allowing for a closer and more detailed view. For exampl ...

Everything seems to be functioning properly on the local server, but once the media files or players (mp3 and mp4) are uploaded, the background fails to work entirely

function playMusic() { var songs = [ "pump.mp3", "ybwm.mp3", "bb.mp3", ]; var randomIndex = Math.floor(Math.random() * songs.length); var selectedSong = songs[randomIndex]; var audio = new Audio(selecte ...