Repositioning a variable number of divs as the cursor hovers over the target area

Can anyone show me how to generate div elements in a loop using jQuery and change their position with the "mouseover" function? I've tried some code, but the positioning isn't changing correctly. Any suggestions on what needs fixing?

var r, g, b, counter, i;
//generate random number between 20 and number.
function generateRandomNumber(number) {
  return Math.floor(Math.random() * (number - 20)) + 20;
}
// maximum number of random elements is 30.
counter = generateRandomNumber(30);
for (i = 0; i < counter; i++) {
  var div = $("<div/>");
  div.id = "randomlyPlaced" + i;
  //random style for the elements
  r = generateRandomNumber(255);
  g = generateRandomNumber(255);
  b = generateRandomNumber(255);
  $(div).css({
    position: "absolute",
    background: "rgb(" + r + "," + g + "," + b + ")",
    height: generateRandomNumber(200) + "px",
    width: generateRandomNumber(400) + "px",
    top: generateRandomNumber(500) + "px",
    left: generateRandomNumber(1000) + "px"
  });
  //append the elements to body.
  $('body').append(div);
  //change the position of the element.
  $("#" + div.id).mouseover(function() {
    $(this).animate({
      top: generateRandomNumber(500) + "px",
      left: generateRandomNumber(1000)
    }, 500, "linear");
  })
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<!DOCTYPE html>
<html>

<head>
  <title>Randomly Placed Animated rectangles</title>
</head>

<body style="width: 80%; height: 80%; background-color :rgb(164, 173, 
    226); position:relative;">
  <div id='+div.id+'></div>
</body>

</html>

Answer №1

To properly utilize the div object, it is essential to reference the actual object itself rather than using "#"+div.id. This is due to the fact that the id method only works when the element is already present in the DOM, which may not be the case when you are dynamically creating div elements.

$(div).mouseover(function(){
  $(this).animate({
         top: generateRandomNumber(500) + "px", 
         left:generateRandomNumber(1000)
      },500,"linear");
});

For a demo, see this fiddle https://jsfiddle.net/stdeepak22/t5w6cm9x/

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

Extract data from a CSV table stored in a variable using node.js

Currently, I am working on a node application that can potentially result in a CSV formatted table being stored in a variable. I am interested in converting this CSV data into a JSON format. I have explored various modules, but it appears that most of th ...

Interact with users on a website by using PHP to process form data

Here is the code snippet I am struggling with: <form action="profiles.php" method="POST" name="SearchSimple" id="SearchSimple" > <input name="search" id="s" style="width: 150px;" type="text"> <a style="display: inline-block; widt ...

Utilize JavaScript to apply the CSS -moz-transition

Creating a web application and using CSS3 to transform a div, but encountering a challenge with Firefox. Able to make Chrome, Opera, and IE work properly, except for Firefox. Here's how I'm setting up the working browsers: obj.style.WebkitTrans ...

What steps can I take to design a functional hamburger menu?

After multiple attempts to create a hamburger menu, I have hit a roadblock. Clicking on the menu icon transforms it into an 'X', but unfortunately, it does not trigger the opening of the menu. Despite days of effort and research, I have yet to fi ...

Struggling to resolve a common issue in Migration? It seems that a raw query in Sequelize is adding backslashes that are causing errors when inserting values into the database

During migration, data is taken from one table and inserted into another. However, an issue arises when Sequelize adds backslash escape characters to the 'v_occupation' value, causing insertion errors. I have attempted various replacements and m ...

Should a React application perform a complete refresh when a file is reloaded?

Recently, I delved into the world of React and learned about one of its key benefits: updating only the necessary DOM elements. However, as I began building an app from scratch, I encountered a situation where every time I saved the .js file, it resulted ...

What is the best way to incorporate a custom modal created with HTML/CSS into my Bootstrap website?

I am facing an issue with the modal implementation on my bootstrap website. The modal is supposed to open when a user clicks a button. Strangely, it was working perfectly fine on another HTML/CSS file, but once I added it to this Bootstrap file, it stopped ...

How can I run an ajax request in a loop where it only proceeds to the next loop value upon successful completion?

I'm facing a simple but important issue: running 3 Google Maps place URLs and displaying the results after each one is successful. Here's my current approach: var values = ["url1", "url2", "url3"]; values.forEach(function(value, i) { var ...

Jest fails to pass when encountering the double colon

Having issues testing a React app using Jest. I encounter errors when running my code: FAIL src\App.test.js ● Test suite failed to run C:/Users/user1/Projects/map-editor/src/App.js: Unexpected token (40:33) 38 | <div cla ...

Are you looking for a way to prevent the default behavior of an event in angular-ui-router 1.0.x? Check out

Recently, I made a change in my code where I replaced $stateChangeStart with $transitions.onStart $rootScope.$on('$stateChangeStart', function(e, ...){ e.preventDefault(); // other code goes here... }); Now, the updated code looks lik ...

The Javascript Ajax loader gif is malfunctioning

I'm currently working on creating an Ajax loader gif using XMLHttpRequest. When I type something in the input field, a list of different words appears. This technique is commonly used in search engines as you type in the search box. However, I am als ...

The Importance and Purpose of Incorporating a Callback

Understanding asynchronous operations and callbacks has been a challenge for me. To improve my familiarity with these concepts, I've been studying code examples that utilize them. However, there's one aspect of this specific code snippet that con ...

Display the button exclusively on responsive mobile views

I'm looking to enhance my website by adding a call support button with a responsive design feature. The goal is to display the button exclusively in mobile view and replace it with text in other views. Encountering challenges in toggling the visibili ...

Mastering the use of node cluster mode in conjunction with agenda cronjobs

Currently, I am utilizing nodejs and agenda to run cronjobs. With a total of 10 cronjobs in place, the process is taking longer as nodejs is single-threaded and they all run simultaneously. In an attempt to resolve this issue, I experimented with pm2 by e ...

tips for using jquery ajax to send a json array via post request

I am facing an issue while trying to send an array in an AJAX JSON post request. The code seems to have some errors. Can anyone help me fix this code? HTML <table width="200" border="1"> <tr> <td>table</td> ...

Utilizing AngularJS for Your Business Website

We are in the process of developing a new commercial website to replace our current one. Concerns about performance are on our minds. The amount of data we have per page is not very heavy, with a maximum of 150 data binds. We plan to use AngularJS 1.2 t ...

Tips for creating a dynamic sticky footer

Seeking out a solution for a sticky footer that adjusts its height based on the width of the browser. Creating sticky footers in flexible designs can be tricky. I've come across various suggestions, discussions, and fixes for implementing sticky foot ...

How can I set the textbox focus to the end of the text after a postback?

In my ASP.Net form, there is a text box and a button. When the user clicks the button, it adds text to an ASP:TextBox during a postback (it adds a specific "starter text"). After the postback, I want the focus to be set to the end of the text in the textbo ...

Arrange an array by the occurrence rate of its elements within objects contained in another array, using Javascript

I found the explanation to be rather complex. Essentially, my goal is to iterate through each object in the 'objects' array, analyze the 'choice' values, tally the frequency of each letter, and then arrange the original arrays based on ...

An array of dictionaries that are the same except for one dictionary containing an unspecified key

A while ago, I wrote some sample code to generate Euler diagrams from an array of dictionaries. Strangely enough, it only works when the array is explicitly defined in my .js file; using input from a .json file to construct it incrementally does not yield ...