Sliding over absolute positioned elements using CSS relative positioning to create hover effects

I'm in the process of creating a game where I want to prevent users from resizing or scaling the screen without causing issues. The game consists of one large background with dynamic elements overlayed on top. Currently, the elements are not scaling (they are set to scale with the browser window), which is good, but positioning them correctly was quite challenging.

The main objective is to have the div move up by X pixels when a user hovers over an image. However, these relative images are placed within an absolute box for left and top CSS modifications to the window.

I looked into using negative margins as suggested online, but it doesn't seem to work. While the margins do go negative, the div remains in its original position.

You can view the JSFiddle for the issue at: http://jsfiddle.net/uyx09byn/2/

I would like some advice on the proper approach to solving this. Below is my current jQuery code to maintain the aspect ratio:

$(document).ready(function() 
{
    setSizes();
});


$(window).resize(function() 
{
    setSizes();
});

var widthMultiplier;
var heightMultiplier;

var normalWidth = 1920;
var normalHeight = 1080;
var offsets;
function setSizes()
{
    widthMultiplier = ($(window).height()/9*16) / normalWidth;
    heightMultiplier = $(window).height() / normalHeight;

    //Background Image
    $('#stadium').height($(window).height());
    $('#stadium').width($(window).height()/9*16);

    offsets = $('#stadium').offset();

    //playerspace
    $("#players").width(946 * widthMultiplier);
    $("#players").height(130 * heightMultiplier);

    $("#players").css("left", (((1920 * widthMultiplier) * 29.8 / 100) + offsets.left) + "px");
    $("#players").css("top", (((1080 * heightMultiplier) * 77.9 / 100) + offsets.top) + "px");


    //players
    $(".player").width(86 * widthMultiplier);
    $(".player").height(115 * heightMultiplier);
    $(".player").css("margin", (5.5 * heightMultiplier) + "px " + (4 * widthMultiplier) + "px " + (4 * heightMultiplier) + "px " + (4 * widthMultiplier) + "px");

    var lefttemp;
    $(".player").mouseover(function()
    {
        console.log("UP: " + this.id);
        $(this).css({marginTop: '-=15px'});
    });
    $(".player").mouseout(function()
    {
        console.log("DOWN: " + this.id);
        $(this).css({marginTop: '+=15px'});
    });
}   

Answer №1

Here is an updated link to the solution: https://jsfiddle.net/uyx09byn/17/

Your issue can be solved more efficiently using CSS instead of JavaScript.

For instance, the following JavaScript lines:

$('#stadium').height($(window).height());
$('#stadium').width($(window).height()/9*16);

You can achieve the same result with this CSS code:

max-width: 1920px;
width: calc(100vh / 9 * 16);
max-height: 1080px;
height: 100vh;

The value "100vh" represents 100% of the viewport height.

To create a scaling effect similar to what you were trying to do with JavaScript, set a padding-bottom: XX%; on the element based on its width. Adjust the percentage to achieve the desired aspect ratio. For example, if two elements each occupy 50% of their parent, setting padding-bottom to 50% would make them square.

To move an element up by X pixels on hover, use the following CSS:

.player:hover {
    backface-visibility: hidden;
    transform: translateY(-15px);
    transition: all .3s;
}

The transform property shifts the element in the specified direction (in this case, 15 pixels up along the Y axis), the transition makes the movement smoother, and backface-visibility: hidden; triggers hardware acceleration for the transformation and transition effects.

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

Retrieve the ng-model value from one div and pass it to another div

I am trying to retrieve the value of ng-model from one div and use it in another div. HTML: <div class="form-group" ng-repeat="key in condition.keys"> <select class="form-control" ng-show="key.aggregator" ng-model="key.aggregator" ng-options ...

Error: The Vue bind object property cannot be read because it is undefined in the class binding

I'm attempting to associate a class with an object property, but I encounter an issue when trying to trigger the @click event on the list object - the console states that it cannot read the isSelected property of the object. My goal is to activate a c ...

The z-index is not functioning correctly when outside of the container

Using bootstrap, I am attempting to display an element outside of the container. [html] <div class="container"> <div class="element"></div> </div> [css] .element{ position:absolute; right:0; top:0; z-index:999;} Issue: The blo ...

Is it possible to utilize Bootstrap Icons as bullet points on a website?

