element properties in jQuery - javascript

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! :)

Related

Write HTML in reference to attribute data with Javascript

I would like to add a class to an adjacent element using the attribute of an anchor tag with javascript:
HTML:
<ul>
<li><span></span>Black</li>
<li><span></span>Red</li>
<li><span></span>Blue</li>
<li><span></span>Green</li>
<li><span></span>Yellow</li>
</ul>
JS:
$(document).ready(function(){
var swatchColor = $(".swatchButton").data('color');
$(".swatchButton").find('span').addClass(swatchColor);
});
I'm eventually looking for:
<li><span class="blk"></span>Black</li>
Do I need to create some kind of array with forEach()?
Thanks!
http://jsfiddle.net/cL1rpk9L/
use each() in jquery
$(document).ready(function(){
$(".swatchButton").each(function() {
var swatchColor = $(this).data('color');
$(this).find('span').addClass(swatchColor);
});
});
Demo: https://jsfiddle.net/tamilcselvan/cL1rpk9L/3/
Your code var swatchColor = $(".swatchButton").data('color'); will return the data-color of the first element with class swatchButton and $(".swatchButton").find('span').addClass(swatchColor); will assign that value to each span element which is a descendant of an element with class swatchButton.
You need to set the color for each span individually
$('.swatchButton span').addClass(function(){
return this.parentNode.dataset.color;
});
Demo: Fiddle
or
$('.swatchButton span').addClass(function(){
return $(this).parent().data('color');
});
Demo: Fiddle

How to change style of div #id that contain selected .class

I'm trying to change style of div #info_frame that contain class nazwa_klasy_display and I can't fix it.
$('.box').mouseenter(function() {
//show up scores
$( this ).children( '.scores' ).css( 'display', 'block' );
nazwa_klasy = $( this ).attr('class').split(' ')[1];
nazwa_klasy_display = nazwa_klasy.split('_')[1];
if ($('#info_frame').has(nazwa_klasy_display))
{
$('#info_frame .'+nazwa_klasy_display).style.display ="block";
}
});
you're mixing jQuery with plain Js:
either you use
/* chain a jQuery method, e.g. show() */
$('#info_frame.'+nazwa_klasy_display).show()
or
/* access to the dom node before using plain js */
$('#info_frame.'+nazwa_klasy_display).get(0).style.display = "block";
If my understanding is correct, you are looking for a <div> that has the id of info_frame and the class of nazwa_klasy_display then you do need to fix your CSS selector. you have a space in there when it shouldn't be.
$('#info_frame.'+nazwa_klasy_display)
the selector #info_frame .[nazwa_klasy_display] will be looking for anything that has the class nazwa_klasy_display that is a descendant of *#info_frame
$("#info_frame").hasClass('.'+nazwa_klasy_display).css('display','block');
try this

How do I remove an .append() then add an .append()

This is to show a check for a diagnostic page. I have an .append(not_ok) but when the swf file is 100% loaded I want to remove the not_ok append then add an .append(ok).
function callbackfunk(e){
$(".FlashNotLoaded").css("color", "red").append(not_ok);
var timer = setInterval(function(){
if(e.ref.PercentLoaded() === 100){
$(".FlashLoaded").remove();
$(".FlashLoaded").css("color", "green").append(ok);
}
}, 1000);
}
swfobject.embedSWF("/static/diag/countdown.swf", "flashDiv", "550", "400", "8.0.0", "expressInstall.swf", flashvars, params, attributes, callbackfunk);
The .append(not_ok) will be removed but the .append(ok) will not replace it. I've tried
.replaceWith(ok) but that doesn't seem to work either.
Generally with jQuery, you do that by leaving both on the page in the same spot. jQuery(notOkSelector).hide(); and jQuery(okSelecter).show();.
Hide makes the object display:none, and show reverses this.
EDIT: As long as the objects are already in the DOM (by default with display:none;)...
To show notLoaded:
$(".FlashLoaded").hide(); // it doesn't hurt to hide an already hidden object.
var notLoaded = $(".FlashNotLoaded");
notLoaded.css( 'color', 'red' );
notLoaded.show();
To hide notLoaded and show ok:
$(".FlashNotLoaded").hide();
var flashLoaded = $(".FlashLoaded");
flashLoaded.show();
flashLoaded.css( 'color', 'green' );
EDIT including your above code: Your coude may look like the following...
function callbackfunk(e){
$(".FlashLoaded").hide();
$(".FlashNotLoaded").css("color", "red").show();
var timer = setInterval(function(){
if(e.ref.PercentLoaded() === 100){
$(".FlashNotLoaded").hide();
$(".FlashLoaded").css("color", "green").show();
clearInterval(timer);
}
}, 1000);
}
this line
$(".FlashLoaded").remove();
removes the element(s) from the DOM, so the following line can't append anything to the DOM
$(".FlashLoaded").css("color", "green").append(ok);
I suppose you wanted to remove ok instead.
Are you appending new HTML tags? If so you can use jQuery replaceWiht() , it replace an existing element with a new element.

jQuery Adding DOM Elements

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
});

mootools inject function

I have span which i crate like this:
new Element('span', {'class': 'file-img', 'html': 'Image'})
I want to inject image to it:
var my_img = new Element ('img' , {'src' :'uploading/abc.jpg' ,
'style' : 'width:50px; text-align:left' }).inject(file-img, 'top') ;
It's not working.
Thanks for your help.
this would work (mt 1.2+):
new Element('span', {
'class': 'file-img'
}).inject($(document.body)).adopt(new Element("img", {
'src' :'uploading/abc.jpg',
styles: {
width: 50,
textAlign: "left"
}
});
but if you are trying to use file-img as a reference to the CSS class of the span you have created, then you need to use document.getElement("span.file-img") as your target container. and - don't use - in the class names, if you can help it. use _ instead, - implies subtraction and may have an effect on CSS selectors.
another way to do this is to assign it to a variable
for example,
var file_img = new Element("span" ... );
...
someObj.inject(file_img);
What is file-img ??? it looks like a variable but actually it tries to subtract img from file ... looks like the error is there. Variables can't have dashes in their name in javascript

Categories

Resources