Nesting divs that soar within a contained div (not spanning the entire page)

I need the div elements to move within another div container instead of flying over the entire page.

What changes do I need to make in the code to achieve this?

$(document).ready(function() {
  $('.balloon').each(animateDiv);
});

function makeNewPosition() {
  var h = $(window).height() - 50;
  var w = $(window).width() - 50;

  var nh = Math.floor(Math.random() * h);
  var nw = Math.floor(Math.random() * w);

  return [nh, nw];
}

function animateDiv() {
  var el = $(this);
  var newq = makeNewPosition();
  var oldq = $(el).offset();
  var speed = calcSpeed([oldq.top, oldq.left], newq);

  $(el).animate({
    top: newq[0],
    left: newq[1]
  }, speed, function() {
    animateDiv.apply(this);
  });

};

function calcSpeed(prev, next) {
  var x = Math.abs(prev[1] - next[1]);
  var y = Math.abs(prev[0] - next[0]);

  var greatest = x > y ? x : y;
  var speedModifier = .4;
  var speed = Math.ceil(greatest / speedModifier);

  return speed;
}
.balloon {
  width: 50px;
  height: 50px;
  background-color: red;
  position: fixed;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <title>Create a New Pen</title>

  <link rel='stylesheet prefetch' href='http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css'>
  <link rel="stylesheet" href="css/style.css">

</head>

<body>
  <div class='balloon'></div>
  <div class='balloon'></div>
  <div class='balloon'></div>

  <script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
  <script src='http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js'></script>
  <script src="js/index.js"></script>

</body>

</html>

Answer №1

Start by creating a div element with specified height and width in the CSS. Instead of referencing the window dimensions, utilize the class assigned to the div for adjusting the height and width using .height() and .width().

You can choose not to include the balloons within the div in the HTML structure, although I have done so for demonstration purposes.

$(document).ready(function(){
  $('.balloon').each(animateDiv);
});

function makeNewPosition(){
    
    // Fetch viewport dimensions (excluding the div's dimensions)
    var h = $('.sky').height() - 50;
    var w = $('.sky').width() - 50;
    
    var nh = Math.floor(Math.random() * h);
    var nw = Math.floor(Math.random() * w);
    
    return [nh,nw];    
    
}

function animateDiv(){
  var el = $(this);
    var newq = makeNewPosition();
    var oldq = $(el).offset();
    var speed = calcSpeed([oldq.top, oldq.left], newq);
    
    $(el).animate({ top: newq[0], left: newq[1] }, speed, function(){
      animateDiv.apply(this);        
    });
    
};


function calcSpeed(prev, next) {
    
    var x = Math.abs(prev[1] - next[1]);
    var y = Math.abs(prev[0] - next[0]);
    
    var greatest = x > y ? x : y;
    
    var speedModifier = .4;

    var speed = Math.ceil(greatest/speedModifier);

    return speed;

}
.balloon {
width: 50px;
height:50px;
background-color:red;
position:fixed;
    
}
.sky{
  width:100%;
  height:150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html >
<head>
  <meta charset="UTF-8">
  <title>Create a New Pen</title>
  
  <link rel='stylesheet prefetch' href='http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css'>
      <link rel="stylesheet" href="css/style.css">
  
</head>

<body>
<div class="sky">

</div><div class='balloon'></div>
<div class='balloon'></div>
<div class='balloon'></div>
  <script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src='http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js'></script>

    <script  src="js/index.js"></script>

</body>
</html>

Answer №2

To properly format the elements, surround them with a .container div, define the CSS properties for it, and update the code as follows:

// Get viewport dimensions (remove the dimension of the div)
var h = $(window).height() - 50;
var w = $(window).width() - 50;

change to:

// Get viewport dimensions (remove the dimension of the div)
var h = $('.container').height() - 50;
var w = $('.container').width() - 50;

Here is the complete code snippet:

$(document).ready(function(){
  $('.balloon').each(animateDiv);
});

function makeNewPosition(){
    
    // Get viewport dimensions (remove the dimension of the div)
    var h = $('.container').height() - 50;
    var w = $('.container').width() - 50;
    
    var nh = Math.floor(Math.random() * h);
    var nw = Math.floor(Math.random() * w);
    
    return [nh,nw];    
    
}

function animateDiv(){
  var el = $(this);
    var newq = makeNewPosition();
    var oldq = $(el).offset();
    var speed = calcSpeed([oldq.top, oldq.left], newq);
    
    $(el).animate({ top: newq[0], left: newq[1] }, speed, function(){
      animateDiv.apply(this);        
    });
    
};


function calcSpeed(prev, next) {
    
    var x = Math.abs(prev[1] - next[1]);
    var y = Math.abs(prev[0] - next[0]);
    
    var greatest = x > y ? x : y;
    
    var speedModifier = .4;

    var speed = Math.ceil(greatest/speedModifier);

    return speed;

}
.container {
position:relative;
width:400px;
height:200px;
border: solid 1px;
margin: 50px auto 1000px auto;
}

.balloon {
width: 50px;
height:50px;
background-color:red;
position:absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html >
<head>
  <meta charset="UTF-8">
  <title>Create a New Pen</title>
  
  <link rel='stylesheet prefetch' href='http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css'>
  <link rel="stylesheet" href="css/style.css">

</head>

<body>
<div class='container'>
  <div class='balloon'></div>
  <div class='balloon'></div>
  <div class='balloon'></div>
</div>

  <script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src='http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js'></script>

    <script  src="js/index.js"></script>

</body>
</html>

Answer №3

I have made some adjustments. Please refer to the updated code below. Remember to change the CDN jquery request to https

https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js

$(document).ready(function() {
  $('.balloon').each(animateDiv);
});

function makeNewPosition() {

  // Get viewport dimensions (remove the dimension of the div)
  var h = $(window).height() - 50;
  var w = $(window).width() - 50;

  var nh = Math.floor(Math.random() * h);
  var nw = Math.floor(Math.random() * w);

  return [nh, nw];

}

function animateDiv() {
  var el = $(this);
  var newq = makeNewPosition();
  var oldq = $(el).offset();
  var speed = calcSpeed([oldq.top, oldq.left], newq);

  $(el).animate({
    top: newq[0],
    left: newq[1]
  }, speed, function() {
    animateDiv.apply(this);
  });

};


function calcSpeed(prev, next) {

  var x = Math.abs(prev[1] - next[1]);
  var y = Math.abs(prev[0] - next[0]);

  var greatest = x > y ? x : y;

  var speedModifier = .4;

  var speed = Math.ceil(greatest / speedModifier);

  return speed;

}
.balloon {
  width: 50px;
  height: 50px;
  background-color: red;
  position: fixed;
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <title>Create a New Pen</title>
  <link rel='stylesheet prefetch' href='http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css'>
</head>

<body>
  <div class='balloon'></div>
  <div class='balloon'></div>
  <div class='balloon'></div>

  <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>


</body>

</html>

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

Creating an inclusive h1 header with a logo: A step-by-step guide

Is there a way to have a logo linked to the homepage and also have an h1 element that is invisible? This is my current layout: <header id="pageHeader"> <h1> <a href="<?php bloginfo('url'); ?>"> & ...

Provide users with the option to select a specific destination for saving their file

In the midst of my spring MVC project, I find myself in need of implementing a file path chooser for users. The goal is to allow users to select a specific location where they can save their files, such as C:\testlocation\sublocation... Despite r ...

ng-class causing delay in setTimeout execution until form is modified

In my JavaScript code, I have implemented a timeout function: setTimeout(function () { $scope.shadow = 'speller-blue'; currIndex = Math.floor(Math.random() * 2); $scope.currCard = cards[currIndex]; }, ...

sending information from a PHP form to a JavaScript window

Currently, I am in the process of developing a game using javascript and jquery. In this game, when a player interacts with another character, it triggers the opening of text from an external file using the window.open('') function. At the start ...

Maintain the div in its current location when zooming the map

I created a multi-layer map and added a div to it. However, the issue arises when I zoom in on the image, causing the div to change its position unexpectedly. For example, if I place the div over India and then zoom and drag the image, the div ends up in U ...

Send form information using AJAX response

I have successfully implemented a feature where I load an iframe into a div with the id of #output using AJAX. This allows me to play videos on my website. jQuery( document ).ready( function( $ ) { $( '.play_next' ).on('click', fun ...

How can you use JavaScript to assign a data value to a hyperlink?

I'm currently facing an issue with assigning a value to the data-attribute of an anchor tag. Below is the code snippet in question: <script> window.onload = function(){ document.getElementById("setcolor").click(); } var color = "red"; document ...

Establishing a PHP session variable and then initiating a redirect to a new page through the HREF method

I am working on a table that pulls IDs from a MySQL table named auctiontable and displays them in rows. Currently, I can easily append ?aid="1"or ?aid="2" to the end of the href attribute to utilize $_GET. However, I want to prevent users from controllin ...

Utilizing JQuery Ajax to dynamically replace elements using JQuery functions

My issue is as follows... I am using AJAX and jQuery to populate a form. When the user makes a selection from a dropdown menu, AJAX retrieves data based on the choice and populates the form with this data. Sometimes, new elements are created when the AJA ...

Detect changes in class properties using Node.js

Is it feasible to establish direct proxy watchers for class properties in Node.js? class User{ constructor(name){ this.name = name; let pObject = new Proxy(this,{ set: () => { console.log("something cha ...

Tips for choosing elements based on a specific attribute (such as fill color) in D3.js using the SelectAll method

I have various sets of circles on a map - 10 red circles, 10 blue circles, and 10 green circles. Is there a way to use d3 selectAll or select to specifically choose only the red circles? Are there any alternative methods for achieving this? The color of ...

AJAX should prevent page refresh, but sometimes it forces it

This AJAX test page is a simple demonstration using JQuery. When the page is loaded, it displays a button (BUTTON1). Upon clicking on BUTTON1, it will execute react.php using script.js. The react.php will then replace BUTTON1 with BUTTON2 using a span elem ...

Exploring the Enzyme library in React to trigger an onClick event with a specific parameter

In my quest to simulate an onClick method in my unit tests using Enzyme for React, I have encountered various tutorials on simulating an onClick event that takes an event e. For example: handleClick(e) { // Does something } .... <MyComponent onCli ...

Encountering a problem with the Ionic Modal Slider: unable to locate the matching element associated with delegate-handle= when using $

I am encountering a problem with my Ionic application that features multiple Angular controllers. Specifically, I have a LoginCtrl and RegisterCtrl controller set up. The issue arises when I try to trigger a modal with a slider from the RegisterCtrl by usi ...

What could be causing the jQuery change function to stop working after loading HTML with AJAX?

When loading a form, I use AJAX to dynamically populate a select element from a PHP file. Previously, my change function was working fine (it displayed another input when 'other' was selected). However, after implementing the dynamic AJAX populat ...

The tableize-table R function functions effectively in .html format, but unfortunately does not appear correctly when displayed in Gmail using MIMEText

Hi there, I am a beginner working with HTML. I have the following settings in my .html file, and it displays correctly when opened in a browser like Chrome or Safari. (in browser) https://i.sstatic.net/O6YoC.png --> (failed in Gmail) https://i.sstatic. ...

Challenges with jQuery parent method reaching the grandparent element

Hey, I'm a newbie to jQuery and I'm trying to make changes to divs that are two levels above the function trigger: Here's my initial attempt: I try to locate the closest '.node' which is the parent of all other divs and then modif ...

Is it possible to create a similar design that is also responsive?

I've been struggling to create a header for a website project I'm working on. My goal is to design something like the image below: https://i.sstatic.net/szQGf.jpg The biggest challenge I'm facing is making this design responsive. The point ...

Validation of dynamically generated name fields using radio button group

CODE: html <form id="myform" type="post"> <fieldset id="myid1"> <input id="entries_8490_burn_id_1" name="entries[8490][burn_id]" value="1" type="radio"/> <input id="entries_8490_burn_id_2" name="entries[8490][burn ...

Can values be extracted from a JSON object that is saved in a separate JavaScript file?

In my current project, I am creating unique tables dynamically and displaying them using JavaScript after making an AJAX call. Instead of writing individual code for each table, I'm looking to establish a standard layout where I can customize the desi ...