ie8 appendchild not working - javascript

I am developing a website that must run on IE8.
I need to create a bunch of dynamic paragraphs since I am pulling data from a server at runtime.
To do so I am using the following code:
var tempAbstract = layerItems[iter].abstract; // string
var text1 = document.createElement('p'); // paragraph element
text1.textContent = tempAbstract; // assigning string to paragraph
$(text1).css({top: iter*25 + 30, left: 200, position:'absolute'}); // positioning
$(text1).css('color', 'black'); // make text color black
document.getElementById("listLayersWrapper").appendChild(text1); // appending to div
My problem is that the text won't render.
When I count the paragraph divs before and after I add the element, the counter increments as you would expect it should yet the text does not render. Additionally, when I get call position().left and position.top() the element also has the right coordinates.
I am not sure what I am doing wrong and have run out of options.

The issue doesn't appear to be with appendChild, but with textContent. According to the MDN page, textContent is only available in IE9 and up. Older versions of IE do have a non-standard innerText property you can use to achieve the same thing. Here is how you can implement this.
Example:
var tempAbstract = layerItems[iter].abstract;
var text1 = document.createElement('p');
if(text1.textContent !== undefined)
{
text1.textContent = tempAbstract;
}else{
text1.innerText = tempAbstract;
}
$(text1).css({top: iter*25 + 30, left: 200, position:'absolute'});
$(text1).css('color', 'black');
document.getElementById("listLayersWrapper").appendChild(text1);
Alternatively, this could be implemented in jQuery.
Example:
$('<p></p>')
.text(layerItems[iter].abstract)
.css({
top: iter*25 + 30,
left: 200,
position:'absolute',
color: 'black'
})
.appendTo("#listLayersWrapper");

Related

Using variables within css javascript method

Anyone see what I'm doing wrong here? Creating circles using jQuery and then filling them with a variable from an input field.
The issue: The variable firstletter is is not being displayed when 1. there's input in the input box and 2. when the result pane is clicked to generate a circle. The variable should be in the middle of the circle.
jQuery:
// making of the circles
$('<div/>').attr({
'id': i
}).addClass('circle').css({
'top': e.pageY - 75,
'left': e.pageX - 75,
'content': firstletter
}).appendTo('#area');
firstletter being a variable here which I am using with the content css property.
Here's the fiddle:
http://jsfiddle.net/hslincoln/ZM7dC/
Need to use .val() instead of .text() and add the firstletter as the content of the div since https://developer.mozilla.org/en-US/docs/Web/CSS/content
Demo:http://jsfiddle.net/robschmuecker/ZM7dC/7/
var i = 0;
$('#area').bind('click', function (e) {
// input stuff
$('#jibberjabber').val(
function (index, value) {
var jimmy = value.substring(1);
return jimmy;
});
// push letter to variable ready for circle
var jibberjabbercontent = $('#jibberjabber').val();
var firstletter = jibberjabbercontent.charAt(0);
console.log(jibberjabbercontent, firstletter);
// making of the circles
$('<div>' + firstletter + '</div>').attr({
'id': i
}).addClass('circle').css({
'top': e.pageY - 75,
'left': e.pageX - 75
}).appendTo('#area');
i++;
});
Have updated the fiddle as per your requirement.
the problem is, you used text() instead of val().
jQuery
$('#'+i).html('<span class="charIn">'+firstletter+'</span>');
css
.charIn{
position:absolute;
top:47%;
left:46%;
}
used the above code to add the letter inside the span to make the letter appear center of the cirlce.
here is the working fiddle
Content can only be used with pseudo tags. Since the circle divs are not, the content is simply not displaying. Instead use
.addClass('circle').css({
'top': e.pageY - 75,
'left': e.pageX - 75,
}).text(firstletter).appendTo('#area');
Also you can't use .text to grab jibberjabber content. Instead use .val
Quote from W3Schools:
The content property is used with the :before and :after pseudo-elements, to insert generated content.
You don't have either of those, so the content is going nowhere.
#RobSchmuecker The OP wants the letter to be in the center. Also, your code skips the first letter.

Adding additional data to Raphael.js text element

