jQuery Adding DOM Elements - javascript

This may be a simple answer, but I'm trying to add a dom-created element (i.e. document.createElement(...)) to a jQuery Selector.
jQuery has a great assortment of functions for adding html
.html(htmlString)
.append(htmlString)
.prepend(htmlString)
But what i want to do is add a dom OBJECT
var myFancyDiv = document.createElement("div");
myFancyDiv.setAttribute("id", "FancyDiv");
// This is the theoretical function im looking for.
$("#SomeOtherDiv").htmlDom(myFancyDiv);

Try this:
$("#SomeOtherDiv").append($(myFancyDiv));
Wrapping the DOM element in $(...), I'd expect you could add it with any of the jQuery DOM manipulation functions that take a jQuery element collection.

This should do it !
$("#SomeOtherDiv").append('<div id="FancyDiv"></div>'));

You could make things simpler and faster by cutting out jQuery entirely for something this simple:
document.getElementById("SomeOtherDiv").appendChild(fancyDiv);

This will work in jQuery 1.4
$("<div/>",{
id: 'FancyDiv'
}).appendTo("#SomeOtherDiv");
http://api.jquery.com/jQuery/#jQuery2

You can try this way:
$("<div/>", {
// PROPERTIES HERE
text: "Click me",
id: "example",
"class": "myDiv", // ('class' is still better in quotes)
css: {
color: "red",
fontSize: "3em",
cursor: "pointer"
},
on: {
mouseenter: function() {
console.log("PLEASE... "+ $(this).text());
},
click: function() {
console.log("Hy! My ID is: "+ this.id);
}
},
append: "<i>!!</i>",
appendTo: "body" // Finally, append to any selector
});

Related

How to use createElement() in JavaScript?

