dynamically added div is not draggable - javascript

I'm trying to make my dynamically added divs draggable but if I call after
$("#draggable").draggable({});
this
for( var i = 0; i < 5; i++ ){
var smallone = document.createElement('div');
smallone.id = "draggable";
smallone.className = "smallDiv";
smallone.style.bacgroundColor = 'blue';
document.body.appendChild(smallone);
}
there is no chance to make divs draggable.
I know it works if i create divs first but I need to keep it like this because of my project and this example shows my problem.
Here is fiddle: http://jsfiddle.net/bimbochobot/9jstfwpm/4/
Thank you in advice.

You will have to initialize draggable widget after appending new element.
Try this fiddle:
for( var i = 0; i < 5; i++ )
{
var smallone = document.createElement('div');
smallone.id = "draggable";
smallone.className = "smallDiv";
smallone.style.backgroundColor = 'blue';
document.body.appendChild(smallone);
$(smallone).draggable({});
}

Use a class instead of id as id must be unique
$(".draggable").draggable({});
Assign draggable class to all divs

simple 1 ...
for( var i = 0; i < 5; i++ )
{
var smallone = document.createElement('div');
smallone.id = "draggable";
smallone.className = "smallDiv";
smallone.style.bacgroundColor = 'blue';
document.body.appendChild(smallone);
$(".smallDiv").draggable({});
}
it is working... http://jsfiddle.net/9jstfwpm/7/

Related

How to append multiple element into a parent element? [duplicate]

My question is:
Is that possible to add the same element without rewriting the same variable.
I am creating a slider, and i need to append a div with a class slide-el into block slider.
Here is a part of code
var body, html, sliderBody, btnLeft, btnRight, i, parts, vHeight, vWidth;
//Variable definitions
var i = 0,
parts = 3,
//Main html elements
body = document.body,
html = document.element,
//viewport Height and Width
vHeight = window.innerHeight,
vWidth = window.innerWidth,
sliderBody = _id("slider"),
btnLeft = _id("btn-left"),
btnRight = _id("btn-right"),
urls = ["http://www.wallpapereast.com/static/images/pier_1080.jpg",
"http://www.wallpapereast.com/static/images/pier_1080.jpg",
"http://www.wallpapereast.com/static/images/pier_1080.jpg",
"http://www.wallpapereast.com/static/images/pier_1080.jpg"];
slide = _createEl("div");
slide.className += "slide-el";
function _id(el){
return document.getElementById(""+ el +"");
}
function _createEl(el){
return document.createElement(""+ el +"");
}
window.onload = function(){
slideLayout();
}
function slideLayout(){
for(var i=0; i < urls.length; i++){
sliderBody.appendChild(slide);
}
}
The problem is that I can't append the same element that many times. It just creates one element instead of 4.
For you to understand better I made a fiddle:
https://jsfiddle.net/ud7dvn3z/
appendChild will remove the node from wherever it is before appending it to its new location, so you need to make copies of the node instead. You can use cloneNode for that. The true makes cloneNode perform a deep clone, i.e. with all its child nodes.
for(var i = 0; i < urls.length; i++){
sliderBody.appendChild(slide.cloneNode(true));
}
Okey guys! I found an answer. I have to put
slide = _createEl("div");
slide.className += "slide-el";
into for loop.
Now it looks like this:
for(var i=0; i < urls.length; i++){
slide = _createEl("div");
slide.className += "slide-el";
sliderBody.appendChild(slide);
}

get two Elements by Id in same js function [duplicate]

