How to append text to div - javascript

Hi i have written this code to take 3 parameters and assign to variable.now i want to append the text i am getting throughparameter to div fontdiv
how to do this?
here is what i have tried..
function getTextWidth(text, fontname, fontsize) {
var elem = '<div id="fontdiv" style="position: absolute;visibility: visible;height: auto;"></div>';
$('body').append($(elem));
var fontdiv = document.getElementById('fontdiv');
fontdiv.style.fontSize = fontsize;
fontdiv.style.fontFamily = fontname;
$("#fontdiv").html($('text').val());
return fontdiv.clientWidth;
};

If your text param already has text
$("#fontdiv").append(text); // append text into fontdiv

If the value of text is set already (and it seems to be), use :
$("#fontdiv").append(text);
And it should work.

Use
function getTextWidth(text, fontname, fontsize) {
var elem = '<div id="fontdiv" style="position: absolute;visibility: visible;height: auto;"></div>';
var el = $(elem).append(text);
$('body').append(el);
var fontdiv = document.getElementById('fontdiv');
fontdiv.style.fontSize = fontsize;
fontdiv.style.fontFamily = fontname;
$("#fontdiv").html($('text').val());
return fontdiv.clientWidth;
};
Another way could be
function getTextWidth(text, fontname, fontsize) {
var el = $('<div>', {
id: 'fontdiv'
}).css({
position: 'absolute',
visibility: 'visible',
height: 'auto',
fontSize: fontsize,
fontFamily: fontname
}).append(text).appendTo('body');
return el.get(0).clientWidth;
};

Replace
$('body').append($(elem));
with
$('body').append(elem);

Related

Add multiple label dynamically in html page using javascript

I used following code for adding label dynamically.
var array_resp=[CorrectStreet,CorrectCity,CorrectState,CorrectZip];
// var stateName=map.getKey(CorrectState);
if(array_resp.length > 0) {
var answers = [];
for(var i = 0; i <= array_resp.length - 2; i++) {
answers[i] = document.createLabel({
color : '#000',
text : array_resp[i],
top : top,
left : '30 px',
width : '420 px',
height : '100 px',
visible : 'true',
backgroundColor : 'white',
font : FontNormal,
});
document.body.appendChild(answers[i]);
}
}
in html:-
<button onclick="myFunction()">Try it</button>
But it doesn't give correct output,when I am click on button.
Why it happen? Can someone help me please.
Some issues in your code:
There are no function of createLabel for creating LABEL element
To assign the style / properties in wrong way, never in object type
There is no SPACE between 30 and px for left, width & height.
Try this:
<body>
<script>
function myFunction(){
var array_resp=['CorrectStreet','CorrectCity','CorrectState','CorrectZip'];
// var stateName=map.getKey(CorrectState);
if(array_resp.length > 0) {
for(var i = 0; i <= array_resp.length - 2; i++) {
var label = document.createElement('label');
label.style.color = '#000';
label.style.top = 'top';
label.style.left = '30px';
label.style.width = '420px';
label.style.height = '100px';
label.style.visible = 'true';
label.style.backgroundColor = 'white';
label.style.font = 'FontNormal';
label.innerHTML = array_resp[i];
document.body.appendChild(label);
}
}
}
</script>
<button onclick="myFunction()">Try it</button>
</body>

remove previously added canvas text with fabric.js

