Search code examples
javascriptjquerypositiontypeerrorjsplumb

Error in getting the 'top' position property of dropped Elements


I'm working with a project where I have to drag and drop elements and perform some further actions on these elements. Currently I'm trying to get the position of the elements dropped on the container but am getting the following error in the debugger.

Error

trail.js:262 Uncaught TypeError: Cannot read property 'top' of undefined

Method in Context

function saveFlowchart(){
    var nodes = [];

    //////////////////////////////////////////////////////////////////
    //Code in Context to the question//

    var matches = [];
    var searchEles = document.getElementById("container").children;
    for(var i = 0; i < searchEles.length; i++) 
    {
        matches.push(searchEles[i]);
        alert("elements: "+ searchEles[i].id);
        var idOfEl = searchEles[i].id;

        var $element = $(idOfEl);
        var position = $element.position();
        position.bottom = position.top + $element.height();
        position.right = position.left + $element.width();
        alert("Top position: " + position.top + "\nLeft position: " + position.left + "\nBottom position: " + position.bottom + "\nRight position: " + position.right);
    }    
    /////////////////////////////////////////////////////

    $(".node").each(function (idx, elem) {
        var $elem = $(elem);
        var endpoints = jsPlumb.getEndpoints($elem.attr('id'));
        console.log('endpoints of '+$elem.attr('id'));
        console.log(endpoints);
        nodes.push({
            blockId: $elem.attr('id'),
            nodetype: $elem.attr('data-nodetype'),
            positionX: parseInt($elem.css("left"), 10),
            positionY: parseInt($elem.css("top"), 10)
        });
    });
    var connections = [];
    $.each(jsPlumb.getConnections(), function (idx, connection) {
        connections.push({
            connectionId: connection.id,
            pageSourceId: connection.sourceId,
            pageTargetId: connection.targetId
        });
    });

    var flowChart = {};
    flowChart.nodes = nodes;
    flowChart.connections = connections;
    flowChart.numberOfElements = numberOfElements;

    var flowChartJson = JSON.stringify(flowChart);
    //console.log(flowChartJson);

    $('#jsonOutput').val(flowChartJson);
}

This method saves the connections and outputs it in a json format. But I need the custom made elements to be regenerated as well. That is why I'm trying to get there positions and regenerate them so that I can recreate the flowchart created.

error

Any help in this regard will be appreciated.


Solution

  • The following might help

    Previous line of Code

    var $element = $(idOfEl);
    

    Changed as

     var $element = $("#" + searchEles[i].id);