My question is:
Is that possible to add the same element without rewriting the same variable.
I am creating a slider, and i need to append a div with a class slide-el into block slider.
Here is a part of code
var body, html, sliderBody, btnLeft, btnRight, i, parts, vHeight, vWidth;
//Variable definitions
var i = 0,
parts = 3,
//Main html elements
body = document.body,
html = document.element,
//viewport Height and Width
vHeight = window.innerHeight,
vWidth = window.innerWidth,
sliderBody = _id("slider"),
btnLeft = _id("btn-left"),
btnRight = _id("btn-right"),
urls = ["http://www.wallpapereast.com/static/images/pier_1080.jpg",
"http://www.wallpapereast.com/static/images/pier_1080.jpg",
"http://www.wallpapereast.com/static/images/pier_1080.jpg",
"http://www.wallpapereast.com/static/images/pier_1080.jpg"];
slide = _createEl("div");
slide.className += "slide-el";
function _id(el){
return document.getElementById(""+ el +"");
}
function _createEl(el){
return document.createElement(""+ el +"");
}
window.onload = function(){
slideLayout();
}
function slideLayout(){
for(var i=0; i < urls.length; i++){
sliderBody.appendChild(slide);
}
}
The problem is that I can't append the same element that many times. It just creates one element instead of 4.
For you to understand better I made a fiddle:
https://jsfiddle.net/ud7dvn3z/
appendChild will remove the node from wherever it is before appending it to its new location, so you need to make copies of the node instead. You can use cloneNode for that. The true makes cloneNode perform a deep clone, i.e. with all its child nodes.
for(var i = 0; i < urls.length; i++){
sliderBody.appendChild(slide.cloneNode(true));
}
Okey guys! I found an answer. I have to put
slide = _createEl("div");
slide.className += "slide-el";
into for loop.
Now it looks like this:
for(var i=0; i < urls.length; i++){
slide = _createEl("div");
slide.className += "slide-el";
sliderBody.appendChild(slide);
}

How can I add divs to an array dynamically?

