Draggable element in jQuery can only be dragged once

I am attempting to create a draggable div using JavaScript, but I am running into an issue where the div is only draggable once. I would like it to remain draggable at all times.

I believe the problem lies in the fact that the draggable attribute is within the function add_annotation. I'm not sure how else to approach this. Here is my code:

        <div id="controle_panel">
            <button id="add_annotation" class="btn btn-default" onclick="add_annotation()">
                <span class="glyphicon glyphicon-plus"></span> New annotation
            </button>
        </div>
        <div class="video_commands">
            <div id="video-wrapper" class="video-wrapper">
                <video id="advertisment_video" margin-top="100px" class="video-js 
                       vjs-default-skin" preload="auto" data-setup="{}" controls />
                <source src=<?php echo '"' . $video["video_link"] . '"'; ?> type="video/mp4"></source>
            </div>
            <div id="annotation_confirmation" style="display: none;">
                <button id="confirm_annotation" class="btn btn-default" onclick="">
                    <span class="glyphicon glyphicon-ok"></span> Confirm time and position
                </button>
            </div>
        </div>
    </div>
</body>

<script>
    function add_annotation() {
        var v = document.getElementsByTagName('video')[0];
        if (v.paused) {
            alert("Please start the video to place an annotation at the current time");
        } else {
            v.pause();
            var retVal = prompt("Enter the text of your anotation", "new anotation");
            if (retVal != "new annotation") {
                var e = $('<div style="background: rgba(255,255,255,0.5); width: 25%;">' + retVal + '</div>');
                $('.video-wrapper').prepend(e);    
                e.attr('id', 'annotation'); 
                e.draggable({
                    containment: '#video-wrapper',
                    cursor: 'move',
                    snap: '#video-wrapper'
                });
                document.getElementById('annotation_confirmation').style.display = "inline";
            }
        }
    };
</script>

Answer №1

If you're looking for a way to make the draggable container more efficient, I suggest incorporating it directly within the document and updating it as necessary instead of creating a new one.

<div id="dragContainer" style="background: rgba(255,255,255,0.5); width: 25%; display:none"></div>

Then in your javascript code, you can set it to be draggable upon loading

$(function() {
    $("#dragContainer").draggable({
                containment: '#video-wrapper',
                cursor: 'move',
                snap: '#video-wrapper'
             });
});

You can also adjust your function as follows:

function add_annotation(){
    var v = document.getElementsByTagName('video')[0];
    if (v.paused){
        alert("Please start the video to place an annotation at the current time");
    }else{
        v.pause();
        var retVal = prompt("Enter the text of your annotation", "new annotation");
        if (retVal !== "new annotation"){

            $('#dragContainer').html(retVal).show();

            document.getElementById('annotation_confirmation').style.display ="inline";         
        }
    }
};

Simply triggering a hide event when needed will allow you to remove the draggable container effortlessly.

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

What could be causing my javascript (jquery) code to malfunction on my website?

Hey there, I'm currently working on my first website design project and I'm experimenting with something new: 1) As the page loads, it displays an image as the background. 2) When a user scrolls down past the image, the menu bar should become f ...

I am trying to figure out the best way to position the navbar directly under the jumbotron in Bootstrap 4

Obtaining information is possible with Bootstrap 3, yet I am struggling to understand how to implement it with Bootstrap 4. ...

leveraging embedded jetty for developing a web-based interface

As a newcomer to web development and using embedded Jetty, I have created the source code below in Eclipse IDE. I need to programmatically start the Jetty server and cannot use the command line to do so. The web interface must be lightweight due to the li ...

Implementing Node.js Modules Technology

Is it possible to implement a module called 'test' in nodejs that exposes two functions, getter and setter, for accessing and setting its member data? The challenge is ensuring that data set via the setter function from another module, such as & ...

Is there a way to link my search state to the URL and synchronize it with the next.js router?

I have been exploring the react instant search example found at const generateURL = state => `?${qs.stringify(state)}`; const convertSearchStateToUrl = searchState => searchState ? generateURL(searchState) : ''; const urlToSearchState ...

Why is the decision made to simply remove an item? Is there an option to instead choose and delete the specific item?

I am facing an issue with my form where I have a function to dynamically add inputs using "append" and another button to remove the inputs added. When I use the "last-child" selector to delete the last generated div, the remove button stops working and I a ...

Convert an array of strings to my custom array type in Angular

I have a list of different statuses Here is an example of it: export enum InvoiceStatus { Created = 1, Pending = 2, Approved = 3, Rejected = 4, Paid = 5, Deleted = 6, PreparingPayment = 7 } My goal is to convert it into an ar ...

Guidelines for calculating the CRC of binary data using JQuery, javascript, and HTML5

Can you please assist me with the following issue? Issue: I am currently reading file content using the HTML5 FileReaderAPI's ReadAsArrayBuffer function. After storing this buffer in a variable, I now need to compute the CRC (Cyclic Redundancy Check) ...

Using a background image in a flexbox container with CSS

I'm struggling to add a background image to text. I have a feeling that the issue might be related to nesting too many classes within the "div" tag, but I can't seem to solve it. CSS: .box { display: flex; top: 80px; position: relative; ...

What is the best way to modify a stylesheet attribute in React Native from outside the component?

This is a code example I created: import React from 'react'; import { StyleSheet, Text, View, TouchableOpacity } from 'react-native'; export default function App() { const changeBorderColor = () => { styles.button.borderColor ...

Exploring the latest MUI Styles in Scoping Version 5

We are currently in the process of transitioning our legacy application to React and MUI. To ensure that there is no styling conflict between the old and new parts of the application, we have implemented scoped styles by combining an id selector with a des ...

Struggling to make jquery-masonry function properly

Coding Challenge <div id="container"> <div class="item"> <p>Lorem ipsum dolor sit amet tail frankfurter brisket, meatloaf beef ribs doner pork prosciutto ball tip rump tenderloin tongue. Pastrami fatback beef, sausage beef ribs venison ...

JS Not activating when clicked

I'm attempting to activate the function call_ajax_add_to_quotelist by using a button with the code below: $cartlink .= '<a class="add_to_cart button alt" href="javascript:void(0);" onclick="call_ajax_add_to_quotelist(add_to_quotelist_ajax_url ...

OnePageCheckout may result in empty boxes being displayed due to OneStepCheckout CSS styling

Seeking advice for an issue with the Magento OneStepCheckout module. Upon checkout, there are three columns: customer data (working fine), payment options (selectable via checkbox), and details about the chosen payment method. Unfortunately, the informati ...

Automatically populate the form with data from a MongoDB database in Express, based on the user's previous selection

I am currently in the process of developing an online hospital appointment booking website using express and mongodb. I need to dynamically display available time slots from the database based on the user-selected date without any redirection. I attempted ...

HTML Buttons Remain Selected After Being Clicked

Currently working on a calculator app for a class project but I've hit a roadblock while setting up keyboard listeners. The keyboard functionality is fine, however, when it comes to clicking on buttons, specifically the non-keyboard functions, they re ...

Error message "Module 'ngFacebook' not found! Please check ngFacebook service" occurred when attempting to use ngFacebook service

Greetings, I am currently working on integrating Facebook with my Angular JS web application. To achieve this, I have employed the ngFacebook service in Angular JS. However, upon running my application, I encountered an error: "Uncaught Error: [$injector: ...

Is it feasible to execute code after all AJAX calls have finished within a for loop?

I am faced with a challenge involving a for loop statement that executes an ajax call in each iteration. $.each(arr, function(i, v) { var url = '/xml.php?id=' + v; $.ajax({ url: url, type: 'GET', dataTyp ...

"Is it possible to make a JSON API call in Node.js before exiting with a SIGINT

In my attempt to configure certain variables and make an API call using the request module before exiting the program, I encountered issues where the function was not being properly executed due to the presence of both SIGINT and exit signals: const reque ...

Close the tooltip automatically after a set period

Looking to create an effect where a tooltip appears when hovering over an element and then disappears after a few seconds, even if the mouse is still on the element. Here is my current code: <div data-sentence-tooltip="yes" data-tooltip-content: "some ...