Display an image from the API that rotates when hovered over with the mouse

Currently, I am fetching data from pokeapi.co and dynamically inserting it into a table. This data includes various stats and an image. My goal is to make the image rotate when hovered over. While creating the table, I added an id="pokeImage" dynamically. Initially, I attempted to achieve this using CSS:

 #pokeImage:hover {-webkit-transform: rotate(360deg);
      transform: rotate(360deg);}

and also with jQuery:

$('#pokeImage').on('click', function () { 
$(this).css({ 
    transform: 'rotate(' + (Math.random()*45+45).toFixed(3) + 'deg)'
}); 

However, these approaches were ineffective. I'm seeking guidance on how to accomplish this task. Any advice would be greatly appreciated. Thank you.

EDIT: Here is how I am fetching data, populating a table, and displaying it:

$('#getPokemons').click(function(){
var table = document.createElement('table');
        table.className = "table table-condensed";
        table.setAttribute("id", "ajaxTable");

        var header = document.createElement('tr');
        header.innerHTML = '<th> Name </th><th> Image </th><th> HP </th>';
        header.setAttribute("id", "tableHeader");
        table.appendChild(header);

var random = Math.floor(Math.random()*100);
for(var i = random ; i <= random + 10; i++){
$.ajax({
    type: "GET",
    url: "http://pokeapi.co/api/v2/pokemon/"+i+"/",
    dataType: 'json',
    success: function(response){
        var name = response.forms[0].name;
        var imgUrl = response.sprites.front_default;
        var hpName = response.stats[5].stat.name ; 
        var hpVal= response.stats[5].base_stat;

        var row = document.createElement('tr');
        row.innerHTML = '<td>' + name + '</td>' + '<td>' + '<img id="pokeImage" src ="'+imgUrl+'"/>' + '</td>' + '<td>' + hpVal + '</td>';
        $('#pokedex1').append(row);

    }
});}    $('#pokedex1').append(table);});

Answer №1

Check out the code snippet below for an example of it working with the mouseover event

$('#pokeImage').on('mouseover', function () { 
   $(this).css({ 
      transform: 'rotate(' + (Math.random()*45+45).toFixed(3) + 'deg)'
   }); 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="pokeImage" src= "http://images.indianexpress.com/2017/06/oneplus5_final_image.jpg">

Updated version of the code snippet:

<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="getPokemons" value="submit">Click</button>
<div id="pokedex1"></div>
<script>
$('#getPokemons').click(function(){
var table = document.createElement('table');
table.className = "table table-condensed";
table.setAttribute("id", "ajaxTable");

var header = document.createElement('tr');
header.innerHTML = '<th> Name </th><th> Image </th><th> HP </th>';
header.setAttribute("id", "tableHeader");
table.appendChild(header);

var random = Math.floor(Math.random()*100);
for(var i = random ; i <= random + 10; i++){
$.ajax({
type: "GET",
url: "https://pokeapi.co/api/v2/pokemon/"+i+"/",
dataType: 'json',
success: function(response){
var name = response.forms[0].name;
var imgUrl = response.sprites.front_default;
var hpName = response.stats[5].stat.name ; 
var hpVal= response.stats[5].base_stat;

var row = document.createElement('tr');
row.innerHTML = '<td>' + name + '</td>' + '<td>' + '<img id="pokeImage" src ="'+imgUrl+'" onmouseover = "rotateImage(event)"/>' + '</td>' + '<td>' + hpVal + '</td>';
$('#pokedex1').append(row);
}
});
}    
$('#pokedex1').append(table);
});
function rotateImage(event) {
$(event.target).css('transform', 'rotate(' +  (Math.random()*45+45).toFixed(3) + 'deg)');
}
</script>
</html>

Added mouseout event

<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="getPokemons" value="submit">Click</button>
<div id="pokedex1"></div>
<script>
$('#getPokemons').click(function(){
var table = document.createElement('table');
table.className = "table table-condensed";
table.setAttribute("id", "ajaxTable");

var header = document.createElement('tr');
header.innerHTML = '<th> Name </th><th> Image </th><th> HP </th>';
header.setAttribute("id", "tableHeader");
table.appendChild(header);

var random = Math.floor(Math.random()*100);
for(var i = random ; i <= random + 10; i++){
$.ajax({
type: "GET",
url: "https://pokeapi.co/api/v2/pokemon/"+i+"/",
dataType: 'json',
success: function(response){
var name = response.forms[0].name;
var imgUrl = response.sprites.front_default;
var hpName = response.stats[5].stat.name ; 
var hpVal= response.stats[5].base_stat;

var row = document.createElement('tr');
row.innerHTML = '<td>' + name + '</td>' + '<td>' + '<img id="pokeImage" src ="'+imgUrl+'" />' + '</td>' + '<td>' + hpVal + '</td>';
$(document).on("mouseover", "#pokeImage", rotateImage);
$(document).on("mouseout", "#pokeImage", reRotateImage);
$('#pokedex1').append(row);
}
});
}    
$('#pokedex1').append(table);
});
function rotateImage(event) {
$(event.target).css('transform', 'rotate(' + 355 + 'deg)');
}
function reRotateImage(event) {
$(event.target).css('transform', 'rotate(' + 0 + 'deg)');
}
</script>
</html>

Answer №2

Perhaps this demonstration can offer some clarity. The rotation effect is functioning even without the use of JavaScript.

.someImage {
  width: 100px;
  height: 100px;
  background-color: blue;
}

.someImage:hover {
  transform: rotate(45deg);
}
<div class="someImage"></div>

Answer №3

You have mistakenly used the incorrect syntax for the .css selector. The correct syntax should be .css( propertyName, value ), as outlined in the documentation

In this scenario, the proper code to use is:

$(this).css('transform', 'rotate(' + (Math.random()*45+45).toFixed(3) + 'deg)')); 

Refer to the snippet below for a functional demonstration.

$('#pokeImage').on('mouseover', function () { 
  $(this).css('transform', 'rotate(' +  (Math.random()*45+45).toFixed(3) + 'deg)');
}); 

// To revert the rotation when not hovering
$('#pokeImage').on('mouseout', function () { 
  $(this).css(
    'transform', 'rotate(0deg)');
}); 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="pokeImage" src="http://placehold.it/100x70">

If you are dynamically adding elements (e.g., through an AJAX request), ensure to add the event handler dynamically too. Follow this approach:

 /* ... */

var row = document.createElement('tr');
row.innerHTML = '<td>' + name + '</td>' + '<td>' + '<img id="pokeImage" src ="'+imgUrl+'"/>' + '</td>' + '<td>' + hpVal + '</td>';

$(row).on('mouseout', function () { 
  $(this).css(
    'transform', 'rotate(0deg)');
});

$('#pokedex1').append(row);

/* ... */

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

Avoid using the JQuery IIFE outside of the document ready function as it is considered a

Hey there! I've been coming across a puzzling "pattern" lately that doesn't sit well with me. The code seems messy and lacks clear structure. I've included a sample of the code for context. Is declaring all those IIFEs outside the document ...

Obtaining a byte array using the file input method

var profileImage = fileInputInByteArray; $.ajax({ url: 'abc.com/', type: 'POST', dataType: 'json', data: { // Other data ProfileImage: profileimage // Other data }, success: { } }) // Code in Web ...

JQuery WCF Service is returning a 400 Bad Request response

I developed a WCF web service in ASP.NET 4.5 using VS2012 that delivers a JSON response successfully via the built-in webservice client. The endpoints are correctly configured in the Web.config file. However, I encountered an issue on the client side with ...

An error has occurred in React with a nested JSON object, suggesting that it may actually

I encountered an interesting error with my React file using Axios. While the data retrieval from my post works fine, I am facing a problem when trying to display all posts on one page. Despite my efforts to find a solution, I have not been successful. Bel ...

Is it possible to incorporate a variable into an object?

If you are wondering whether it is possible to utilize a variable in the following scenario, the reason for my inquiry is connected to the potential of utilizing an input element to dynamically modify the variable: var str = "pineapples" var cost = { pine ...

Is there a way to determine if a WordPress query contains additional posts?

I am currently using AJAX to filter and load posts into a container. My goal is to display only 6 posts at a time and show a "load more" button if there are additional posts beyond the initial 6. I would like to avoid creating separate pages for each set o ...

"The process of updating a div with MySQL data using Socket.io on Node.js abruptly halts without any error message

Embarking on a new project using socket.io has been quite the learning experience for me as a beginner. Despite extensive research, I managed to reach the desired stage where I have divs dynamically populated with data fetched from MySQL. In my server.js f ...

What is the process of utilizing an npm package as a plain JavaScript library through require and module export?

Hey there, I'm a bit unsure if I'm on the right track with my question, but here it goes: What steps do I need to take to modify a node.js package for use as a standalone embedded script/library in HTML? How can I invoke a class constructor in ...

How can jQuery be prompted to execute a query at regular intervals every X hours?

I'm facing some issues with events in PHPMyAdmin as I do not have super user permissions. Despite contacting my host for help, they have not been cooperative. As a solution, I am considering running a specific PHP query every hour. Is this feasible? ...

What is the best way to update JSON data using JQuery?

I apologize for posing a seemingly simple query, but my understanding of JavaScript and JQuery is still in its early stages. The predicament I currently face involves retrieving JSON data from an external server where the information undergoes frequent ch ...

What are some ways to condense this Angular/TS code for improved performance and readability?

I am in need of assistance with refactoring a method called getBaseUrl(). This method assigns a specified string value to this.baseURL based on the input serviceType. getBaseUrl(serviceType: string, network?: string) { // Method logic to determine base ...

Is it possible to establish a CSS minimum width that is relative to a different element?

Is it possible to set the min-width of a submenu in CSS to be equal to that of the corresponding link in a navigation menu? I am using LESS for my styling. <ul> <li> <a href="">Item FooBarBaz</a> <ul class="submenu"&g ...

How to display specific JSON objects that meet particular criteria in HTML cards using Ionic and Angular?

As a beginner in Ionic/Angular, I am attempting to fetch data from a JSON file and display it using cards in the HTML. The JSON contains numerous objects that are either marked as "deTurno == true" or "deTurno == false". Here is what I have so far: publi ...

struggle to locate / Node.js Error

I followed the tutorial located at and implemented the following code. // Module dependencies. var application_root = __dirname, express = require( 'express' ), //Web framework path = require( 'path' ), //Utilities for dealing with fi ...

Combining Python Bottle with Polymer Paper Elements

My website currently has a variety of forms where users input information, which is then used to calculate and display new content using Javascript. I rely on Python Bottle for user registration, form auto-filling from the backend and database management. ...

Executing multiple HTTP requests simultaneously in groups using an asynchronous for loop for each individual request

I'm currently working on running multiple requests simultaneously in batches to an API using an array of keywords. Read Denis Fatkhudinov's article for more insights. The issue I'm facing involves rerunning the request for each keyword with ...

Unable to load JSON information into an ExtJS grid

I have exhausted all the solutions I found (there are many on Stackoverflow) in an attempt to fix my extjs store issue. Despite ensuring that the grid is displayed correctly, the data still refuses to show up. Feeling perplexed, I am sharing the "store" co ...

Receiving a k6 response that includes a JSON object with a lengthy integer value

During a performance test, I encountered an issue where the response contained items like: {"item":{"id":2733382000000000049}} When parsed using k6's response.json(), it appeared as : {"item":{"id":273338200000 ...

Troubleshooting issue: AngularJS not receiving NodeJS GET requests

I recently developed a web application for sharing photos. Currently, I am working on a route that is designed to fetch and display the photos of all users from an array. The code for the route is as follows: router.get('/getphotos',function(re ...

What is the reason that when we assign `'initial'` as the value for `display` property, it does not function as intended for list elements?

To toggle the visibility of elements, I have created a unique function that accepts an object and a boolean. Depending on the boolean value, either 'none' or 'initial' is assigned to the 'display' property of the specified obj ...