I would like to create several divs with the same options like color, width, height, etc.
I would like to add all of these divs to an array, but I need to do this dynamically.
My current code:
var ArrayInfo = [];
do {
var InfoDiv = document.createElement('div');
InfoDiv.id = 'Info_Div';
InfoDiv.className = 'Info_Div';
InfoDiv.style.width = "100px";
InfoDiv.style.height = "30px";
InfoDiv.style.display = "inline-block";
ArrayInfo.push(InfoDiv);
}while(i < x);
x can be a very very large number.
Is this the right way to add div a to an array?
How can I write text into the elements of an array?
I tried this:
ArrayInfo[i].innerHTML = "something";
But it didn't work.
You never increment i, so your loop will never end.
Second, you never actually add any of the divs to the document -- creating them doesn't do that for you.
And as noted in the comments, you can't use the same id over and over.
var ArrayInfo = [];
var x = 10;
var ctr = document.getElementById('ctr');
for (var i = 0; i < x; ++i) {
var InfoDiv = document.createElement('div');
InfoDiv.id = 'Info_Div' + i;
InfoDiv.className = 'Info_Div';
InfoDiv.style.width = "100px";
InfoDiv.style.height = "30px";
InfoDiv.style.display = "inline-block";
ArrayInfo.push(InfoDiv);
ctr.appendChild(InfoDiv);
}
for (i = 0; i < x; ++i) {
ArrayInfo[i].innerHTML = "div " + i;
}
<div id=ctr></div>
I'd avoid using do...while. I'd also avoid creating a new div on every loop. Instantiate once, then clone (it's faster).
var InfoDiv = document.createElement('div');
InfoDiv.id = 'Info_Div';
InfoDiv.className = 'Info_Div';
InfoDiv.style.width = "100px";
InfoDiv.style.height = "30px";
InfoDiv.style.display = "inline-block";
var ArrayInfo = [];
for(var i = 0; i < x; i++) {
var div = InfoDiv.cloneNode(true);
div.id += i; // Add number to id
ArrayInfo.push(div);
}
IDs must be unique! Considering adding a number to the end of each Info_Div to uniquely identify it.
Also consider using a for loop instead of a do while loop.
The convention for JavaScript variables is lowerCamelCase. So we should fix that as well.
In your code, the divs were added to the array but not to the document. If you wanted to add them to the DOM, you would have to add document.body.appendChild.
Your code would look more like this.
var arrayInfo = [];
var x = 5; // Or whatever value it is
for (var i = 1; i < x; i++) {
var infoDiv = document.createElement('div');
infoDiv.id = 'Info_Div' + i;
infoDiv.className = 'Info_Div';
infoDiv.style.width = "100px";
infoDiv.style.height = "30px";
infoDiv.style.display = "inline-block";
arrayInfo.push(infoDiv);
arrayInfo[i].innerHTML = "div " + i;
document.body.appendChild(infoDiv);
}

I'm trying to make a div width expand once clicking on another div

Im trying to make a div expanded once you click on another div. In my case I'm try to make div with some text in it expand when the image is clicked. A link to my JSFiddle - https://jsfiddle.net/txoyuvqn/3/
My javascript that I am using looks like.
var divs = document.getElementsByClassName('image');
var whattochange = document.getElementsByClassName('text');
for (var i = 0; i < divs.length; i++)
divs[i].addEventListener("click", function () {
for (var i = 0; i < whattochange.length; i++) {
whattochange[i].style.width = '500px'
whattochange[i].style.transition = 'all 1s'
whattochange[i].style.backgroundColor = 'red'
}
}, false);
However when I click on the class called image it effects all the Text classes, i know it's because were changing the css to all of the text divs, however is there a way to make it only effect the correlating div? Or am I going about creating this in the wrong way?
getElementsByClassName returns an array, not a single element.
divs is an array, and you are correctly using a for loop and the index indicator [i] after your variable name divs.
You need a similar for loop for whattochange.
var divs = document.getElementsByClassName('image');
var whattochange = document.getElementsByClassName('text');
for (var i = 0; i < divs.length; i++)
divs[i].addEventListener("click", function () {
for (var i = 0; i < whattochange.length; i++) {
whattochange[i].style.width = '800px';
whattochange[i].style.transition = 'all 1s';
whattochange[i].style.backgroundColor = 'red';
}
}, false);
There may be a better way, but you could do it like this:
var divs = document.getElementsByClassName('image');
var whattochange = document.getElementsByClassName('text');
for (var i = 0; i < divs.length; i++)
{
divs[i].addEventListener("click", function()
{
var w = document.getElementById(this.id.replace('img', 'text'));
w.style.width = '800px'
w.style.transition = 'all 1s'
w.style.backgroundColor = 'red'
});
whattochange[i].id = 'text' + i;
divs[i].id = 'img' + i;
}
See the fiddle
Javascript
var divs = document.getElementsByClassName('image');
var whattochange = document.getElementsByClassName('text');
for (var i = 0; i < divs.length; i++) {
divs[i].addEventListener("click", function () {
for (var i = 0; i < whattochange.length; i++) {
whattochange[i].style.width = '800px';
whattochange[i].style.transition = 'all 1s';
whattochange[i].style.backgroundColor = 'red';
}
}, false);
}
You have to be sure that the elements exist if your JavaScript code depends on them. The reason why your fiddle didnt work was because, you was not loading the script after the body has finished loading.
In your code, One way of achieving this is by putting the <script> tag at the end of the body like this:
<html>
<head></head>
<body>
<script type="text/javascript">
// code here
</script>
</body>
You can also put all your code in a function for the window.onload event or use jQuery.

Javascript - How to get all elements and do same thing on each of them

I want to get all DIVs in DIV(id = room) and do the same javascript code on each one.
I think it should look like this
Get element by id room -> Get all divs inside -> do something on them(change each class to "grass")
or by using a loop.
How to do that?
Please don't use jQuery.
Modern browsers (IE9+):
var divs = document.querySelectorAll('#room div');
[].forEach.call(divs, function(div){
div.className = 'green';
});
var a = document.getElementById("room").getElementsByTagName("div");
for(i = 0; i < a.length; i++)
{
a[i].className = "grass";
}
Do you want to get all divs inside, or just direct children?
This one traverses direct children. If you want to go through all internal nodes, you need to recurse it.
function grassify(nodeId) {
var node = document.getElementById(nodeId);
for(var i in node.childNodes) {
// Do things with node.childNodes[i], for example:
node.childNodes[i].className = 'grass';
}
}
Then just:
grassify('room');
var room=document.getElementByID("#room");
var divs=room.getElementsByTagName("div");
for(var i=0;i<divs.length;i++){
doSomething(divs[i]);
}
Use getElementByID and getElementsByTagName
Use getElementsByTagName
First get a reference to the container element, then use getElementsByTagName for the type of element you want.
See http://jsfiddle.net/aQtTx/
JS:
var targetDiv = document.getElementById("div1");
var nestedDivs = document.getElementsByTagName("div");
for(var divIndex = 0; divIndex < nestedDivs.length; divIndex++)
{
nestedDivs[divIndex].style.backgroundColor = 'red';
}
function myFunction()
{
var a=document.getElementById('room').childNodes;
for (i=0; i<a.length; i++)
{
a[i].className="grass";
};
}
JsFiddle
var parent = document.getElementById("room");
var divs = parent.getElementsByTagName('div');
for (i=0; i<divs.length; i++)
{
divs[i].className="grass";
};

Categories