on change event of text-Area i want to change the text which is already drawn on canvas. following code i have written , using if/else condition i am removing text which was added earlier .remove doesn't works here perfectly . after text change if i drag text somewhere then text is changed to first one which is already removed what would be problem ?
$('#filedset').delegate(' textarea', 'change ', function () {
var canvas = new fabric.Canvas('design_text');
if (x == 0) {
alert('if called');
var message = $(this).val();
console.log('text area change' + message);
var text = new fabric.Text(message, {
left: 150,
top: 60
});
canvas.remove(text1);
canvas.add(text);
x = 1;
} else {
alert('else called');
var message = $(this).val();
console.log('text area change' + message);
var text1 = new fabric.Text(message, {
left: 150,
top: 60
});
canvas.remove(text);
canvas.add(text1);
x = 0;
}
}
Sure. I created small jsfiddle: http://jsfiddle.net/Kienz/BTh6A/
var canvas = new fabric.Canvas('design_text');
$('#filedset').on(' textarea', 'change ', function(e) {
var obj = canvas.getActiveObject() || canvas.item(0),
text = e.target.value;
if (!obj || obj.type !== 'text') return;
obj.setText(text);
canvas.renderAll();
});

Prepend next element to div

I´m trying to prepend a div (.portrait_text) to a container (.gallery_container):
Every image gets prepended to its corresponding .gallery_container. but I want to aslo prepend every next .portrait_text div to it´s .gallery_container. Any ideas?
<div id="gallery_images_inner" class="clearfix">
<img src="img/portrait.jpg" alt="portrait" width="850" height="557">
<div class="portrait_text">Girls After Swim</div>
<img src="img/gallery5.jpg" alt="gallery5" width="850" height="566">
<div class="portrait_text">Girls After Swim</div>
</div>
JS:
function Gallery(selector) {
this.add_module = function (type, image) {
var container = $('<div />', {
'class': 'gallery_container'
}).append(image);
if (type == 'horizontal') {
var h_ar = image.attr('height') / image.attr('width');
var c_width = selector.width();
var c_height = selector.width() * h_ar
container.css({
'width': c_width - 60,
'height': c_height
})
}
if (type == 'vertical') {
var c_width = v_width;
var c_height = v_height
container.css({
'width': Math.floor(v_width) - 30,
'height': v_height
})
}
container.css({
'float': 'left',
'overflow': 'hidden'
})
container.find('img').attr({
'width': '100%',
'height': '100%'
})
container.attr('ar', c_height / c_width)
container.appendTo(selector);
//container.children('img').fitToBox();
}
}
If image is being passed as a jQuery object, as your code seems to suggest, you can use .next() to select the text as well:
function Gallery(selector) {
this.add_module = function (type, image) {
var portrait_text = image.next('.portrait_text');
var container = $('<div />', {
'class': 'gallery_container'
}).append(image).append(portrait_text);
...
}
}
Of course, this is appending and you asked for prepending, but the concept is the same.
jQuery has a next selector, so you can do
$(selector).next(".portrait_text").appendTo(container);

Storing an inline style into jquery variables

I have the following img tag,
<img id="image1" src="URL" alt="image1" name="image1" width="137" height="119" border="0" style="position: relative; left: -355px; top: 62px;" >
I would like to somehow, onclick, store the following items into seperate variables..
style="position: relative; left: -355px; top: 62px;"
var left = -355px
var top = 62px
Is that possible? Thank you!
Of course this is possible, have you tried something like this:
$('#image1').on('click', function () {
var style = 'style="' + $(this).attr('style') + '"';
var left = $(this).css('left');
var top = $(this).css('top');
alert(style);
alert(left);
alert(top);
});
Example: http://jsfiddle.net/9ZXHX/
var imageInfo = {style:null, left:null, top:null};
$('#image1').on('click', function() {
var $this = $(this);
imageInfo.style = $this.attr('style');
imageInfo.left = $this.css('left');
imageInfo.top = $this.css('top');
console.log('Image Clicked: ', imageInfo);
});
You could get the image with jquery, and then access its attributes from there.
var img = $("#image1");
var imgStyle = img[0].getAttribute("style");
var imgLeft = img.css("left");
var imgRight = img.css("right");
link to jquery's api for css: http://api.jquery.com/css/
In a function:
function getDetails(imgId)
{
var imgDetails = {};
var img = $("#"+imgId);
imgDetails.imgStyle = img[0].getAttribute("style");
imgDetails.imgLeft = img.css("left");
imgDetails.imgRight = img.css("right");
return imgDetails;
}
Here is a fiddle showing an example of this working, and the requested output in the question: http://jsfiddle.net/j7eYf/1/
I suggest your use jquery, it will make the job a lot easier. Try out this example,
$("#your trigger").live('click',function ()
{
$("#image1").css({
position: "absolute",
top: 62 + "px",
left: -355 + "px"
});
});

Messy but Working jQuery

I've written the jQuery you'll see below for a little project I'm working on. It works perfectly and is all set, but, as you can see, it's messy and kind of...long winded.
I've tried a bunch of different ways to clean this up but I'm not just ninja-like enough to really neaten it up. Any advice? Thanks in advance guys!
var colspan = $(".col header span"),
rowspan = $(".row header span"),
topspan = $(".top header span");
var colh2 = $(".col header h2").h2width();
var rowh2 = $(".row header h2").h2width();
var toph2 = $(".top header h2").h2width();
var colwidth = 820 - colh2;
var rowwidth = 820 - rowh2;
var topwidth = 820 - toph2;
colspan.css({float: 'left', width: colwidth});
rowspan.css({float: 'left', width: rowwidth});
topspan.css({float: 'left', width: topwidth});
["col", "row", "top"].forEach(function (className) {
var str = "." + className + " header";
var h2s = document.querySelectorAll(str + " h2");
var spans = document.querySelectorAll(str + " span");
var width = 820 - h2width(h2s);
Array.prototype.forEach.call(spans, function (span) {
span.style.float = "left";
span.style.width = width;
});
});
Because jQuery is always overkill.
I would do it like this maybe? shorter but maybe not as well documented:
$(".col header span, .row header span, .top header span").each(function(){
$(this).css({
float: 'left',
width: 820 - $(this).siblings("h2").width()
});
});
I would probably rewrite your code in the following way:
var conts = {
'col': jQuery('.col header'),
'row': jQuery('.row header'),
'top': jQuery('.top header')
};
jQuery.each(conts, function(index, val){
val.find('span').css({
'float': 'left',
'width': 820-val.find('h2').h2width()
});
});
This uses caching the main elements and then will iterate on all of them applying the similar actions.
See more information on jQuery's .each() function.
EDIT: Or even shorter:
jQuery('.col header, .row header, .top header').each(function(){
var current = jQuery(this);
current.find('span').css({
'float': 'left',
'width': 820 - current.find('h2').h2width()
});
});
Simply get rid of the duplicate code:
$.each(['.col', '.row', '.top'], function(i, cls) {
var width = $(cls + ' header h2').h2width();
$(cls + ' header span').css({
float: 'left',
width: 820 - width
});
});
Just use a function:
function updateStyle(name){
var headerSpan = $('.' + name + ' header span');
var headerH2 = $('.' + name + ' header h2');
headerSpan.css({float: 'left', width: 820 - headerH2.h2width()});
}
updateStyle('col');
updateStyle('row');
updateStyle('top');

Categories