I am working on some sort of graph in Raphael.js, I made it first with D3 (which can be found here), but that didn't work as well in Internet Explorer. I've heard Raphael.js does it much better in IE.
So now I am trying to convert my D3 code to Raphael, I made some progress, but I have some problems trying to add additional data or an id to a text element, which I can use to modify the text of a specific element. In D3 I've used .attr("weight", weight) on a text element, and this works fine. But in Raphael, I can't get it to work.
I've tried giving the text an ID like this:
var text = paper.text((y * 50) + 20, (i * 50) + 15, weight).attr({
fill: '#000'
});
text.attr({
"font-size": 16,
"font-family": "Arial, Helvetica, sans-serif"
});
text.id = weight;
But still no luck in logging that ID. If it is not clear why I need this ID, check the before mentioned jsFiddle I made with D3, I need to get a specific element to change its text.
var grossRisks = [{
"weight": "1",
"number": "5"
}, {
"weight": "4",
"number": "6"
}];
function populateChart(riskArray) {
var element = document.getElementsByTagName("text"),
attr;
var loops = riskArray.length;
for (var i = 0; i < loops; i++) {
var obj = riskArray[i];
for (var x = 0; x < element.length; x++) {
attr = element[x];
if (/^text/.test(attr.nodeName)) {
console.log(
"Weight: " + attr.getAttribute("weight"));
if (attr.getAttribute("weight") == obj.weight) {
attr.textContent = obj.number;
}
}
}
}
I have tried multiple things like making a new set and adding data to that set, but I don't know where to go from that point, like how do I change the text of a set with a specific ID?
newSet[i] = paper.set();
newSet[i].push(rect, text);
newSet[i].attr({
cursor: 'pointer'
}).data('weight', weight);
newSet[i].click(function () {
console.log(this.id("weight"));
});
The not working code of Raphael can be found in this jsFiddle.
The issues are
You get the raw DOM nodes, and not the RaphaelJS wrapped objects (because you use document.getElementsByTagName)
You set data but try to access it through attr.
In the fiddle, the newSet is not correctly built becuase you use the i variable which goes from 1 to 5.. to calculate the index you need to account for both of the loop counter.
So the changes made are
When populating the newSet
var index = (i*5) + y;
newSet[index] = paper.set();
When clearing and populating the chart use newSet
newSet[x].forEach(function(item){
if (item.type=='text')
attr=item;
});
to get the text node.
Working demo at Have a look at http://jsfiddle.net/G94sQ/22/
You can ofcourse use id to simplify the code
To assign an id just use text.id = 'your-id'
When creating the newSet
text.id = 'weight-'+weight;
and when clearing/populating
attr = paper.getById('weight-'+obj.weight);
Working demo at http://jsfiddle.net/G94sQ/23/
(additionally: you are using jquery 1.11 in which the .toggle method just shows/hide the element and does not rotate the click functions as earlier versions. So I changed your code to 1.4.2 as a quick fix..)

Does Jquery/Javascript require an elem to be in the DOM to use .css()?

if(typeof this.description === 'undefined') {alert('No Description Set!'); return false;}
var tempDiv = document.createElement('div'); //create a div outside of the DOM
tempDiv.className = 'descriptionColumn formBox contentRow'; //make sure and use the
//same/equivlent class(s) to ensure accuracy
tempDiv.innerHTML = this.description; //insert the text
document.body.appendChild(tempDiv); //render div
lineHeight = parseInt($(tempDiv).css('line-height')); //get the line-height (make sure this is specified in CSS!)
//also we use Jquery here to handle any vender inconsistencies,
divHeight = tempDiv.clientHeight; //get the div height
tempDiv.parentNode.removeChild(tempDiv); //clean up, delete div
delete tempDiv;
return divHeight/lineHeight; //divide the height by the line-height and return
This code works, I am trying to calculate the number of lines in a div. That said I wasn't able to get the line-height until after I added this element to the DOM.
Origionally I planned on not adding it at all because I only use it to calcuate the number of lines in the DIV.
It makes sense that it wouldn't have a height until I added it, I am just wondering if I did the right thing, or if there is a way to get the line-height without adding it to the DOM in the first place.
Rendering/Layout decision by browser is taken by browser 2 conditions:
1)new element is inserted
2)some element's style has been changed
3)sometimes when window is resized
so until the element is in DOM Tree browser will not give Layout related style to it.
consider following code:
var div = document.createElement(div);
var style = window.getComputedStyle(div);
console.log( style.color );//prints "" (empty string)
why??
because window.getComputedStyle() returns the CSS style which are actully present in DOM(browser).
now,
document.body.appendChild(div);
var style = window.getComputedStyle(div);
console.log( style.color );//prints rgb(somevalue)
why??
because rendering engine has decided the CSS properties.
//One gotcha
var div2 = document.createElement("div");
div2.style.color = "red";
console.log( $(div2).css("color") ); //prints red because jQuery gives preference to div2.style.color over window.getComputedStyle(div2);
but console.log ( window.getComputedStyle(div2).color );//prints "" .... this proves that browser has not yet decided the properties of div2
Yes, it is. But ... if you have jQuery on your page, why don't you use it?
var $div = $('<div/>', {
class: 'descriptionColumn formBox contentRow',
text: 'Description',
css: {
position: 'absolute',
left: '-99999px'
}
}).prependTo('body'); // element wouldn't be visible for user on this step
//your calculations
$div.remove();

How to get margin value of a div in plain JavaScript?

