Shuffle various div elements in a random pattern using jQuery

Check out this jQuery fiddle I'm using for my project: http://jsfiddle.net/BREvn/5/

Currently, I am creating a bird shooting game where the number of birds increases with each level. These birds are essentially represented by div elements, but I am facing an issue where they keep going out of the container and appearing in the bottom right position. What I want is for the divs to only touch the borders of the container.

Here is a snippet of my code:

<!DOCTYPE html>
<html>
<head>
 <script src="/js/jquery-2.0.2.min.js"></script>
<style>
div#container {height:50%;
                   width:50%;
       border:2px solid white;           



    }
    .a {
width: 120px;
height:120px;

position:relative;

}
</style>

 <script type="text/javascript">
 function randomFromTo(from, to) {
                return Math.floor(Math.random() * (to - from + 1) + from);
            }

            function moveRandom(obj) {
                var cPos = $('#container').offset();
                var cHeight = $('#container').height();
                var cWidth = $('#container').width();
                var pad = parseInt($('#container').css('padding-top').replace('px', ''));
                var bHeight = obj.height();
                var bWidth = obj.width();
                maxY = cHeight ;
                maxX = cWidth;
                minY = cPos.top + pad;
                minX = cPos.left + pad;
                newY = randomFromTo(minY, maxY);
                newX = randomFromTo(minX, maxX);

                obj.animate({
                    top: newY,
                    left: newX
                }, 1000, function () {
                    moveRandom(obj);
                });
            }

            $('.a').each(function () {
                moveRandom($(this));
            });
</script>
</head>
<body>

<div id="container">
        <img src="graphics-birds-917288.gif" class='a'/>
        <img src="graphics-birds-917288.gif" class='a'  />
        <img src="graphics-birds-917288.gif" class='a' />
        <img src="graphics-birds-917288.gif" class='a' />
        <img src="graphics-birds-917288.gif" class='a' />
    </div>
</body>
</html>

Answer №1

An important component has been eliminated

maxY = cHeight;
maxX = cWidth;

It should actually be

maxY = cPos.top + cHeight - bHeight;
maxX = cPos.left + cWidth - bWidth;

Currently, you are allowing the top of each image to reach the height of the container - this slight adjustment ensures that it reaches the height of the container MINUS the height of the object

In your code, you have omitted these adjustments for some reason, even though they are included in the example fiddle (+ padding, which is unnecessary for your specific scenario)

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

I'm encountering a Python Selenium error related to the timing of webpage loading

# Specifying the path to the chromedriver program service = Service('C:\Program Files (x86)\Google\chromedriver.exe') service.start() # Opening a remote connection with robinhood website using the driver driver = webdriver.Remote( ...

Preloading images before loading a div using JavaScript

Can you walk me through implementing object first and then mergeObject in JavaScript? I have an interesting scenario where I need to display the original list followed by a merged list after a short delay. How can I achieve this using JavaScript? Specific ...

Return an array to Ajax using php and mysqli

Currently, I am immersed in a mini project that involves working with two MySQL database tables - one for questions and the other for answers. The answers table holds the question ID. I have a query in an AJAX call that retrieves one question and its four ...

Embedding the @media tag directly into a class for simplification and to eliminate redundancy

For the complete css/html code sample, please visit: https://jsfiddle.net/menelaosbgr/jbnsd9hc/1/ Here are two specific definitions I am working with: /* Dropdown Content (Hidden by Default) */ .dropdown-content { display: none; position: absolut ...

Sending HTML data using jQuery's post method

TestData = { Test: function (eventId) { var obj = new Object(); obj.Content = 'Hello<br>world.'; var data = $.toJSON(obj); alert(data); $.post(SvConstant.GetBaseUrl() + "/Services/PageHandler/Tes ...

Using div elements to mimic the layout of tables with row spans

<div class="container"> <div class="box1">1</div> <div class="box2">2</div> <div class="box3">3</div> </div> .box1 { border: 1px solid red; float: left; width: 20px; } .box2, .box3 { ...

Overlay text on an image using a CSS grid

I'm working on a CSS grid layout where I want to overlay text on an image. Below you can see the code I currently have without the text overlay. .sbp-item12 { grid-row: 6 / 7; grid-column: 9/13; height: 250px; } <div ...

Using AJAX to Capture PHP Error Responses

I have implemented a form where users can upload profile pictures and see live validation feedback without refreshing the page. I am currently using AJAX for this functionality, but it seems that the requests are not reaching the PHP file. Also, after subm ...

The nestedSortable plugin fails to detect elements once the HTML has finished rendering

If I add multiple elements to a nested sortable list, they automatically go to the root and can be dragged around normally. When I drag a parent element, the child moves along with it as shown in the image below. https://i.sstatic.net/l1l1m.png After savi ...

Issues with audio and video playback intermittently occurring on Sencha Touch 2

As a beginner with Sencha Touch 2, I am currently working on uploading images onto an iPad using Xcode. My app has audio playing on the home screen, and I want the video to start playing and the audio to stop when a specific tab is selected. However, the ...

Synchronized loops in jQuery using the .each method

I'm having trouble getting the ajaxStop function in jquery to work. Any suggestions on how to make it fire? My goal is to iterate through each anchor tag and update some content within it. After that, I want to use the ajaxstop event to trigger a scr ...

Using URL parameters in Node.js applications

I am encountering an issue with my nodejs setup, and I am hoping someone can assist me. My challenge lies in trying to pass a parameter with a specific value to a page.html file, like this: page.html?s=1 However, I am encountering a problem where the pa ...

Modify an HTML table and record any modifications as POST requests using Javascript

As a beginner in JavaScript and HTML, I am open to corrections if I am not following the correct practices. Recently, I delved into editing an HTML form table. {%extends 'base.html'%} {%block content%} <html> <body> <h4> Search ...

Guide for positioning the p-checkbox label to the left of the checkbox using PrimeNG

<p-checkbox name="group1" [value]="true" label="Outsourcing" style="margin: 0 25px"></p-checkbox> I am looking to change the position of the label from the right to the left ...

How to retrieve a string from a regular expression in Javascript without [Object object] output

Within my code, there exists a parent form component and a child component used for auto-completing text input. The Parent component passes an array of objects named autoCompTxt, consisting of name and id fields, to the Child component. //Parent: const [ob ...

Passing a sophisticated data structure to the controller, where some of the attributes are derived from a separate partial view

I have a model for my view that includes information about appointments and their recurrence. It looks something like this: public partial class AppointmentModel { public appointment Appointment { get; set; } public appointmentRecurrence Rec ...

"Receiving a rendered HTML page instead of an SQL result from a jQuery POST request

Currently, I am utilizing codeigniter within my application and have implemented a jQuery post function that is performing flawlessly. $.post('getticketstacktype', {ticketnumber:ticketnumber},function(result) { alert(result); } Subsequently, I ...

How Can You Create a Sliding List Animation (Up/Down) Using Angular and Twitter-Bootstrap?

Hey, can you give me a hand with this? :) I'm attempting to create a sleek sliding up and down list in Angular, but I'm struggling to make it work. My CSS skills are not very advanced, so I'm still learning and gave it my best shot: http:// ...

Is there a way for me to configure my website so that when a link is clicked, my PDF file will automatically open in Adobe

I've been facing an issue where I need my users to access a specific PDF file from a link on my website. Currently, the PDF opens in a separate tab next to my site, but ideally, I would like it to be forced to open in Adobe Reader directly. Is this ac ...

Backstretch malfunctioning

Looking to enhance my webpage with a backstretch image slideshow effect using the body background, but encountering issues. The code I have included before the </head> tag is: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery ...