feknaz feknaz - 1 year ago 98
CSS Question

JavaScript random margin for div only working on first div only

I'm displaying images from all users. And I want them to appear in different places. I have this code right now:

@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 problem is that the margin changes for first div only.

Answer Source

id attributes have to be unique in the DOM. The issue you're seeing is because of this expectation. To work with multiple grouped elements, use a class instead:

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

Then in JS you need to loop over those elements and set the margin-top individually:

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

Or in jQuery:

$('.fighter').css('margin-top', function() {
  return Math.floor(Math.random() * 100) + "px";
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download