A div element with the class name "draggable" is

One of my functions sends notifications to a page by prepending a main div with the notification. Here is the function:

function displayNotification(notificationTitle, notificationContent, notificationColor, notificationSize) {
    console.log('Attempting to execute notification');

    var notificationArea = $('#notification_area');
    var notificationHtml;

    notificationHtml += '<div class="container">';
    notificationHtml += '<div class="col-md-' + notificationSize + ' col-centered">'; // column
    notificationHtml += '<div class="draggable panel panel-pink">';
    notificationHtml += '<div class="panel-heading" style="background-color: ' + notificationColor + '">';
    notificationHtml += notificationTitle;
    notificationHtml += '</div>';
    notificationHtml += '<div class="panel-body">';
    notificationHtml += notificationContent;
    notificationHtml += '</div>';
    notificationHtml += '</div>';
    notificationHtml += '</div>'; // end column
    notificationHtml += '</div>';

    $("#notification_area").prepend(notificationHtml);
    $('.draggable').draggable();
}

The issue I am facing is that although I declare the draggable class, it only works for the first notification created. Is there a way to make all divs with that class draggable?

HTML Structure:

<div id="notification_area">
    <!-- Notifications will automatically be added here. -->
</div>

Modified full code:

var ws = new WebSocket('ws://localhost:8181/');

var isConnected = false;

function initializeWebSockets() {
    ws.onmessage = function (messageEvent) {
        receiveMessage(messageEvent.data);
    };

    ws.onopen = function () {
        onConnectionOpen();
    };

    ws.onclose = function () {
        onConnectionClose();
    }
}

function receiveMessage(messageData) {
    var messageParts = messageData.includes('\\') ? messageData.split('\\') : messageData;

    if (messageData.includes("\\")) {
        if (messageParts[0] == "compose:show_custom_notification") {
            displayBootstrapNotification(messageParts[1], messageParts[2], messageParts[3], messageParts[4]);   
        }
    }   
    else {
        if (messageData == "compose:authentication_complete") {
            console.log('Authentication to WebSocket server has been completed.');
        }

        if (messageData == "compose:authentication_failed") {
            sendMessage("client_identity_token " + habboSso);
        }
    }
}

function onConnectionOpen() {
    console.log('Connected to the WebSocket server.');
    isConnected = true;

    sendMessage("client_identity_token " + habboSso);
}

function onConnectionClose() {
    if (!isConnected) {
        console.log('Failed to connect to the WebSocket server.');
    } 
    else {
        console.log('The connection to the WebSocket server was unexpectedly closed.');
    }
}

function sendMessage(message) {
    if (isConnected) {
        ws.send(message);
    }
}

initializeWebSockets();

function displayBootstrapNotification(notificationTitle, notificationContent, notificationColor, notificationSize) {
    console.log('Attempting to execute notification');

    var notificationArea = $('#notification_area');
    var notificationHtml;

    const randomId = '' + new Date().getTime() + '_' + Math.random();

    notificationHtml += '<div class="col-md-' + notificationSize + ' col-centered">';
    notificationHtml += '<div id="' + randomId  + '" class="draggable panel panel-pink">';
    notificationHtml += '<div class="panel-heading" style="background-color: ' + notificationColor + '">';
    notificationHtml += notificationTitle;
    notificationHtml += '</div>';
    notificationHtml += '<div class="panel-body">';
    notificationHtml += notificationContent;
    notificationHtml += '</div>';
    notificationHtml += '</div>';
    notificationHtml += '</div>';

    $("#notification_area").prepend(notificationHtml);

    setTimeout(function() {
        const element = $('#'+randomId);
        element.removeAttr('id');
        element.draggable();
    }, 0);
}

Answer №1

There are a few key issues to address:

  • If the same element(s) are made draggable multiple times, it could be causing problems. Have you attempted selecting only the recently added notification div and attaching it to the other draggables? (Refer to the example)

  • var notificationHtml; <-- This variable seems to be a string that requires initialization with an empty string.

  • A reference for the parent container has already been created:

    var notificationArea = $('#notification_area');
    . When appending content, make use of this reference. (Although not a critical error)

To resolve these issues, your showBootstrapNotification function should look like this:

function showBootstrapNotification(notificationTitle, notificationContent, notificationColor, notificationSize) {
    console.log('attempting to execute notification');

    var notificationArea = $('#notification_area');
    var notificationHtml = '';
    notificationHtml += '<div class="col-md-' + notificationSize + ' col-centered">';
    notificationHtml += '<div class="draggable panel panel-pink">';
    notificationHtml += '<div class="panel-heading" style="background-color: ' + notificationColor + '">';
    notificationHtml += notificationTitle;
    notificationHtml += '</div>';
    notificationHtml += '<div class="panel-body">';
    notificationHtml += notificationContent;
    notificationHtml += '</div>';
    notificationHtml += '</div>';
    notificationHtml += '</div>';

    const newNot = $(notificationHtml);
    notificationArea.prepend(newNot);
    newNot.draggable();
}

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

Using jQuery, effortlessly scroll a div to a specific vertical position of your choice

After referring to this previous question: Scrollpane on the bottom, css is hacky, javascript is hard I followed the same scrolling method as explained in the accepted answer. Now there's a new requirement to select a specific item (e.g., through a ...