Is it possible to use Bootstrap icons for bullet points with CSS? I am aware that FontAwesome can be used for this purpose, but I would like to confirm if the same can be achieved using Bootstrap. Though there is a method using: <ul> <li>< ...

Enhancing jQuery Datatables with automatic scrolling functionality for details control

I am currently using jQuery Datatables and I am looking for a way to automatically scroll to display the details-control once it has been activated. Right now, if I click on the last row of my table to open the information, the user might miss out on seein ...

Adding more pixels to the height of an element does not actually make it larger

Recently, I've been working with material UI and I have a scrolling list of items that I want to resize to be larger. However, I've noticed that no matter how I adjust the height in pixels, the items never exceed 140px. Below is the code snippet ...

Why is it not possible to establish a minimum height of 100% in html?

HTML Code: <!DOCTYPE html> <html> <head></head> <body> <link rel="stylesheet" type="text/css" href="style.css"> <div class="sheet" style="width:80%;max-width:1024px;height:400px;"></div> ...

Connect cells within an HTML table by drawing a line between them

While attempting to create a visually appealing floor plan, I have been unable to find any Javascript/jQuery libraries that meet my needs. My input is a text file with 0s and 1s (a sample 10x10 matrix), where the 1s represent walls. After processing the in ...

Styling with CSS Attributes

While conducting research on CSS specifications through W3C, I stumbled upon this document. Although the Wikipedia page claims it is part of level 3. However, I have a couple of questions: The document does not explicitly state that it belongs to level 3 ...

Toggling event triggers with the second invocation

At this moment, there exists a specific module/view definition in the code: define(['jquery', 'underscore', 'backbone', 'text!templates/product.html'], function($, _, Backbone, productTemplate) { var ProductView = ...

Tips for creating a flexible popover widget

I am facing an issue with my project that has a popover (ng-bootstrap) similar to what I need. The problem is that the tooltips and popovers are not flexible when it comes to resizing the page. To address this, I attempted to put a mat-grid (which works pe ...

Error: Angular unable to locate static assets files

Issue: Encountering a 404 Not Found error when trying to access fonts within the assets folder. http://server.com/assets/fonts/Bold/RobotoCondensed-Bold.woff2 However, it works fine in local development: http://localhost/assets/fonts/Bold/RobotoCondensed- ...

The variable that was posted in the JavaScript 'if' statement seemed to vanish in an instant

My website has forms that send data to a PHP file, triggering the appearance of items in a cart: <form method="post"><fieldset> <input type="hidden" name="jcartToken" value="<?php echo $_SESSION['jcartToken'];?>" /> <i ...

The div father's width is not fully occupied by col-xl-12

Can you explain why inew2 and inew3 do not have a width of 100% of their parent div? https://i.sstatic.net/a4GEa.jpg html, body{ width: 100%; height: 100%; margin: 0px; padding: 0px; } .ibrands{ height: 120px; background-color: blue; } @media only scre ...

Error: jQuery Validation not triggering in Bootstrap modal window

My attempts to use jQuery Validation for form validation inside a modal have hit a dead end. The validation doesn't trigger at all, not even an error message is displayed. Upon debugging, a warning emerged: No elements selected for validation; retu ...

extract part of a JavaScript date by utilizing substring

When attempting to populate a text box with a date in the format Wed Sep 14 2016 00:00:00 GMT+0400, I encountered an issue. My goal was to extract the date in the format Sep 14 2016 using the substring method. I implemented the code below, but unfortunate ...

Having difficulties retrieving the <td> id using jQuery

I am a beginner in the world of JavaScript and jQuery, and I am currently attempting to extract both the ID and the value of an element. Here is my initial AJAX request: $.ajax({ type: "POST", url: "Home/AddText", data: JSON.stringify({ te ...

Track WordPress Post Views on Click using AJAX

Is there a way to track the number of post views on my WordPress site using AJAX when a button is clicked? Currently, the view count only updates when the page is refreshed. I want to be able to trigger this function with an AJAX call. Here is the code I ...

Switching up the navbar's background hue

Struggling to change the background color of individual navbar options using id's. Only the text in the navbar changes, not the background color. My goal is to have a unique background color for each navbar option within this bootstrap template I am c ...

Creating Custom Styled Divs Dynamically

I am currently trying to customize the appearance of divs that are displayed on the front page. https://i.sstatic.net/BsEaM.png My platform is WordPress, and my goal is to have each new post align alternately left and right starting with the first post. ...