Make the background image draggable while maintaining its size with background-size:cover

I'm working on a fixed div with an image as the background, set up like this:

<div style='
     width:230px;
     height:230px;
     background-repeat: no-repeat;
     background-image:url(img/myimage.jpeg)
     background-size: cover;'></div>

The issue I'm facing is that the image overlaps the div-box. What I want to do is allow the user to drag the image and then be able to access the new background-position: coordinates via jQuery when they release the mouse. Essentially, I want to create a simple image effect similar to what you see on Facebook:

https://i.sstatic.net/faQ84.gif

Is there a way to achieve this? And would it still work if the background overflowed due to using background-size:cover?

Answer №1

If you're looking to add draggable backgrounds to your website, check out this handy Plugin and give it a try:

element.backgroundDraggable()

For a live demonstration, head over to this demo page.

Answer №2

To achieve the desired effect, you must handle the mousemove event on the specific div and calculate the new positioning of the background element based on the mouse movement.

Here is a helpful example to kickstart your project: http://codepen.io/dghez/pen/ItxKE

In order to determine if the left mouse button is being pressed during the mousemove action (simulating a drag), verify that e.buttons === 1. You can refer to this documentation for further assistance: MDN

Update:

The mousemove function in the above example has been modified to allow for dragging of the background image, albeit with some text selection issues:

...
$(".title").mousemove(function(e) {
    if(e.buttons === 1) {
        mouseX = e.offsetX;
        mouseY = e.offsetY;
        traX = mouseX + 1640;
        traY = mouseY + 200;
        //console.log(traX, traY);
        $(".title").css({"background-position": traX + "px " + traY + "px"});
    }
});

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

PHP code exhibiting inconsistent behavior when executed on a WAMP Server

My WAMP Server is set up and running smoothly as I dive into PHP code for a class assignment. The server icon shines bright green, my HTML and PHP files in the www folder are functioning perfectly. I am currently using PHP v7.0.1 on my WAMP setup. However ...

Incorporating Ajax comments into an Ajax-powered status feature

I'm currently in the final phase of implementing ajax in my feed. Originally, I thought it would be a simple matter of pasting the comment input, but it turned out to be more complex than I anticipated. I placed the input below the main ajaxed status ...

IE randomly aborts Ajax requests

I'm encountering an intermittent issue with my Ajax call specifically in IE9. Let me share the code snippet that I am using: $.ajax({ url: buildUrl('ActiveTasksTable/' + $('#Id').val()), type: "POST", cache: false, ...

CSS confusion: What's causing the header to not align horizontally and the footer to not justify evenly spaced?

I am new to coding and experimenting with CSS flexbox to design a responsive layout. I am struggling with aligning the header elements horizontally in the widest viewport and adjusting the footer to space out evenly. For the header, I attempted using disp ...

Add motion to the div element when hovering and moving the mouse away

Looking to add animation to a list moving from left to right and vice versa. Now, I want the list to animate from left to right when the mouse hovers over the div, and then animate from right to left when the mouse leaves the div. Can someone assist me wit ...

Harness the Power of JSON in your JavaScript Applications

I have come across many examples on Stack Overflow discussing how to parse JSON into a JavaScript object or convert JSON to a JS object. However, I haven't found an example that demonstrates binding JSON to an already defined JS object. I am currently ...

Tips for enhancing the flexibility of the owl carousel

I've been trying to make four items fit on a medium screen and two on a mobile device, but no matter what I do - adjusting widths, heights, columns, and responsive classes like col-6, col-md-3, col-lg-3 - nothing seems to work well. I could really use ...

Font reference in IE and Chrome causing HTTPS to fail

Take a look at in both Internet Explorer and Chrome. The header tags (h1 through h6) all have font specifications that rely on a javascript fonts.com specification. However, there seems to be an issue with rendering properly. Interestingly, the fonts ar ...

The canvas is being expanded by utilizing the drawImage method

Ensuring the correct size of a <canvas> element is crucial to prevent stretching, which can be achieved by setting the width and height attributes. Without any CSS applied other than background-color, I am faced with an unusual issue. Using ctx.draw ...

Continuous refreshing of window during Ajax and PHP form submission

Appreciation to those who took the time to read this post! I have a contact form on my website and I am facing an issue where the window keeps refreshing after submission, despite using Ajax with a POST method. Below is the HTML code: <form class="fo ...

Trapping an anchor tag event in asp.net

I am currently working on a menu bar using HTML code (I am unable to use asp link buttons). <ul> <li><a href="#"><span>Reconciliation</span></a> <ul> ...

Multiple Ajax Requests at the Same Time?

I am looking to optimize the execution of a specific PHP script on my server by making multiple calls concurrently. Each call takes approximately 0.5 seconds and is independent of one another. Currently, my implementation looks like this: $(document).read ...

Displaying elements upon checkbox selection in React

Hello, I'm new to React and I am facing an issue with checkbox click handling in React. My goal is to display a div when a checkbox is checked and hide the div when the checkbox is unchecked. The current implementation only shows the div when the che ...

Overriding Styles Set by an External CSS file

Let's assume that I have two different style sheets set up on my webpage: site.css: .modal { position: absolute; width: 200px; ... } ... reset.css: .reset * { position: static; width: auto; ... } Unfortunately, I don ...

Looking for assistance with text alignment?

23 Years Young From: The Boogie Down Bronx Heritage: Puerto Rican Pride Trade: Master Tailor For a demonstration, click on this link ...

unexpected result from ajax call

After successfully establishing the ajax call, I encountered an issue when trying to retrieve a response from the PHP file. In my .php file, I have <?php echo 'hello'; ?>. However, when I alert the parameter in the success function, it disp ...

Ways to utilize CSS for capturing user-inputted text in a text field

I have a question about incorporating user input text into CSS styling. Specifically, I am looking to create a color background option (#ffffff) where the designer can input their own color and have it displayed once saved in the body background style. Wh ...

Simultaneously sending jQuery.ajax data while submitting a form

I'm facing a bit of a dilemma here. I have a form with multiple fields, including one for entering links. When you input a link and click the add button, the link is added to a link_array using jQuery. My goal is to send this array through the jQuery. ...

Validate if the Jquery AJAX response contains any data

I've been attempting to integrate an alert message in my code that triggers if the response is null, but every time I try to do so, something goes wrong. If anyone has any suggestions or assistance with this issue, it would be greatly appreciated. He ...

Comparison between Standard Form Submission and Ajax Form Submission: Leveraging Browser's Auto Save and User Input Suggestions

Many of us who use forms with ajax have likely encountered the issue where the user input is not saved or suggested by the browser in future sessions. This can be problematic, especially on 'sign in' pages where the browser typically offers to sa ...