At the click of a button I want to insert an element BEFORE the currently selected element. I handle “selected” by storing the last clicked element ID in a variable.
My code:
initialise.js
[code=php]
(function()
{
main.page = parent.document;
}
)();
/**
*
* Easier than console.log();
*
*/
function echo(string)
{
console.log(string);
}
item_document_elements.js
[code=php]
// Example of the 2 parameters:
// controls.inserting_this = “canvas”
// select_element.selected = “default_div”
main.page.getElementById(“new_element_go”).addEventListener
(
“click”,
function()
{
controls.insert_before(controls.inserting_this, select_element.selected);
},
false
);
controls.insert_before = function(element, selected)
{
echo(“DEFINITELY INSERTING BEFORE”);
var id = main.page.getElementById(“new_element_id_input”);
var name = main.page.getElementById(“new_element_name_input”);
// Return false if the input field is empty.
if(id.value == “” || id.value == null || id.value == “undefined”)
{
id.style.color = “#F00”;
id.value = “ID required”;
id.focus();
return false;
}
// Check if the element ID is in the array.
// If indexOf returns -1, it doesn’t exist.
if(create.element_array[“name”].indexOf(id.value) != -1)
{
id.style.color = “#F00”;
id.value = “ID already exists”;
id.focus();
return false;
}
else
{
var master_parent = main.page.getElementById(selected).parentNode;
var create_element = main.page.createElement(element);
create_element.id = id.value;
create_element.style.border = “1px solid black”;
create_element.style.width = “auto”;
create_element.style.height = “auto”;
create_element.textContent = “New ” + element;
// Add element to array of elements in the document.
create.element_array[“name”].push(id.value);
create.element_array[“name”][“properties”].push(new element_properties);
master_parent.insertBefore(create_element, selected);
}
// End blackout window and remove popup.
controls.end_darkness();
}
The document contains only the following:
[code=php]
<div id=”container” class=”hovering selected” style=”margin-right: auto; margin-left: auto; height: auto;”>
<div id=”default_div” style=”width: auto; height: 120px; border: 1px solid #999;”></div>
</div>
The above code always inserts the new element AFTER the last one, never before. As far as I’m aware the function is being used correctly. If not, please advise.
What am I doing wrong?