jQuery - remove() not working - javascript

I have a script that places divs according the position of mouse on the body of a page. I have a button which says "Clear" and I want to use it to clear the divs created. How can I achieve that?
The script and source I have written:
HTML
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<script src="bhaiya.js"></script>
<button style="z-index: 2000;" class="clear" onclick="clear()">Clear</button>
</body>
</html>
jQuery
$(document).ready(function(){
$(this).mousedown(function(e){
$x = e.pageX;
$y = e.pageY;
$div = "<div class='theDiv' style='width: 250px; height: 150px; background-color:#e7e7e7; position: absolute; top:" + $y + "px; left:" + $x + "px;'>Hey</div>";
$("body").prepend($div);
});
function clear() {
$(".theDiv").remove();
}
})
jsFiddle:
http://jsfiddle.net/BpAYz/
Any help would be appreciated :)

Inline html attribute event handlers can only call global functions. Your clear() function is not global because it is defined inside your document ready handler, so your onclick="clear()" can't find it. You need to either move the function outside the ready handler (making it global), or, better, bind the click with jQuery:
$(document).ready(function(){
$(this).mousedown(function(e){
var $x = e.pageX;
var $y = e.pageY;
var $div = "<div class='theDiv' style='width: 250px; height: 150px; background-color:#e7e7e7; position: absolute; top:" + $y + "px; left:" + $x + "px;'>Hey</div>";
$("body").prepend($div);
});
$(".clear").click(function () {
$(".theDiv").remove();
});
});
Note also that I've added var in front of the variables in your mousedown handler: without var they become global variables, which just makes your code more error prone and hard to debug. (Unless you have a good reason why they should be globals?)

The function clear should be in global scope. Otherwise give an id button1 to the button and add the function as the click event listener using jQuery.
http://jsfiddle.net/BpAYz/2/
Code:
JS
$(document).ready(function () {
$(this).mousedown(function (e) {
if (!$(e.target).is("#button1")) {
$x = e.pageX;
$y = e.pageY;
$div = "<div class='theDiv' style='width: 250px; height: 150px; background-color:#e7e7e7; position: absolute; top:" + $y + "px; left:" + $x + "px;'>Hey</div>";
$("body").prepend($div);
}
});
$(".clear").click(function () {
$(".theDiv").remove();
});
})
HTML
<body>
<button id="button1" style="z-index: 2000;" class="clear">Clear</button>
</body>
I have just modified your code. Please use var keyword when declaring variables in a function.

Do it like this: http://jsfiddle.net/Qn9yL/1/
You should attach to the click even of the button rather than using onclick.
$(document).ready(function(){
$(this).mousedown(function(e){
$x = e.pageX;
$y = e.pageY;
$div = "<div class='theDiv' style='width: 250px; height: 150px; background-color:#e7e7e7; position: absolute; top:" + $y + "px; left:" + $x + "px;'>Hey</div>";
$("body").prepend($div);
});
$('#clear').click(function(e){
e.preventDefault();
$(".theDiv").remove();
});
})
You also want to do the e.preventDefault(); to stop the event then bubbling up and creating a new div etc.

You need to do this:-
Clear
$(document).ready(function(){
$(this).mousedown(function(e){
$x = e.pageX;
$y = e.pageY;
$div = "<div class='theDiv' style='width: 250px; height: 150px; background-color:#e7e7e7; position: absolute; top:" + $y + "px; left:" + $x + "px;'>Hey</div>";
$("body").prepend($div);
});
$(document).on("click", "button.clear", function(e){
e.stopPropagation();
$(".theDiv").remove();
})
})

This works with successive elements:
<style media="all">
.theDiv {
display:none;
}
</style>

Related

jQuery Draggable - Create draggable and start dragging on html5 native Drag And Drop api event

