Prevent a div from being displaced by the transform property once it reaches the window's border

Is it possible to prevent the viewer I created using CSS transform from moving when its borders reach the window borders? Should I consider using a different method instead?

If you'd like to see the code, you can check it out here.

var x=0, 
    y=0,
    rateX=0,
    rateY=0,
    maxspeed=10;
var container = $('.container');

var w = container.width() / 2;
var h = container.height() / 2;
var center = {
    x: container.offset().left + container.width() / 2,
    y: container.offset().top + container.height() / 2
};

container.on('mousemove', function(e){   
    var offsetX = e.pageX - center.x;
    var offsetY = e.pageY - center.y;

    rateX = -offsetX / w;
    rateY = -offsetY / h;
});

container.hover(
    function(){
        var scroller = $(this).data('scroller');
        if (!scroller) {
            scroller = setInterval( moveContent, 30 );
            $(this).data('scroller', scroller);
        }
    },
    function(){
        var scroller = $(this).data('scroller');
        if (scroller) {
            clearInterval( scroller );
            $(this).data('scroller', null);
        }
    }
);   

function moveContent(){
    x += maxspeed * rateX;
    y += maxspeed * rateY;
    var newpos = 'translate('+x+'px, '+y+'px)',
        transform = '-webkit-transform' || '-moz-transform' || '-ms-transform' ||  '-o-transform'  || 'transform',
        content = $('.content');
    content.css(transform ,newpos);
}

Answer №1

One possible solution is to implement boundaries and apply transformations within those limits when they are exceeded:


function moveContent(){
    x += maxspeed * rateX;
    y += maxspeed * rateY;

    // Apply top and left boundaries
    x = x > 0 ? 0: x;
    y = y > 0 ? 0: y;

    // Define bottom and right boundaries
    var x_bound = -$('.content').width() + $(window).width();
    var y_bound = -$('.content').height() + $(window).height();
    
    // Check if the positions are beyond the boundaries
    x = (x < x_bound) ? x_bound : x;
    y = (y < y_bound) ? y_bound : y;

    var newpos = 'translate('+x+'px, '+y+'px)',
        transform = '-webkit-transform' || '-moz-transform' || '-ms-transform' ||  '-o-transform'  || 'transform',
        content = $('.content');
    
    // Apply transformation to the content
    content.css(transform ,newpos);
}

Here's an updated version of the code on JSFIDDLE

Please note that in the example, I used a static value of 1500 instead of $('.content').width() because the provided width does not represent the actual width of your combined boxes.

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

My webpage lacks responsiveness

I've recently put together an HTML page, but unfortunately, it's not responsive. My Code <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> ...

Deactivating a hyperlink on my print-friendly webpage with JavaScript

My code is designed to generate a printable version of a webpage by duplicating the HTML content and then making certain modifications, such as deactivating buttons upon page load. In addition to disabling buttons, I also aim to deactivate all links on th ...

Vulnerability protection against AngularJS JSON is not removed

I am currently working on an Angular app that communicates with an API. The JSON responses from the API are prefixed with )]}', as recommended in Angular's official documentation. The issue I am facing is that my browser seems to try decoding th ...

Is it possible to update a MobX state when a message is received from Firebase in the background?

I've set up Firebase in my project like this: import { initializeApp } from 'firebase/app'; import { getMessaging, getToken, onMessage, isSupported } from 'firebase/messaging'; import store from './flag'; ...

Choosing a specific category to display in a list format with a load more button for easier navigation

Things were supposed to be straightforward, but unexpected behaviors are popping up all over the place! I have a structured list like this XHTML <ul class = "query-list"> <li class="query"> something </li> <li class="query" ...

What is the best way to add items to arrays with matching titles?

I am currently working on a form that allows for the creation of duplicate sections. After submitting the form, it generates one large object. To better organize the data and make it compatible with my API, I am developing a filter function to group the du ...

Is javascript or ajax the best choice for updating a database in asp.net mvc?

I need help with updating a row in my database based on a change event from a dropdown list. I am not sure whether to use javascript or ajax for this purpose as I want to avoid page refresh. Any recommendations on which method is best and where I can find ...

Error in Angular Google Maps Component: Unable to access the 'nativeElement' property as it is undefined

I am currently working on creating an autofill input for AGM. Everything seems to be going smoothly, but I encountered an error when trying to integrate the component (app-agm-input) into my app.component.html: https://i.stack.imgur.com/mDtSA.png Here is ...

At what point is the JavaScript function expression triggered in this code snippet?

let express = require('express') let app = express(); app.use(express.static('static')); let server = app.listen(3000, function() { let port = server.address().port; console.log("The server has started on port", port); }); I ...

I am unable to retrieve a list using Jquery's ajax function

Can someone please help me diagnose the issue with the code below and why it's not functioning properly? This code snippet is from a webmethod in an aspx.cs page. [webmethod] [ScriptMethod(ResponseFormat=ResponseFormat.Json)] public sta ...

Initiating an action the moment the element comes into view by scrolling

I need to apply specific classes to an element with an id of ig-container. The classes I want to add are: $("#ig-container").addClass("animated bounceInRight"); I aim to animate this element once it becomes visible on the screen, triggered by a user scro ...

Positioning a text directly next to an image that are both hyperlinked to the same webpage located in the center of the image

When viewing my site on a mobile device, I want to have an image with text next to it that both link to the parent menu. However, I'm facing an issue with the text not aligning properly (it should be centered within the picture height but appears at t ...

mandating the selection of checkboxes

Currently, I am exploring the possibility of automatically selecting a checkbox when an option is chosen from a dropdown menu. Below is a code snippet that demonstrates what I am aiming to tweak: $('.stackoverflow').on('change', func ...

How come the hook keeps triggering endlessly in a loop when I try to pass the updated props?

I've encountered an issue with a custom hook I created for making HTTP requests. The problem is that the request seems to be firing in an endless loop, and I'm unsure of what's causing this behavior. My intention is for the request to only t ...

Accurate representation of a JavaScript object using Node.js Express

I have a certain structure that I need to display on my JADE page, so I created a JSON-like object to store the data. This is how the JSON object looks like : var dataSet1 = { meta: { "name": "Some text", "minimum": mini_2, "ma ...

I'm in the process of constructing a create-next-app and I need to retrieve data from a web API. However, I'm unsure of the best place to securely store the API key

I am working on building a create-next-app that will retrieve data from the News Catcher API and display it within my application. I have obtained an API key to access the News Catcher API. However, I am unsure of where to securely store the API key and h ...

Utilize JavaScript to apply the CSS -moz-transition

Creating a web application and using CSS3 to transform a div, but encountering a challenge with Firefox. Able to make Chrome, Opera, and IE work properly, except for Firefox. Here's how I'm setting up the working browsers: obj.style.WebkitTrans ...

Understanding the behavior of the enter key in Angular and Material forms

When creating forms in my MEAN application, I include the following code: <form novalidate [formGroup]="thesisForm" enctype="multipart/form-data" (keydown.enter)="$event.preventDefault()" (keydown.shift.enter)="$ev ...

Is there a way to extract the content length from the raw DraftJS data?

I have a system where I am storing the data from my DraftJS editor in my database as a JSON string by passing it through convertToRaw(editorState.getCurrentContent()). For example, this is how the stored data looks like in the database: {"blocks": [{"key ...

Is it possible for me to load a window following a click

I developed a customized Modal Box that functions similar to the browser's "alert()". When using the traditional alert(), it halts the rendering and executions of the underlying webpage. I am seeking methods to achieve this same behavior: preventing ...