I can get height in jQuery with
$(item).outerHeight(true);
but how do I with JS?
I can get the height of the li with
document.getElementById(item).offsetHeight
but i will always get "" when I try margin-top:
document.getElementById(item).style.marginTop
The properties on the style object are only the styles applied directly to the element (e.g., via a style attribute or in code). So .style.marginTop will only have something in it if you have something specifically assigned to that element (not assigned via a style sheet, etc.).
To get the current calculated style of the object, you use either the currentStyle property (Microsoft) or the getComputedStyle function (pretty much everyone else).
Example:
var p = document.getElementById("target");
var style = p.currentStyle || window.getComputedStyle(p);
display("Current marginTop: " + style.marginTop);
Fair warning: What you get back may not be in pixels. For instance, if I run the above on a p element in IE9, I get back "1em".
Live Copy | Source
Also, you can create your own outerHeight for HTML elements. I don't know if it works in IE, but it works in Chrome. Perhaps, you can enhance the code below using currentStyle, suggested in the answer above.
Object.defineProperty(Element.prototype, 'outerHeight', {
'get': function(){
var height = this.clientHeight;
var computedStyle = window.getComputedStyle(this);
height += parseInt(computedStyle.marginTop, 10);
height += parseInt(computedStyle.marginBottom, 10);
height += parseInt(computedStyle.borderTopWidth, 10);
height += parseInt(computedStyle.borderBottomWidth, 10);
return height;
}
});
This piece of code allow you to do something like this:
document.getElementById('foo').outerHeight
According to caniuse.com, getComputedStyle is supported by main browsers (IE, Chrome, Firefox).
I found something very useful on this site when I was searching for an answer on this question. You can check it out at http://www.codingforums.com/javascript-programming/230503-how-get-margin-left-value.html. The part that helped me was the following:
/***
* get live runtime value of an element's css style
* http://robertnyman.com/2006/04/24/get-the-rendered-style-of-an-element
* note: "styleName" is in CSS form (i.e. 'font-size', not 'fontSize').
***/
var getStyle = function(e, styleName) {
var styleValue = "";
if (document.defaultView && document.defaultView.getComputedStyle) {
styleValue = document.defaultView.getComputedStyle(e, "").getPropertyValue(styleName);
} else if (e.currentStyle) {
styleName = styleName.replace(/\-(\w)/g, function(strMatch, p1) {
return p1.toUpperCase();
});
styleValue = e.currentStyle[styleName];
}
return styleValue;
}
////////////////////////////////////
var e = document.getElementById('yourElement');
var marLeft = getStyle(e, 'margin-left');
console.log(marLeft); // 10px
#yourElement {
margin-left: 10px;
}
<div id="yourElement"></div>
Here is my solution:
Step 1: Select the element
Step 2: Use getComputedStyle and provide the element to it
Step 3: Now access all the properties
const item = document.getElementbyId('your-element-id');
const style= getComputedStyle(item);
const itemTopmargin = style.marginTop;
console.log(itemTopmargin)
It will give you margin with px units like "16px" which you might not want.
You can extract the value using parseInt()
const marginTopNumber = parseInt(itemTopmargin)
console.log(marginTopNumber)
It will give you the numerical value only (without any units).

jQuery placeholder/hint JavaScript that keeps the hint on focus

There are hundreds of jQuery placeholder/hint plugin. But none that do what I want it to do
I'm looking for one that will:
Fade the hint when the user focuses on the field, but not clear it until the user starts typing (like the StackOverflow/iOS one)
Will work with the HTML5 placeholder attribute.
Built with jQuery
Cross browser (including IE7/IE8)
Uses unobtrusive JavaScript
Ideally would also Work with password fields
#Roatin Marth is right; if you're going to treat the text as a placeholder, it's supposed to clear. That's the very definition of a placeholder.
Still, I mocked up a proof of concept that you're welcome to use as you like. However, I had to make the placeholder text so light it's barely viewable to keep it from garbling the front text too much (which is why the default behavior is to clear it).
You can see it working at: http://jsfiddle.net/zYQ4Q/4/
// Create placeholder input to serve as background
var $test = $('#test');
var $placeholder = $test.clone().removeAttr('id').removeAttr('placeholder').addClass('placeholder').val($test.attr('placeholder'));
var $container = $('<span class="placeholder-container"></span>');
$container.insertAfter($test).append($test).append($placeholder);
// Basic styling
$container.css({
position: 'relative'
});
$test.css({
position: 'absolute',
left: 0,
top: 0,
zIndex: 10,
backgroundColor: 'transparent',
borderColor: 'transparent'
});
$placeholder.css('color', 'transparent');
// Behavior for focus and blur to achieve the visual effect
$test.focus(function(){
var $input = $(this);
var $placeholder = $('.placeholder', $input.parent());
$placeholder.css('color', '#e0e0e0');
}).blur(function(){
var $input = $(this);
var $placeholder = $('.placeholder', $input.parent());
if ($input.val() == '')
$placeholder.css('color', 'transparent');
}).keyup(function(){
var $input = $(this);
if ($input.val().trim() != '') {
$placeholder.val('');
} else {
$placeholder.val($input.attr('placeholder'));
}
});
UPDATE: Code and jsfiddle have been updated to reflect new changes based on OP's comment. The placeholder now clears after text has been entered into the input.
Update, thanks to chrisdpratt I've actually found a plugin that does what I want it to:
Demo: http://labs.mario.ec/jq-watermark/
Source: https://github.com/marioestrada/jQuery-Watermark

Categories