Okay, basically what I want to try to achieve, is when a dragover event fires from HTML5 Drag And Drop API, I wish to create a jQuery draggable object, and start following the mouse around, while the dragend event fires from the HTML5 Drag And Drop API.
The reason I want to do this, is the following:
I have an application which uses a plugin, that has a functionality, which is dependent on the jQuery.ui draggable to function (it is the FullCalendar Scheduler plugin, version 3)
I want to achieve a new functionality in the application, with which the client can drag something from browser window A, and drop it in the above mentioned plugin in browser window B.
As the above mentioned plugin is not working with the native HTML5 Drag and Drop API, and the jQuery.ui draggable is not capable of dragging elements from one browser window to the other, I think my only option is to mix these two plugins.
My proposed solution to this problem was, using the native HTML5 Drag and Drop API, and when the dragged element reaches over a dropzone, creating a new draggable element in browser window B, and simulating a mousedown event on it, so it starts following the cursor. When the dragend event would fire, I planned to plain and simply fire the mouseup event on the draggable element also, and from here on the scheduler plugin can do it's magic.
To try to test this out, with a single browser window at first, I've tried to achieve the first part of my above solution, ie: when the dragover fires, create the jQuery.ui draggable and simulate a mousedown on it, then it should start following the mouse. I can't achieve this behaviour.
I made a fiddle, where you can see what I tried so far (I am not posting the whole code here, as it is rather long): JSFiddle
Basically, the error I am getting at the Fiddle, with both options that I tried, is a type.indexOf is not a function error.
I also asked and received some help on the following question, from where the proposed solution works fine when starting the drag operation with a click event, but it isn't working with any other event type. I pressume, I can simulate a mousedown.draggable event, only from a MouseEvent, and the dragend event is not a MouseEvent.
Long story short, I would need help in obtaining the result I am looking for, at least for the first part of my proposed solution!
There does not appear to be a good answer for this. First, not all browsers support the same DnD terminology or functionality. Such as FireFox fires a dragenter event on drop and Chrome does not seem to detect a drop event when the object is from another window.
Here is my testing so far. To use, copy the content into a Text file and save as HTM or HTML. Then Open the file locally in your browser. Open another Window and open the second HTM. now you have two windows you can drag to and from.
wina-1.htm
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Window A</title>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<style>
.items {
position: relative;
}
.items > div {
margin-right: 5px;
width: 150px;
height: 150px;
padding: 0.5em;
border-radius: 6px;
display: inline-block;
}
#log {
width: 100%;
height: 5em;
overflow-y: auto;
}
[draggable].idle {
background-color: rgba(255,0,0,0.75);
}
[draggable].selected {
background-color: rgba(255,0,0,0.95);
}
</style>
</head>
<body>
<pre id="log"></pre>
<div class="items ui-widget">
<div id="draggable" class="ui-widget-content idle" draggable="true">
<p>Drag me around</p>
</div>
<div id="static" class="ui-widget-content">
<p>I can't be moved</p>
</div>
</div>
<script>
var srcEl;
function log(s){
var now = new Date();
var t = now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds()
+ "." + now.getMilliseconds();
var l = document.getElementById("log");
l.append(t + ": " + s + "\r\n");
l.scrollTop = l.scrollHeight;
}
function dragStart(e){
log("Drag Start: " + e.target.nodeName + "#" + e.target.id);
srcEl = e.target;
if(e.dataTransfer == undefined){} else {
e.dataTransfer.effectAllowed = "copyMove";
log("Event dataTransfer.effectAllowed: " +
e.dataTransfer.effectAllowed);
log("Source Element: " + srcEl.nodeName + "#" + srcEl.id);
}
this.classList.add("selected");
}
function dragOver(e){
e.preventDefault();
log("Drag Over: " + e.target.nodeName + (e.target.id != "" ? "#" +
e.target.id : ""));
return false;
}
function dragLeave(e){
log("Drag Leave: " + e.target.nodeName + (e.target.id != "" ? "#" +
e.target.id : ""));
}
function dragStop(e){
log("Drag End: " + e.target.nodeName + "#" + e.target.id);
this.classList.remove("selected");
}
log("Init");
var item = document.getElementById("draggable");
item.addEventListener('dragstart', dragStart, false);
item.addEventListener('dragover', dragOver, false);
item.addEventListener('dragleave', dragLeave, false);
window.addEventListener('dragleave', dragLeave, false);
var items = document.querySelectorAll('.items > div');
[].forEach.call(items, function(el) {
el.addEventListener('dragover', dragOver, false);
});
</script>
</body>
</html>
As you can see, this is using raw JavaScript. I was tinkering with jQuery UI, and I kept the stylesheet just for easy theming. We have a section to print out log details, a draggable, and a static item.
winb-1.htm
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Window B</title>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<style>
.drag-item {
width: 100px;
height: 100px;
background-color: red;
}
body {
position: relative;
}
div.drag-helper {
width: 100px;
height: 100px;
background-color: red;
z-index: 1002;
position: relative;
}
#log {
width: 100%;
height: 5em;
line-height: 1em;
font-size: 1em;
overflow-y: auto;
}
#dropzone {
background-color: green;
width: 95%;
height: 340px;
}
</style>
</head>
<body>
<pre id="log"></pre>
<div id="dropzone"></div>
<script>
jQuery(function($) {
function log(s){
var now = new Date();
var t = now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds
() + "." + now.getMilliseconds();
$("#log").append(t + ": " + s + "\r\n").scrollTop($("#log").prop
("scrollHeight"));
}
function dragEnter(e){
e.preventDefault();
log("Drag Enter triggered: " + $(e.target).prop("nodeName") +
($(e.target).attr("id").length ? "#" + $(e.target).attr("id") : ""));
}
function dragOver(e){
log("Drag Over triggered: " + $(e.target).prop("nodeName") +
($(e.target).attr("id").length ? "#" + $(e.target).attr("id") : ""));
e.dataTransfer.dropEffect = 'move';
e.preventDefault();
}
function handleDrop(e){
if (e.stopPropagation) {
e.stopPropagation();
}
log("Drop Triggered: " + $(e.target).attr("id"));
return false;
}
function dragEnd(e){
log("Drag End Triggered: " + $(e.target).prop("nodeName") +
($(e.target).attr("id").length ? "#" + $(e.target).attr("id") : ""));
}
log("Init");
$("#dropzone").on({
dragenter: dragEnter,
dragover: dragOver,
drop: handleDrop,
mouseup: handleDrop,
dragend: dragEnd
});
$(window).on({
dragenter: dragEnter,
dragover: dragOver,
drop: handleDrop,
dragend: dragEnd
});
});
</script>
</body>
</html>
Window B uses jQuery as the intention was to convert the element into a jQuery UI Draggable.
First thing to know, there is no way to do in transit. Since the Source element is not a part of the target DOM, it cannot be done. It can be added and initialized as a Draggable in the drop event. Essentially what will happen is a new element will be created at that time assigned all the data.
Second, data transfer is unreliable and I would avoid DataTransfer as your data container. I would advise using localStorage. This is similar to a cookie and is a lot more reliable.
For example, I created the following Data object:
{
id,
type,
attr: {
id,
class,
width,
height
},
content
}
Here are some example functions:
function collectData(obj){
return {
id: obj.attr("id"),
type: obj.prop("nodeName"),
attr: {
id: obj.attr("id"),
class: obj.attr("class"),
width: obj.width(),
height: obj.height()
},
content: obj.text().trim()
};
}
function saveData(k, d){
localStorage.setItem(k, JSON.stringify(d));
}
function getData(k){
return JSON.parse(localStorage.getItem(k));
}
function makeEl(d, pObj){
return $("<" + d.type +">", d.attr).html("<p>" + d.content + "</p>").appendTo(pObj);
}
$("#draggable").on('dragstart', function(e){
saveData("drag-data", collectData($(this)));
});
$("#dropzone").on('drop', function(e){
var item = makeEl(getData('drag-data'), $(this));
item.addClass("clone").position({
my: "center",
of: e
}).draggable();
});
In theory, this should all work. In practice, I have hit a ton of roadblocks. I would suggest something like a click-to-copy type of action. Where the User clicks an item in Window A (selecting it) and then clicks where they want it to be in Window B. Again using localStorage, the item could be cloned into the new location.
wina-3.htm
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Draggable - Default functionality</title>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<style>
.items {
position: relative;
}
.items > div {
margin-right: 5px;
width: 150px;
height: 150px;
padding: 0.5em;
border-radius: 6px;
display: inline-block;
}
#log {
width: 100%;
height: 5em;
overflow-y: auto;
}
[draggable].idle {
background-color: rgba(255,0,0,0.5);
}
[draggable].selected {
background-color: rgba(255,0,0,0.95);
}
</style>
</head>
<body>
<pre id="log"></pre>
<div class="items ui-widget">
<div id="draggable" class="ui-widget-content idle" draggable="true">
<p>Click on me</p>
</div>
<div id="static" class="ui-widget-content">
<p>I can't be moved</p>
</div>
</div>
<script>
var intv;
function log(s){
var now = new Date();
var t = now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds() + "." + now.getMilliseconds();
var l = document.getElementById("log");
l.append(t + ": " + s + "\r\n");
l.scrollTop = l.scrollHeight;
}
function collectData(el){
return {
id: el.id,
type: el.nodeName,
attr: {
id: el.id,
class: el.className,
width: el.width,
height: el.height
},
content: el.innerText
};
}
function saveData(k, v){
localStorage.setItem(k, JSON.stringify(v));
}
function getData(k){
return JSON.parse(localStorage.getItem(k));
}
function clearData(k){
localStorage.setItem(k, null);
}
function selElem(e){
var trg = e.target.nodeName + (e.target.id != "" ? "#" + e.target.id : "");
if(e.target.classList.contains("selected")){
log("Deselect element: " + trg);
e.target.classList.remove("selected");
} else {
log("Element Selected: " + trg);
e.target.classList.add("selected");
saveData("select-data", collectData(e.target));
}
intv = setInterval(function(){
if(getData("select-data") == null){
document.getElementsByClassName("selected")[0].classList.remove("selected");
log("Unselected");
clearInterval(intv);
}
}, 1000);
}
log("Init");
var item = document.getElementById("draggable");
item.addEventListener('click', selElem);
</script>
</body>
</html>
winb-3.htm
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Window B</title>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<style>
.drag-item {
width: 100px;
height: 100px;
background-color: red;
}
body {
position: relative;
}
#log {
width: 100%;
height: 5em;
line-height: 1em;
font-size: 1em;
overflow-y: auto;
}
#dropzone {
background-color: green;
width: 95%;
height: 340px;
position: relative;
}
.cloned {
position: absolute;
width: 150px;
height: 150px;
padding: 0.5em;
border-radius: 6px;
display: inline-block;
background-color: rgba(255,0,0,0.75);
}
</style>
</head>
<body>
<pre id="log"></pre>
<div id="dropzone"></div>
<script>
jQuery(function($) {
function log(s){
var now = new Date();
var t = now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds
() + "." + now.getMilliseconds();
$("#log").append(t + ": " + s + "\r\n").scrollTop($("#log").prop
("scrollHeight"));
}
function getData(k){
console.log("Getting Data: '" + k + "'", localStorage.getItem(k));
return JSON.parse(localStorage.getItem(k));
}
function clearData(k){
log("Clear Data");
localStorage.setItem(k, null);
}
function makeEl(dObj, pObj){
console.log(dObj, pObj);
return $("<" + dObj.type + ">", dObj.attr).html("<p>" + dObj.content +
"</p>").appendTo(pObj);
}
function handleDrop(e){
if (e.stopPropagation) {
e.stopPropagation();
}
var trg = $(e.target);
log("Drop Triggered: " + trg.prop("nodeName") + "#" + trg.attr("id"));
var d, item;
if(e.target.id == "dropzone" && (e.type == "click" || e.type ==
"mouseup")){
log("Click Detected - Collecting Data");
d = getData("select-data");
console.log("Data", d);
d.attr.id = "clone-" + ($("#dropzone .cloned").length + 1);
log("Making Element: " + d.type + "#" + d.attr.id);
item = makeEl(d, trg);
item.removeClass("selected").addClass("cloned").position({
my: "center",
of: e
}).draggable();
clearData("select-data");
return true;
}
return false;
}
log("Init");
$("#dropzone").on({
mouseup: handleDrop,
click: handleDrop
});
});
</script>
</body>
</html>
I know this is not the answer you're looking for, and for that you need to try to ask the real question. You seem to keep asking around the question.
Hope this helps.