var htmlComponent = [
{
element : 'button',
text : "Addition"
},
{
element : 'h1',
text : "This is the heading"
},
{
element : 'p',
text : "This is the paragraph."
}
];
htmlComponent.forEach(function(item) {
// Problem here
document.body.appendChild(document.createElement(item.element).appendChild(document.createTextNode(item.text)));
}
Actually I wanted to create an html element using DOM Object but this is not working. I mean my code is not working properly..
but when I changed something Like that:
htmlComponent.forEach(function(item) {
var _element = document.createElement(item.element);
var text = document.createTextNode(item.text);
_element.appendChild(text);
document.body.appendChild(_element);
}
Then the code is working.
Here the main question is why 2nd code is working and the 1st one is not working...... what is the problem in my code.
please Explain me........
You are chaining the calls together like body.createElement().appendChild() where you shouldn't.
This works with createElement() because it returns the element you want to append to, but it doesn't work with appendChild() because that returns the child you just appended, which you are then appending again to the body.
This programming style is known as a "fluent" interface. It is supported by some libraries e.g. jQuery, but not by native Javascript DOM functions.
See https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild
Try as follows
appendChild does not return parent
var htmlComponent = [{
element: 'button',
text: "Addition"
},
{
element: 'h1',
text: "This is the heading"
},
{
element: 'p',
text: "This is the paragraph."
}
];
htmlComponent.forEach(function(element) {
var btn = document.createElement(element.element);
var t = document.createTextNode(element.text);
btn.appendChild(t);
document.body.appendChild(btn);
});
According to the documentation for appendChild:
The returned value is the appended child except when the given child
is a DocumentFragment, in which case the empty DocumentFragment is
returned.
You are appending a text node to the button, then trying to append the returned result to the body. This is the reason why you are not seeing the button being appended to the body.
If you break it down like this, it's easier to see what's going on:
document.body.appendChild(
// createElement returns button
document.createElement("button")
// button.appendChild then returns the appended child (a text node)
.appendChild(document.createTextNode("text"))
)

element properties in jQuery

i'm new to jQuery. so in javascript you can create a div and give it it's own properties like this :
var msgbubble = document.createElement('div');
msgbubble.marginTop="10px";
msgbubble.style.backgroundColor="#ccc";
is there is anyways i can create an element like this in jquery and how to append it.
Thanks.
Check this code snippet to create div element with some css properties and set other attributes using jQuery.
$(document).ready(function() {
let elem = $("div"); // create div element and reference it with `elem` variable
// Set css properties to created element
elem.css(
{
'background-color': 'red', 'marginTop': '50px',
'height': '200px', 'width': '200px'
}
);
// Set attribute to created element
elem.prop(
{
'id':'div1', 'class': 'myClass'
}
);
$('body').append(elem);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
For more info on jQuery visit https://www.w3schools.com/jquery
Hope, this small code snippet works for you.. :) :)
A small example of creating a div, setting properties, and appending it:
var msgBubble = $('<div></div>');
// set css properties
msgBubble.css({
'margin-top': '10px',
'background': '#ccc'
});
// or set html attributes
msgBubble.attr({
'data-foo': 'bar'
});
// add some text so it actually has a height
msgBubble.text('message bubble');
$('span').append(msgBubble);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span></span>
With jQuery(html) you can pass html text, which will then create an element.
var element = jQuery('<div></div>');
And if passed a second argument for attributes, jQuery(html, attributes), it will use those and set them on the element.
var element = jQuery('<div></div>',{
css:{
marginTop:'10px',
backgroundColor:'#ccc'
}
});
To append you can use the various methods like append(), appendTo().
element.appendTo(document.body);
So if you wanted to create your element, set the styles, and append the element in one go you would combine all of these like so:
jQuery('<div></div>',{
css:{
marginTop:'10px',
backgroundColor:'#ccc'
},
text:"Some text to go into the element"
}).appendTo(document.body);
jQuery simply uses the .append() method, though it also has .appendTo(), which functions the same way, although the two are syntactically different.
$("span").append("Appended text");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span></span>
Ass for the actual stylisation, that can be done directly through the .css() property:
el.css('margin-top', '10px');
el.css('background-color', '#ccc');
Hope this helps! :)

Make a dynamically generated div droppable

I am working on a Table with div inside the cell, and I want that div to be droppable.
And when I drop something in a div it generate a new div under the first one.
But the dynamically generated div must be droppable to and now it's not...
Here is the creation of a div:
// in a loop with i
divCreate = $("<div>", { id: "divCreate" + i, class: "droppable" });
$(divCreate).css("text-align", "center");
$(divCreate).css("width", "125px");
$(divCreate).css("height", "30px");
$(Cell).append($(divCreate));
JS droppable :
$(".droppable").droppable( function() {
// a lots of line with several function
})
So I try to add that $(divCreate).droppable(); to the creation of the div. Now the div is droppable but not with the JS function that I affect to the class ".droppable".
Do I need to make $(divCreate).live("droppable"); ? Or is it impossible and I need to put all the code from the JS function to the div creation? I really want to avoid that if it is possible.
Move the droppable code into a named function:
function my_droppable() {
// a lots of line with several function
}
And change your general binding to:
$(".droppable").droppable(my_droppable);
Then you can do:
divCreate.droppable(my_droppable);
after appending new elements dynamically.
Try to use:
$(divCreate).appendTo($(Cell)).droppable();
Here is the sample I have created.
$( "<div/>", {
"class": "test",
id:"myDiv",
text: "Drag me!",
width:"125",
height:"30",
'text-align':"center"
}).appendTo( "#droppable" );
$("#myDiv").css("text-align", "center");
$("#droppable" ).draggable();

jQuery animate a value of one elem of a class

I have problems to animate a value of a certain element when selecting it with the class, instead it will animate all elements of that class.
$('.class').parent().hover(
function() {
$({ value: $(this).val() }).animate( .... );
...
}, function() {
$({ value: $(this).val() }).animate( .... );
...
});
Unfortunately due to a plugin i use for creating a slider i have to use the .parent() selector, so i can not use ..
$('.parent') -> $('.class', this)
.. what i think it would solve it.
I have three elements with the ".class"-class and they are all three animated whenever i hover one of them.
further explanation:
The html is only one thing:
<input type="text" value="0" class="class" />
The Plugin creates a canvas above the input and the input is used as the value for the animated bar. It also creates a div wrapping around this two elements. Like so :
<div>
<canvas>
<input ... >
</div>
I'm sure i can find a easy solution by using id's and writing it multiple times in the code with the id's as selector, but i hope for a more elegant way to solve this.
Here the JSFiddle
As long as you know that the <canvas> tag will always be created, why not just use the <canvas> tag as the selector to provide context?
$('canvas').hover(
function() {
var that = $(this);
$({ value: $(this).next() }).animate(
...
progress: function() {
that.next().val(Math.round(this.value)).trigger('change');
}
);
}, function() {
var that = $(this);
$({ value: $(this).next().val() }).animate(
...
progress: function() {
that.next().val(Math.round(this.value)).trigger('change');
}
);
});
NEW Working Fiddle
Maybe try wrapping it in an event listener instead:
$(function(){
$('.class').on('hover',function(){
$({value:$(this).parent().val()}).animate( ...)
})
});

Where to place JQuery (set :visibility via CSS) in a BackBone View

I think this question ultimately boils down to where I should place the JQuery code, and I am unsure for backbone.js.
I have a nested div :
<div>Parent
<div class='pull-right remove-measure-btn'>Child</div>
</div>
and I want the child to only show when the parent is being hovered.
So I can use this code (top lines within the func() in the render() of the parent Backbone.View.extend:
render: function():
....
$(this.el).hover(
function() {
$('.remove-measure-btn').show();
// $('.remove-measure-btn').css('visibility' : 'visible');
},
function() {
$('.remove-measure-btn').hide();
// $('.remove-measure-btn').css('visibility' : 'hidden');
}
);
....
return this;
},
But this only toggles the display, and since I am using Bootstrap and taking advantage of .pull-right, I need to toggle CSS' :visibility, and not display: to keep the height of the child div in place when it is not visible. So if I use the second line from within the above code block, I get an undefined error, since the compiled template has been returned yet (i think....).
So where do I place the JQuery to change the CSS visibilty, or how do I change the rendering to accomodate the code where it is?
Notes:
There are many of these "parent" and "child" divs.
I am assuming it is best to use the selector with this.el to tie the interaction directly as opposed to using several global document.ready()s, but maybe I am not aware of a "safe/good" way to accomplish it using this method
As chcrist notes, the "Backbone" way of doing this is to use the events hash:
var MyView = Backbone.View.extend({
events: {
'mouseenter': 'showChild',
'mouseleave': 'hideChild'
},
render: function () {
//...
},
showChild: function () {
$('.remove-measure-btn').css({'visibility' : 'visible'});
},
hideChild: function () {
$('.remove-measure-btn').css({'visibility' : 'hidden'});
}
});
Also, I'm assuming this is a typo, but this code is wrong:
$('.remove-measure-btn').css('visibility' : 'hidden');
You can either pass an object (one or more style properties):
$('.remove-measure-btn').css({'visibility' : 'hidden'});
Or pass one property/value pair:
$('.remove-measure-btn').css('visibility', 'hidden');
This can be done with straight CSS. Javascript (backbone or otherwise) is not required.
Adding the following CSS to your page will get you exactly what you need without the use of javascript:
.remove-measure-btn {
visibility:hidden;
}
div:hover > .remove-measure-btn {
visibility:visible;
}
A fiddle showing this in action is here: http://jsfiddle.net/35TXY/
try $('remove-measure-button').addClass('hidden') and removeClass('hidden'). Define hidden:
.hidden {visibility: hidden;}

Categories

Resources