What is the best way to enable an image to be moved on top of another image?

Is there a way to allow users to drag around an image that is positioned on top of another image in an HTML file? I want the superimposed image to stay within the boundaries of the underlying image. Any suggestions on how this can be achieved?

<html>
<head>
  <style type="text/css">

  #about {
    z-index:1;
    position:absolute;
    top:10%;
    left:3%;
    opacity: 0.6;
  }

  #main-content-image {
    height:100%;
    position:relative;
  }

  </style>


  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
  </script>
  <script type="text/javascript">
  $(document).ready(function(){    

    $(function () {
      var img = new Image();
      $(img).load(function () {
        $('#main-content-image').append(this);
      }).attr('src', 'foo.jpg');
    });

  });
  </script>
</head>
<body>

  <div id="main-content-image">
    <img id="about" src='bar.jpg'>
  </div>

</body>
</html>

Answer №1

To enable dragging functionality, simply utilize the draggable function from jQuery UI library.

$(document).ready(function () {

    $(function () {
        $("#draggable").draggable();
    });

});

For a practical demonstration, refer to this interactive example:

https://jsfiddle.net/rv8kcjqd/

Answer №2

If you want to restrict movement within a specified area, you can utilize the jQueryUI Draggable Widget. This widget enables you to set a containment parameter, preventing the element from being dragged outside of the defined bounding box.

For reference, here is a simple demonstration:

$(function() {
  $("#draggable3").draggable({ containment: "#containment-wrapper", scroll: false });
});
.draggable { width: 90px; height: 90px; padding: 0.5em; float: left; margin: 0 10px 10px 0; }
#containment-wrapper { width: 95%; height:150px; border:2px solid #ccc; padding: 10px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>

<div id="containment-wrapper">
  <div id="draggable3" class="draggable ui-widget-content">
    <p>I'm staying inside the designated area</p>
  </div>
</div>

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

Can the details of a package be retrieved from a Nuget private store using a REST API?

Currently working on an Angular 8 project that involves displaying the details of Nuget packages from a custom store. I am wondering if it is possible to retrieve package details from an NPM custom store using a REST API? Something similar to: https://lea ...

When the browser screen is minimized, the menu bar toggler in my Angular project stops functioning properly. I rely on Bootstrap features within Angular to handle this

When the browser is at full-screen mode, HTML works perfectly. However, when I resize the browser to a smaller size, the navbar disappears and a toggle is shown - which is the expected behavior. If I click on the toggle, the menu list should be displayed ...

Interactive Form directly linked to SQLite3 database

Looking for assistance with converting a modal from static, fake data to dynamic data from an SQLite3 database. The goal is to display a table of existing data and allow users to add new rows by clicking a +New button. However, when trying to incorporate ...

React does not allow objects as children, but what if it's actually an array?

My function is encountering an error message that reads: "Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead." I am struggling to understand why this error is occurring. ...

Having trouble getting the ReactJS AXIOS post function to work properly?

Error in console: [1]: https://i.sstatic.net/xOfUV.png issue with axios request .post("https://bootcamp-2022.devtest.ge/api/application", { token: "7e475dfc-0daa-4108-81c8-d6c62a3df4ca", first_name: JSON.parse(localStorage.ge ...

Error handling: Encountered unexpected issues while parsing templates in Angular 2

I'm a beginner with Angular 2 and I'm attempting to create a simple module, but encountering an error. app.component.html import { Component } from '@angular/core'; import { Timer } from '../app/modules/timer'; @Component({ ...

How can I set up multiselect values in AngularJS ui-select?

Solution: Success! I managed to resolve the issue by implementing this solution and creating a customized build of the ui-select. Hopefully, this fix will be incorporated into the official master branch soon! Issue Is there a way to set up a select elem ...

The AngularJS application appears to have trouble accessing a local text file, even when it is deployed on

Within the same directory of my application deployed on IIS, there are 4 files: home.html Angular.js data.txt web.config (Automatically generated by IIS for default document) I am looking to display the content of 'data.txt' on 'home.html ...

Using Javascript, display an image that was previously hidden with CSS when a radio button is selected

Within a table of 25 rows, each row contains an attribute accompanied by an image (represented by a tick symbol) and five radio buttons for rating the attribute from 1 to 5. Upon clicking one of the radio buttons, the hidden image (tick symbol) should beco ...

Tips for maintaining the original ng-click initialized value as the ng-init value after the page is refreshed

My ng-repeat feature includes buttons for liking and disliking images. The problem I'm facing is that each time the page refreshes, the count of likes and dislikes gets reset to the initial value set by ng-init. How can I maintain the incremented lik ...

Creating a file structure for JavaScript files in a Vue CLI project

When structuring my Vue CLI project, I'm struggling to find clear documentation on best practices. Currently, I have 10 modules each with an associated JS file. My approach so far involves organizing all the pages in my router.js within a views direc ...

Error: A semicolon is required before the statement in an HTML select tag

I am struggling with the code below in my java script: var i = 2; $(".addmore").on('click', function () { count = $('table tr').length; var data = "<tr><td><input type='c ...

Can HtmlCleaner be safely used with multiple threads?

I've been searching for information on their website but can't seem to find an answer. Can you confirm if HtmlCleaner is thread safe? I have multiple threads that will be using it and I'm unsure whether reusing an instance of the HtmlCleane ...

"Learn the steps to efficiently input multiple data entries with the same name from a single form into different rows within the same column of

How can I modify this form to insert four separate data entries in the same column upon submission? <form action="entry.php" method="post" > <table> <tr> <td> <input type="text" name="searchid[]" id="searchid" placeh ...

Using Ajax with Bootstrap's typeahead feature

I've been struggling to implement typeahead on my website, and here's what I've attempted so far. Here is my HTML and code: <html> <head> <title>typeahead</title> <link href="//maxcdn.bootstrapcdn.com/ ...

Refreshing select2 dropdown options dynamically with AJAX updates

I have a select dropdown for locations that is initialized using select2 on page load. I am looking to dynamically update the data in the dropdown at regular intervals using ajax calls. However, when I attempt to update the data in select2, the dropdown ...

Lifting Formik's "dirty" value/state to the parent component: A step-by-step guide

Parent Component const Mother = () => { const [dusty, setDusty] = useState(false) return ( <ChildComponent setDusty={setDusty} /> ) } Child.js ... <Formik initialValues={initialValues} onSubmit={onSubmitHandler} validationSchema={sch ...

ES6 syntax specification allows for the use of a fat arrow function for declaring React components

When learning React, I have noticed two different ways of declaring components. The first is using the classic fat arrow syntax with a return statement. const Component = () => { return ( <div>Hello</div> ) } Recently, I came ...

Personalized configurations from the environment in the config.json file

I need to dynamically populate a setting object in my config.json file based on environment variables. The settings should vary depending on the environment. "somesetting": { "setting1": "%S1%", "setting2": "%S2%" } I am currently working on Wind ...

The content on the page is not visible when viewing on an Android device in

After spending a considerable amount of time browsing StackOverFlow for coding solutions, I have come across a problem that I can't seem to find an answer for. Yesterday, I made some changes to the media queries on my site in order to incorporate a dr ...