Add text to specific DIV

How to append text to a specific <div> if i know the ID of the <div>?
For example, here's my code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function appendDIV(idDIV, txt) {
$("#" + idDIV).append('<p>' + txt + '</p>');
}
appendDIV("content-01", "some text");
</script>
<div id="content-01" style="float: left; width: 150px; height: 150px; border: 2px solid red;"></div>
Function accepts the ID of the <div> and some text, but nothing happens.
What's going wrong?
code for getting each p in side div you should do like this
Working
// Shorthand for $( document ).ready()
$(function() {
appendDIV("content-01", "some text");
//get all p element and go through each
$('#content-01 > p').each(function( index ) {
console.log( index + ": " + $( this ).text() );
console.log( "id of element" + $(this).attr('id'));
});
});
function appendDIV(idDIV, txt) {
$("#" + idDIV).append('<p>' + txt + '</p>');
}
Working Demo
you should allows to load DOM first before doing any manipulation , so for that you should write you code in document.ready method provided in jquery, which get called when DOM is ready
// Shorthand for $( document ).ready()
$(function() {
appendDIV("content-01", "some text");
});
add code as above. that will do . Read here : $( document ).ready()
You might also consider a custom trigger, passing values, for example if you want a click event on the DIV, then insert some stuff:
$('body').on('appenddiv', function(event, idDIV, txt) {
$("#" + idDIV).append('<p>' + txt + '</p>');
});
// some where later in code:
$(".mydiv-group").on('click', function() {
let myid = $(this).attr('id');
let mytext = myid + ": some text";
$('body').trigger('appenddiv', [myid, mytext]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mydiv-group" id="content-01" style="float: left; width: 150px; height: 150px; border: 2px solid red;"></div>
<div class="mydiv-group" id="content-02" style="float: left; width: 150px; height: 150px; border: 2px solid red;"></div>

How can one append a div exactly in the position where the mouse is over? jQuery

I want to leave a colored div trail without generating divs when the page loads. I want them to be appended when the mouse is over the parent div and position them where the mouse is within it.
EDIT: I think I need to be more precise so I posted the code that I want to rewrite. I want it to do the same thing without generating the divs that become colored on mouseover when the page loads but to create a colored div when the mouse is over $(".container") at the current position of the mouse.
THANKS!
Mention: the script generates lots of divs - it might take a while for the page to load.
$(document).ready( function() {
var csize = $(".container").width() * $(".container").height();
var space = $(window).width() * $(window).height();
while ( csize * $(".container").length < space) {
$("#space").append("<div class='container'></div>");
};
$(document).on("mousemove", function() {
window.color = Math.floor(Math.random()*16777215).toString(16);
});
$(".container").on("mouseover", function() {
$(this).css("background-color", "#" + window.color);
});
});
#space{
width: auto;
height: auto;
}
.container {
width: 15px;
height: 15px;
display: inline-block;
float: left;
border: none;
}
<!DOCTYPE html>
<html>
<head>
<title> JqPractice</title>
<link rel="stylesheet" type="text/css" href="reset.css">
<link rel="stylesheet" type="text/css" href="style.css">
<script src="jq.js" type="text/javascript"></script>
<script src="sv2.js" type="text/javascript"></script>
</head>
<body>
<div id="space">
<div class="container">
</div>
</div>
</body>
<footer>
</footer>
</html>
$("#parent").on({
mousemove: function (e) {
var wrapper = $(this);
var parentOffset = wrapper.offset();
var relX = e.pageX - parentOffset.left + wrapper.scrollLeft();
var relY = e.pageY - parentOffset.top + wrapper.scrollTop();
wrapper.find('.randomTrail:visible').remove();
wrapper.append($('<div class="randomTrail"/>').css({
left: relX,
top: relY
}));
},
mouseleave: function () {
$('.randomTrail:visible').remove();
}
});
DEMO
Ref:
.offset()
.scrollLeft()
.scrollTop()
.remove()
e.pageX and e.pageY
.on()
mousemove
mouseleave
Events
find()
You will need to use mousemoves() to get the event data and coordinate like below
$( "#target" ).mousemove(function( event ) {
var msg = "Handler for .mousemove() called at ";
msg += event.pageX + ", " + event.pageY;
console.log(msg);
});
and you will need a div with css {position:absolute; width:10px; height:10px; background-color:yellow; left: event.pageX; top:event.pageY} something like this will do
For more info checkout official doc from jQuery

Button stays in the last div when a div is removed

I'm trying to fix my jQuery code. I want 'add content' button in the last div only. If a div is removed, the button stays in the last div. Suggestions please.
var i = 1;
var deletedDivs = 0;
var createdDivs = 0;
$(document).ready(function () {
$(document).on('click', '.addcontent', function () {
if (i == 1) $(".question").html('');
$(".hide_button").remove();
$(".question").append('<div class="new-question" id="question' + i + '" name="question' + i + '"><div class="deleteButton" id="question' + i + '">Remove</div><b>Question ' + i + '</b><br> This is div text <br> <button class="addcontent hide_button' + i + '">Add content</button></div>').show('slow');
createdDivs++;
i++;
});
$(document).on('click', '.deleteButton', function () {
var id = $(this).attr("id");
$("#" + id).remove();
deletedDivs++;
if (createdDivs == deletedDivs) {
i = 1;
$(".question").append('<button class="addcontent hide_button">Add content</button>').show('slow');
}
});
});
HTML:
<div class="question">
<button class="addcontent hide_button">Add content</button>
</div>
Try this:
Move your button out of your div:
HTML:
<div class="question">
</div>
<button class="addcontent hide_button">Add content</button>
JS:
var i = 1;
var deletedDivs = 0;
var createdDivs = 0;
$(document).ready(function () {
$(document).on('click', '.addcontent', function () {
if (i == 1) $(".question").html('');
$(".question").append('<div class="new-question" id="question' + i + '" name="question' + i + '"><div class="deleteButton" id="question' + i + '">Remove</div><b>Question ' + i + '</b><br> This is div text <br></div>').show('slow');
createdDivs++;
i++;
});
$(document).on('click', '.deleteButton', function () {
var id = $(this).attr("id");
$("#" + id).remove();
deletedDivs++;
if (createdDivs == deletedDivs) {
i = 1;
}
});
});
JSFIDDLE: http://jsfiddle.net/ghorg12110/a7L3cn1a/1/
Here is the updated/working code.
HTML:
<div>
<div class="question"></div>
<button class="addcontent">Add content</button>
</div>
JavaScript:
var i = 1;
var deletedDivs = 0;
var createdDivs = 0;
$(document).ready(function () {
$(document).on('click', '.addcontent', function () {
if (i == 1) {
$(".question").html('');
}
$(".question").append('<div class="new-question" id="question' + i + '" name="question' + i + '"><div class="deleteButton" id="question'+i+'">Remove</div><b>Question ' + i + '</b><br> This is div text <br></div>').show('slow');
createdDivs++;
i++;
});
$(document).on('click', '.deleteButton', function () {
var id = $(this).attr("id");
$("#" + id).remove();
deletedDivs++;
if (createdDivs == deletedDivs) {
i = 1;
}
});
});
A little hard to see what you have in mind, but I would have the button in all the divs and use CSS to show or hide the button.
div button { display: none; }
div:last-of-type button { display: inline; }
It's more efficient if you use CSS to overlap that property at the end and you will conserve the same element with the necessity of adding and removing it
html:
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.9.1.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div id="content" class="content"></div>
<button class="addcontent hide_button">Add content</button>
</body>
</html>
css:
.new-question {
background-color: green;
width: 300px;
height: auto;
position: relative;
margin:0;
}
.deleteButton {
background-color: red;
width: 50px;
height: 50px;
margin-left: 100%;
position: relative;
}
.addcontent{
z-index: 1;
top:-25px;
left:200px;
position:relative;
}
.content{
min-height:30px;
}
js:
$(function (){
var i = 1,
contentQuestion = $('<div class="new-question"></div>'),
remove = $('<div class="deleteButton">Remove</div>').appendTo(contentQuestion),
content = $('#content');
$('.addcontent').on('click', function () {
content.append(contentQuestion.clone().append('<b>Question ' + i + '</b><br> This is div text'));
i += 1;
});
content.on('click', '.deleteButton', function () {
$(this.parentNode).remove();
});
});
jsbin:
http://jsbin.com/gequveroba/1/edit?html,css,js,output

resizable jquery plugin zoom issue

I'm creating a form wysiwyg builder and I'm having problems with the resizable jquery plugin. It seems that when I resize any item that is on the page the zoom goes out of whack. I have found a workaround for draggable here: Jquery draggable with zoom problem
But I cannot find the same workaround for resizable.
The scenario is when I create a resizable and draggable item and I zoom in or out the item seems to drift outside of its containing parent. You can see this
here:
http://drniermanoptometry.cu.cc/Main/Forms_Module/editForm.php/?name=horizontal-clickersearch.html
Note: click the allocation 'NO' button to create a resizable draggable item. And then zoom out using control++
I have set the containment to parent and the css position to relative to no avail.
There are a few other issues with resizable. When I resize the item it does not let me drag the item all the way to the right and draggable does not work in FF. Possibly related?
Update:
I have found out that there is a problem with margins set to auto so I have the left side of my resizeable container fixed to avoid the issue. But I still would like to know if there is a workaround for auto margins.
This guy has the same issue... http://www.webdeveloper.com/forum/showthread.php?236987-jQuery-resizable-with-margin-0-auto
Code Below:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<link rel="stylesheet" type="text/css" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/themes/base/jquery-ui.css"/>
<script language="javascript" type="text/javascript">
$(document).ready(function(){
$('.create').click(function(){
var jquerybox = $('<div/>' , {class: 'blocked form-item' , width: '100px', height: '20px' , background: 'red'} );
var zoom = $('#form-preview').css('zoom');
var canvasHeight = $('#form-preview').height();
var canvasWidth = $('#form-preview').width();
jquerybox.resizable({
containment: 'parent'
});
jquerybox.draggable({
containment: 'parent',
drag: function(evt,ui)
{
// zoom fix
ui.position.top = Math.round(ui.position.top / zoom);
ui.position.left = Math.round(ui.position.left / zoom);
// don't let draggable to get outside of the canvas
if (ui.position.left < 0)
ui.position.left = 0;
if (ui.position.left + $(this).width() > canvasWidth)
ui.position.left = canvasWidth - $(this).width();
if (ui.position.top < 0)
ui.position.top = 0;
if (ui.position.top + $(this).height() > canvasHeight)
ui.position.top = canvasHeight - $(this).height();
}
});
$('#form-preview').append(jquerybox);
});
});
function updateItem(Item){
//ajax call to update script
}
</script>
<style>
.blocked{
display:block;
background: red;}
#form-preview{
height: 550px;
width: 600px;
border: 2px solid black;
margin-left: auto;
margin-right: auto;
}
.centered{
margin-right: auto;
margin-left: auto;
}
</style>
</head>
<body>
<div id = "editbar">
<form action="Idkyet" method = "POST">
<table>
<tr>
<th>Type</th>
<th>Allocated</th>
</tr>
<?
error_reporting(E_ALL);
ini_set('display_errors', '1');
if(isset($_GET['name'])){
require_once '../../db_connect.php';
$sqlpre = 'SELECT id FROM forms WHERE name = "' . $_GET['name'] . '";';
$res = $mysqli->query($sqlpre);
$rds = $res->fetch_array();
$id = $rds['id'];
$res->free();
$sql = 'SELECT * FROM form_fields WHERE form_id = ' . $id ;
$res = $mysqli->query($sql);
if($res){
while($rds = $res->fetch_assoc()){
echo '<tr>';
echo '<td><input value = " ' . $rds['type'] . ' "type="textarea"></td>';
echo '<td><input class = "create centered" type="button" value = ' . (($rds['allocated'] == 1) ? 'Yes' : 'NO') . '></td>';
echo '</tr>';
}
}
}
?>
</table>
</form>
<div id = "form-preview">
<div class = "blocked"height = "20px"></div>
</div>
</div>
</body>
</html>

Categories