The JavaScript random margin functionality is only applying to the first div and not working on any additional

I am working on a project where I need to display images from various users and want them to appear in different positions. Here is the code I am currently using:

@foreach($users as $user)
  <div class="col-md-2 text-center" id="fighter">
    <img src="{{$user->char_image}}">
  </div>
@endforeach
var fighter = document.getElementById('fighter');
fighter.setAttribute("style", "margin-top:" + Math.floor(Math.random() * 100) + "px;");

The issue I am facing is that the margin changes only for the first div.

Answer №1

id attributes must be unique within the DOM structure. The problem you are encountering is a result of this requirement. To handle multiple grouped elements, it is recommended to utilize a class instead:

@foreach($users as $user)
  <div class="col-md-2 text-center fighter">
    <img src="{{$user->char_image}}">
  </div>
@endforeach

Subsequently, in JavaScript, you will need to iterate through those elements and specify the margin-top individually:

Array.from(document.getElementsByClassName('fighter')).forEach(function(el) {
  el.style.marginTop = Math.floor(Math.random() * 100) + "px";
});

Alternatively, using jQuery:

$('.fighter').css('margin-top', function() {
  return Math.floor(Math.random() * 100) + "px";
});

Answer №2

It could be that the issue lies in using IDs to reference the timer containers. When you utilize getElementById, it will always target the first element with the specified ID.

An alternative solution is to use getElementsByClassName(), which will retrieve all instances of the particular class.

Consider trying this method:

In your HTML markup:

@foreach($users as $user)
  <div class="col-md-2 text-center fighter">
    <img src="{{$user->char_image}}">
  </div>
@endforeach

For JavaScript functionality:

var elements = document.getElementsByClassName('fighter');

Array.prototype.forEach.call(elements, function(element) {
  element.setAttribute("style", "margin-top:" + Math.floor(Math.random()*100) + "px;")
})    

PS: Consider exploring jQuery as it can simplify your work and provide cleaner implementations.

If you encounter any difficulties, feel free to reach out :)

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

What are the drawbacks of using global variables?

Is There a Performance Impact to Using Global Variables in JavaScript? Why is it bad to make elements global variables in Javascript? The concept of global variables in JavaScript has long been frowned upon, likened to using street slang compared to m ...

Issue with BeginCollectionItem method in ASP MVC3 causing null values to be returned

I recently came across Steve Sanderson's blog post on binding collection items to a model in ASP.NET MVC. Despite following the instructions, I encountered some unexpected behavior that I couldn't find any solutions for online. Within my model B ...

Is there a way to disable responsiveness on a website?

Currently, I am in the process of developing a responsive style sheet that is live on our website. However, it seems to display poorly on non-desktop devices due to being a work in progress. I am considering using JavaScript to enforce the desktop layout ...

Switch the date format to 'YYYY-MM-DD' when using the DateRangePicker

$('#reportrange').daterangepicker({ startDate: start, endDate: end, ranges: { 'Today': [moment(), moment()], 'Yesterday': [moment().subtract(1, 'days'), moment().subtract ...

The XSLT extension in jquery consistently clears the field

Within this code snippet, there is a div element that serves as a jquery modal dialog. <div id="searchResultsDialog" title="Search Results"> <div id="searchResults"></div> </div> Following that, there is code provided to popul ...

Managing additional components in request JSON when communicating with DialogFlow, previously known as Api.ai

My current challenge involves enhancing the information sent in a JSON request from my application to DialogFlow. While I am familiar with triggering events to send data calling an intent through the method described in Sending Parameters in a Query Reques ...

Creating a Fresh Row - Steps to Activate Datepickr on a Copied Row

Whenever a button is pressed, a row in a table duplicates itself. Here is a snippet of the code: <tr> <td valign="top"><input type="text" name="session[]" size="15"></td> <td valign="top"><textarea name="descr[]" cols="40" ...

What could be causing the nested HTML list to malfunction?

Can you take a look at the code below and help me identify what's wrong? I'm trying to organize Add Result and Manage Result under Result. Additionally, Add1 Result and Add2 Result should be nested under Add Result, creating a hierarchy. However, ...

There is an error in the regular expression that has not been caught: the forward slash is

I have a TableCell with the following structure: <asp:TableCell CssClass="plusTd button" ID="plusCell"> </asp:TableCell> Then, I decided to add a property to it like this: plusCell.Attributes.Add("onclick", "/Add.aspx ...

Guide on how to return to previous page post form submission with PHP

Hey everyone, I'm currently diving into the world of PHP and working on a basic input form for a webpage. The issue I'm facing is that upon submitting the form, the website redirects to a blank page instead of going back to the original one. I&ap ...

"Make sure the last if statement is always the one being executed

I have been using angularjs to develop a mini quiz application. I created 4 if statements, but for some reason, the last condition is always executed even if no answers have been selected. Why does $scope.makeup consistently display You should have makeup ...

Checking if Javascript is loaded using a JQuery getScript call

I would like to improve the performance by loading a JavaScript file upon a click event instead of during the initial page load. How can I check if the JavaScript file has already been loaded? Currently, I am using a global variable to track the 'loa ...

Conceal PHP variable using Cascading Style Sheets

Looking for a solution to this issue, but can't seem to find it anywhere! I need to hide the suffix variable from displaying using CSS or another method. When I simply remove it from the code, the whole site breaks for some reason. Here's the c ...

Steps for using jQuery to drag a div and drop it into another div without allowing the div to move afterwards

What is the process of dragging and dropping a div into another div using jQuery while ensuring that the div does not move after being dropped? ...

CSS rule for elements in a disabled state

Currently, I am utilizing AngularJS to manage the enabling and disabling of image buttons. Despite my attempts to use a CSS selector to display them as transparent once disabled, it is not working as expected. While testing with a provided example that app ...

Making a jQuery AJAX request for JSON from a separate domain

My goal is to send an AJAX request to , expecting JSON data in return (not sure if JSONP) However, when I click on the button to make the AJAX request, I encounter this issue: http://prntscr.com/8xswr1 (Google Chrome Console) Upon double-clicking ' ...

Unable to scroll to top using div scrollTop() function

Here's the fiddle I mentioned: http://jsfiddle.net/TLkmK/ <div class="test" style="height:100px;width:70px;overflow:auto"> Some text here that needs scrolling. </div> alert($('.test').scrollTop()); Feel free to scroll down ...

Using Jquery select2 to transfer and fetch information

Hey there, I've been experimenting with the jquery select2-plugin and I wanted to share the basic usage: Here's a simple example: <select style="width:300px" id="source"> <optgroup label="Alaskan/Hawaiian Time Zone"> < ...

The click event in jQuery is being blocked by the use of "display:none

Currently, I have implemented a search box feature with search suggestions: <input id="searchBar" /> <div id="searchSuggestion"></div> The searchSuggestion div is dynamically updated using jQuery ajax whenever an input is entered (imple ...

Ensuring Form Validity with jQuery for Exclusive Radio Buttons

How can I display an error message when a radio button value is not equal to a specific value? I have a series of yes/no questions and want to show disclaimers under each set of buttons if the value provided is null or different from what is required. Most ...