Tips for rotating several images at once?

I'm working with the code snippet below:

$(document).ready(function() {
  $(".content-image").each(function() {
    var angle = getRandomAngle();
    $(".content-image").css("transform", "rotate(" + angle + "deg)");
  });
});

function getRandomAngle() {
  return Math.floor(Math.random() * 5) + 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img class="content-image" src="https://via.placeholder.com/150" />
<img class="content-image" src="https://via.placeholder.com/150" />

Currently, this code rotates all images with the same angle. How can I make sure each image has a different angle?

Answer №1

Revise

$(".content-image").css("transform"...

into

$(this).css("transform"...

in order to individually apply the transform to each image in the loop

Answer №2

In the context of the each() loop, using the keyword this allows you to target the current element. To illustrate this, let's update your random number generator to output values between 0 and 360.

$(document).ready(function(){
    $(".content-image").each(function() {
        var rotationAngle = getRotationAngle();
        $(this).css("transform", "rotate(" + rotationAngle + "deg)");
    });
});

function getRotationAngle() {
    return Math.floor(Math.random() * 360);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img class="content-image" src="https://dummyimage.com/200x200/000/fff&text=Unique" />
<img class="content-image" src="https://dummyimage.com/200x200/000/fff&text=Different" />

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

Problem with laravel ajax request

I've spent the entire weekend trying to figure this out, but I can't seem to make it work. It works fine with the 'get' method, but not with 'post'. I'm using Laravel 4 and jQuery. Here's how my JavaScript looks: $ ...

When the page loads, the $.ajax function is triggered to send an ajax request. Upon examining the URL in the Global.asax file, it is found to be

$(function () { $.ajax({ url: "MyAccount/UpdatePassword", type: "post", success: function (response) { $('#view-settings').html(response); hideFlyWithMessage("D ...

Issue with PJAX form updates causing duplication of query string parameters resulting in a 414 Request-URI Too Large error

Here's the code for my ActiveForm with PJAX in the view: <?php Pjax::begin(['enablePushState' => false, 'id' => 'pjax-container']); ?> ... <?php $form = ActiveForm::begin(['method' => 'PO ...

Nested Classes in JQuery

Looking for help with fading in text using jQuery. Despite setting everything up, it doesn't seem to be working. Can someone assist me with this issue? Here is my current code: .nav ul li { opacity: 0; padding: 0px 50px; transition: opacity 2s ease-i ...

Troubleshooting issue with Calendar styling in Bootstrap and SimpleCalendar Rails integration

I am having trouble applying styling to my SimpleCalendar in Rails, using the gem. When I render it, this is what I see: https://i.sstatic.net/kJi7m.png Here is the CSS provided by https://github.com/excid3/simple_calendar: .simple-calendar { table { ...

Is there a way to efficiently access checkboxes by their IDs and toggle classes without the need for redundant classes and functions?

In my current project, I have set up functionality to toggle classes on a table for hiding specific columns. This is determined by checkboxes selected by the user above the table, each checkbox having its own unique ID like "product_1", "product_2", and so ...

Accessing the form element in the HTML outside of the form tag in Angular 2

I am attempting to achieve the following: <span *ngIf="heroForm?.dirty"> FOO </span> <form *ngIf="active" (ngSubmit)="onSubmit()" #heroForm="ngForm"> <div class="form-group"> <label for="name">Name</label& ...

Is there a way to extract all the content from a webpage's body using BeautifulSoup?

Looking to extract text from a medical document webpage for a Natural Language Processing project using BeautifulSoup, but encountering challenges. The specific website in question is located here: The goal is to capture the entire text body by utilizing ...

Is it possible to customize the appearance of the Facebook Like box with a scroll-bar?

I recently added a Facebook like-box to my website, and I'm trying to customize the scroll bar within the iframe. However, I'm struggling to find a way to do so. Does anyone have any ideas on how this can be achieved, or if it's even possibl ...

Trying to understand the strange behavior of HTML parsing with jQuery in Javascript and Firefox

I have been working on a script to parse an HTML page using jQuery. The script runs smoothly in Chrome, IE, and Safari, but I'm facing some unexpected behavior while testing it in Firefox (version 36.0.1). Here's the code snippet: $.ajax({ u ...

Converting nested json objects to HTML format with the help of jQuery

I've been wracking my brain on this issue for quite some time and I just can't seem to crack it. After posting a question, I received some helpful answers and decided to implement the code provided in the second response (be sure to check out my ...

Achieve full height for div without causing it to expand (utilize scrollbar for overflow)

I am looking to achieve a specific layout for my webpage, as shown in the image below: The layout depicted in the image above is created using the following HTML and bootstrap classes: <div className="ContentWrapper d-flex mh-100 flex-row h-10 ...

What is the best way to ensure that `col-sm-4` takes up the full space previously occupied by `col-sm-5` when it is hidden

In tablet mode, I am concealing my col-sm-5 using the class hidden-sm. <div class="row"> <div class="col-sm-4"> </div> <div class="col-sm-5"> </div> <div class="col-sm-3"> </div> </div& ...

Picture featuring a right-angled triangle on the right side

I have been experimenting with creating a complex image effect using CSS only, without any JavaScript. Despite several attempts, I haven't been able to achieve the desired outcome yet. https://i.sstatic.net/sUEaJ.jpg CSS .container{ width: 500p ...

Trouble with executing a jQuery dynamic loop for each item

I have a unique situation where I am dealing with a table containing multiple tables for various users. The number of users can vary, so I am aiming to create a dynamic solution. Below are two sample tables for reference. <div class="timecard"> < ...

The content inside the inner div does not stretch to match the height of its parent element

I want to address a specific issue I am facing with my div structure. Although it may seem similar to other questions on StackOverflow, none of the existing solutions have worked for me. The problem is that I have two child divs inside a parent div. The h ...

How to send variables to a function when a value changes in TypeScript and Angular

As someone who is new to Angular and HTML, I am seeking assistance with the following code snippet: <mat-form-field> <mat-select (valueChange)="changeStatus(list.name, card.name)"> <mat-option *ngFor="let i of lists"> {{i.name}} ...

The functionality of Ajax requests varies across various web browsers

My web app game, Ninja Gold, has been coded using Codeigniter. I have encountered an issue while using Ajax requests to navigate through different routes and retrieve gold amounts from various locations. My ultimate goal was to incorporate continuous back ...

What is the best way to incorporate a unique CSS3 animation and transition on hover?

I've created a CSS3 animation test that adjusts the background-size of an element to create a pulsating effect when clicked, toggling the 'active' class and triggering a transition. However, I'm facing an issue where the animation stops ...

Combining the classes "col" and "col-3" simultaneously

I am utilizing the "col" class to generate 7 equal columns, with a responsive design that features two rows - one with 4 columns and the other with 3. Here is my code: <div class="row mt-20"> <div class="col col-3"> <img ...