Utilize NgRepeat to access an unidentified array in AngularJS

In a complex multi-level array, there are objects nested at the deepest level. [ [ [ "FUND", { "totassets":10.9, "totdate":"2015-03-23", "expratiogross":1.35, "exprationet" ...

Reducing the size of CSS classes and IDs

I am searching for a way to automatically compress classes and ids in an .html file. This specific file is generated through a sequence of gulp commands. I attempted to use the Munch command line application, but it had adverse effects on the file by elimi ...

Ways to access a function variable within an AJAX `done` function

This is the JavaScript function I am working with: $('.editable').change(function () { event.preventDefault(); var el_text = this.lastElementChild; var action = this.action; var method = this.method; var data = $(this).serialize(); ...

"Encountered the following error message: "Error [ERR_HTTP_HEADERS_SENT]: Unable to modify headers once they have been sent to the client" while attempting

My attempts to set a cookie when someone inputs the correct key (1234) are resulting in an error message: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client. I'm confused on what steps to take next. I've tried r ...

Regular Expression: do not include comments that are placed inside quotation marks

Using the regular expression /#(.*?)\r?\n|#(.*?)$/g, I was able to parse the following content. However, it also matches the comment within the quotes. How can I prevent this from happening? # # this is a comment # but this is '# not a c ...

A quick guide on automatically checking checkboxes when the user's input in the "wall_amount" field goes over 3

I'm looking to have my program automatically check all checkboxes (specifically "Side 1, Side 2, Side 3 and Side 4") if the input for wall_amount is greater than 3. Is there a way to achieve this? I attempted lines 10-12 in JavaScript without success. ...

Transferring data using Ajax in a contact form PHP file

I recently started learning about AJAX and came across a code snippet online for sending data to a PHP file using AJAX. However, I'm facing an issue where I'm not sure if the data is being submitted or what is happening. The alert box doesn' ...

The issue with WooCommerce's update_checkout function is that it is not properly updating the available shipping methods

My WooCommerce site includes a function that adds a 4€ fee when the cash on delivery payment method is selected: add_action('woocommerce_cart_calculate_fees', 'increase_cod_cost'); function increase_cod_cost() { if(WC()->sessio ...

How can I ensure that TypeORM, Type GraphQL, Apollo Server, and Azure Functions work together seamlessly?

I have an Azure Function written in TypeScript that utilizes various technologies such as TypeORM, Apollo Server, and TypeGraphQL. The function involves creating resolvers for projects and tasks and establishing a database connection. import { createConne ...

sending data from an AngularJS application to an MVC controller in JSON format containing multiple arrays

Currently, I am working on a project that involves using AngularJS and MVC. I am transferring data from an AngularJS controller to my MVC controller using $http.post(). At the moment, I am using a single object or JSON array to retrieve data as follows: pu ...

Using material community icons in conjunction with react-native-vector-icons

I am facing an issue with displaying the store-front icon from the Material Community Icons library in my React Native app. Here is the code snippet causing the problem: import { StatusBar } from "expo-status-bar"; import React from "react&q ...

Display JSON data in a hierarchical tree structure using AngularJS

Looking to display three nodes of a JSON file as a tree using AngularJS. The nodes are data.key, data.parentItem, and data.title. Below is the JavaScript code: var phonecatApp = angular.module('myApp', []) phonecatApp.controller('myContr ...

Page Not Found: React and Express Route Not Found

I encountered an error while attempting to use the sign-up route: POST http://localhost:3001/sign-up 404 (Not Found). I searched for similar issues on StackOverflow but couldn't pinpoint the source of my problem... In the frontend, I am fetching the ...

Curved divs display outlines on more compact dimensions

Check out this relevant Codesandbox There seems to be a recurring issue in my application where rounded divs display edges when they are of smaller sizes. Refer to the image below for a visual representation. What could be causing this problem and how can ...

Can you use AJAX to retrieve the same URL in both HTTP and HTTPS protocols?

Is it possible to configure AJAX requests to retrieve files based on the protocol being used in the browser? I am aware that AJAX requests cannot be made from HTTP to HTTPS, so we are currently working on making content available through both protocols. F ...

The zoom level on Google Maps adjusts based on the size of the window when it

In reference to my previous inquiry about Google maps responsive resize, I am now looking to incorporate dynamic zoom levels based on the window size. Specifically, I want the map to automatically adjust its zoom level when the browser window is resized -- ...

Ways to avoid overflow of dynamically added div element?

Currently, I am facing an issue while dynamically appending div elements with the .magnet class to my page. These elements end up overflowing the container boundaries and I am struggling to find a solution for this problem. If anyone could check out my j ...

Utilizing Express-Partials in conjunction with a single layout to incorporate multiple partials

Recently, as I migrated to Node.js and ExpressJS 3.0, I noticed that partials were no longer supported. However, I stumbled upon express-partials which provided a similar feature. Upon exploring the example on their GitHub page, I came across this snippet ...

Display the variable on the document by clicking the button

Hello, I'm new here so please forgive me if I make any mistakes. I am working with the following PHP code: <?php $quoteFile = "quotes.txt"; //Store quotes in this file $fp = fopen($quoteFile, "r"); //Open file for reading $content = fread ...