Document write cause design flaw - javascript

I write a slider function. And base on value of slider function i print some messages in my document . When i use DW inside a slider after changing the value of the slider that messages are printed without style. How can i fix it?
$(function() {
$( "#slider-5" ).slider({
range:true,
min: parseInt(ctime[0]),
max: parseInt(ctime[ctime.length-1]),
values: [ parseInt(ctime[4]),parseInt(ctime[len])],
change: function( event, ui ) {
$( "#slidevalue" )
.val( "$" + formatDateTime(ui.values[ 0 ]) + " - $" + formatDateTime(ui.values[ 1 ]) );
new_var=ui.values[0];
document.write('<section id="cd-timeline" class="cd-container">')
var ctime = <?php echo json_encode($tweettimes); ?>;
for(var x=0; x<10; x++){
var datum = new Date(parseInt(ctime[x]));
document.write('<div class="cd-timeline-block">')
document.write('<div class="cd-timeline-img cd-location">')
document.write('<img src="img/cd-icon-location.svg" alt="Location">')
document.write('</div>')
document.write('<div class="cd-timeline-content">')
document.write('<h2>'+(x+1)+'</h2>')
document.write('<p>'+<?php echo json_encode($content); ?>[x]+'</p>')
document.write('<span class="cd-date">'+formatDateTime(datum)+'</span>')
document.write('</div>')
document.write('</div>')}
document.write('</section>')
}
});
});

Please don't use document.write. Use document.createElement() instead.
var body = document.getElementsByTagName('body')[0];
var section = document.createElement('section');
section.id = 'cd-timeline';
section.className = 'cd-container';
body.appendChild(section);
for (var x = 0; x < 10; x++) {
var datum = new Date(parseInt(ctime[x]));
var outerDiv = document.createElement('div');
outerDiv.className = 'cd-timeline-block';
section.appendChild(outerDiv);
var div = document.createElement('div');
div.className = 'cd-timeline-img cd-location';
outerDiv.appendChild(div);
var img = document.createElement('img');
img.src = 'img/cd-icon-location.svg';
img.setAttribute('alt', 'Location');
div.appendChild(img);
var div = document.createElement('div');
div.className = 'cd-timeline-content';
outerDiv.appendChild(div);
var h2 = document.createElement('h2');
div.appendChild(h2);
h2_text = document.createTextNode('foo');
h2.appendChild(h2_text);
var p = document.createElement('p');
div.appendChild(p);
p_text = document.createTextNode('bar');
p.appendChild(p_text);
var span = document.createElement('span');
span.className = 'cd-date';
div.appendChild(span);
span_text = document.createTextNode('foobar');
span.appendChild(span_text);
}
DEMO

Related

problems with appendChild <LI> and having Images match <LI> element

I would like to have 3 li elements and in those li elements I want 1 image.
All the images go into the first li element instead of being spread out.
Any suggestion would be greatly appreciated...
I have tried this but it does not work..
/////////////CODE///////////////////
var node = document.createElement("LI");
node.innerHTML =
"<ul class= rsox style=list-style-type: none>" +
"<li class=images id=imageList>" +
"</li>" +
"</ul>";
document.getElementById('sele').appendChild(node);
var image = { image1.jpg, image2.jpg, image3.jpg };
for (i = 0; i < image.length; i++) {
container = document.getElementById ("imageList");
container.innerHTML += "<img class= imageClass src=https://www.WEB-SITE-NAME.com/" + image[i] + ">"
}
Your code is really not clean and I think I know what you want to achieve, so here's my try in fixing your code:
var images = ["image1.jpg", "image2.jpg", "image3.jpg"];
var node = document.createElement("li"};
node.className = "rsox" ;
node.style.listStyleType = "none";
for (var i = 0; i < images.length; i++) {
var listItem = document.createElement("li");
listItem.className = "images";
var img = document.createElement("img");
img.className = "imageClass";
img.alt = "";
img.src = "https://www.WEB-SITE-NAME.com/" + images[i];
listItem.appendChild(img);
node.appendChild(listItem);
}
document.getElementById("sele").appendChild(node);
I haven't tested this, so if you get any errors or something, tell me.

How to create divs dynamically using JavaScript?

I want to create my divs in a way to access my JSON data and display all every time I create a new div. I have my first div display information through my JSON. This is what I got so far:
document.addEventListener('DOMContentLoaded', function() {
function function_name(data) {
return {data: ['nombre','telefono'],pie: 'texto'};
}
function _data(info) {
return info;
}
(function() {
var obj = {
id: 'id',
nombre: 'pepe',
telefono: '6691296347'
};
var body = document.getElementsByTagName('body')[0];
var div = document.createElement('div');
var p = document.createElement('p');
var span = document.createElement('span');
var _p = document.createElement('p');
var _span = document.createElement('span');
var btn = document.createElement('button');
var p_ = document.createElement('p');
var span_ = document.createElement('span');
p_.textContent = 'ID: ';
div.appendChild(p_);
p_.appendChild(span_);
span_.textContent = obj.id;
body.appendChild(div);
data = JSON.stringify(_data(obj));
p.textContent = 'nombre: ';
div.appendChild(p);
p.appendChild(span);
span.textContent = obj.nombre;
_p.textContent = 'Telefono: ';
div.appendChild(_p);
_p.appendChild(_span);
_span.textContent = obj.telefono;
div.appendChild(btn);
btn.textContent = 'button';
btn.setAttribute("id","id");
btn.addEventListener('click',function (e) {
console.log(_data(obj));
});
})();
});
I do not know if the is a basic javascript way to do that ...but i use jquery to add data to every new div element
data = {"obj" : [{"name" : "John"}]}
Json that returns object
$.each(data.obj, function(i, message){
var htmlMessage = "";
htmlMessage += "<div>";
htmlMessage += "<p>";
htmlMessage += "<span>";
htmlMessage += message.name;
htmlMessage += "</div>";
htmlMessage += "</p>";
htmlMessage += "</span>";
$("#body")[0].innerHtml += htmlMessage;
});
You can create a custom function for creating elements. For example:
// creating elements function
function createEl(config){
config = config || {};
if(!config.type) throw new Error('config type required!');
var new_el = document.createElement(config.type);
// check text param
if(config.text) new_el.textContent = config.text;
// maybe check for other element attributes (id, class, etc)
// ...
return new_el;
}
// some code
// ...
var obj = {
id: 'id',
nombre: 'pepe',
telefono: '6691296347'
};
var body = document.getElementsByTagName('body')[0];
var div = createEl({ type: 'div' });
var p = createEl({ type: 'p', text: 'nombre: '});
var span = createEl({ type: 'span', text: obj.nombre});
// other elements
// ...
// and then append
p.appendChild(span);
div.appendChild(p);
body.appendChild(div);
// ...

how to create several buttons dynamically in for loop

Here id my code. I want to append 4 buttons inside the specific div. In the other words, I want to put these 4 buttons inside ''. Now it works but they are not inside the div.
getmyItems function is a function that contains an array of information like: title, description , age ,... .
Help
getmyItems(param, function(data) {
var mtItem = JSON.stringify(data);
myItem = JSON.parse(mtItem);
var Item = document.getElementById('myItems');
for (var i = 0; i < myItem.results.length; i++) {
var buffer = "";
buffer += '<div class="act-time">';
buffer += '<div class="activity-body act-in">';
buffer += '<span class="arrow"></span>';
buffer += '<div class="text">';
buffer += '<p class="attribution">';
buffer += ''+myItem.results[i].title+'';
buffer += myItem.results[i].description;
buffer += '</p>';
buffer += '</div>';
buffer += '</div>';
buffer += '</div>';
var div = document.createElement('div');
div.innerHTML = buffer;
//var elem = div.firstChild;
Item.appendChild(div);
var btn = document.createElement('input');
btn.setAttribute('type', 'button');
btn.setAttribute('class', 'btn btn-danger');
btn.value = "Delete";
btn.onclick = (function(i) {
return function() {
var c=confirm('Are you Sure? ');
if (c==true)
doDelete(myItem.results[i].item_id);
};
})(i);
Item.appendChild(btn);
var show_btn=document.createElement('input');
show_btn.setAttribute('type','button');
show_btn.setAttribute('class','btn btn-primary');
show_btn.value="ShowInDetail";
show_btn.onclick=(function(i){
return function(){
showInDetail(myItem.results[i]);
window.location='showInDetail.html';
};
})(i);
Item.appendChild(show_btn);
var extend_btn=document.createElement('input');
extend_btn.setAttribute('class','btn btn-warning');
extend_btn.setAttribute('type','button');
extend_btn.value="Extend";
extend_btn.onclick=(function(i){
return function(){
extendItem(myItem.results[i]);
window.location='extendItem.html';
};
})(i);
Item.appendChild(extend_btn);
var bookmark=document.createElement('input');
bookmark.setAttribute('type','button');
bookmark.setAttribute('class','btn btn-primary');
bookmark.value='Bookmark';
bookmark.onclick=(function(i){
return function(){
var p={user_id:localStorage.getItem('user_id')};
window.localStorage.setItem('this_item_id', myItem.results[i].item_id);
getBookmarks(p, function(d){
var bk=JSON.stringify(d);
bk=JSON.parse(bk);
if(bk.results){
var l=0;
for(var j in bk.results){
if(bk.results[j].item_id==localStorage.getItem('this_item_id')){
removeBookmark(bk.results[j]);
l=1;
}
}if(l==0){
addBookmark(myItem.results[i]);
}
}else{
addBookmark(myItem.results[i]);
}
});
};
})(i);
Item.appendChild(bookmark);
//document.getElementById(i).appendChild(btn);
}
});
In what specific div do you want them? So far, in this way the four buttons are inside the myItens div see in the fiddle and in the code below.
var getmyItems = function(data) {
var item = document.getElementById('myItems');
for (var i = 0; i < data.length; i++) {
var result = data[i];
// creation of the buffer outer div
var buffer = document.createElement('div');
buffer.className = 'act-time';
//creation of de activity-body
var activity = document.createElement('div');
activity.className = 'activity-body act-in';
//creation of the first span
var arrow = document.createElement('span');
arrow.className = 'arrow';
//creation of the most inner div
var textDiv = document.createElement('div');
textDiv.className = 'text';
//creation of the content of the most inner div
var attribution = '';
attribution += '<p class="attribution">';
attribution += '' + result.title + '';
attribution += result.description;
attribution += '</p>';
//initialize the text div
textDiv.innerHTML = attribution;
//put the arrow span inside the activity div
activity.appendChild(arrow);
// put the text div inside the activity div
activity.appendChild(textDiv);
//put the activity inside the buffer div
// each time appendChild is applied the element is attach tho the end of the target element
buffer.appendChild(activity);
var div = document.createElement('div');
div.appendChild(buffer);
item.appendChild(div);
var btn = document.createElement('input');
btn.setAttribute('type', 'button');
btn.setAttribute('class', 'btn btn-danger');
btn.value = "Delete";
btn.onclick = (function(i) {
return function() {
var c = confirm('Are you Sure? ');
if (c === true) {
//do something;
};
};
})(i);
// now that all div are created you can choose which div you want to put the button inside.
// in this I chose the buffer.
buffer.appendChild(btn);
var showBtn = document.createElement('input');
showBtn.setAttribute('type', 'button');
showBtn.setAttribute('class', 'btn btn-primary');
showBtn.value = "ShowInDetail";
showBtn.onclick = (function(i) {
return function() {
window.location = 'showInDetail.html';
//do something
};
})(i);
// button is append to the end of the buffer
buffer.appendChild(showBtn);
var extendBtn = document.createElement('input');
extendBtn.setAttribute('class', 'btn btn-warning');
extendBtn.setAttribute('type', 'button');
extendBtn.value = "Extend";
extendBtn.onclick = (function(i) {
return function() {
window.location = 'extendItem.html';
//do something
};
})(i);
// button is append to the end of the buffer
buffer.appendChild(extendBtn);
var bookmark = document.createElement('input');
bookmark.setAttribute('type', 'button');
bookmark.setAttribute('class', 'btn btn-primary');
bookmark.value = 'Bookmark';
bookmark.onclick = (function(i) {
return function() {
var p = { user_id: localStorage.getItem('user_id') };
window.localStorage.setItem('this_item_id', myItem.results[i].item_id);
//do something
};
})(i);
// button is append to the end of the buffer
buffer.appendChild(bookmark);
}
};
var myItem = [{ title: 'person', description: 'familyName' }, { title: 'ohterPerson', description: 'otherFamilyName' }];
getmyItems(myItem);

Javascript jslint says spell_img is used before being declared

What is wrong with my code, I checked it with an online jslint and it says spell_img is used before being declared?
spell_img = new Image();
spell_img.src = '/images/standard/spellcheck.gif';
spell_img.setAttribute('title',_lang_spellcheck );
function find_text_boxes()
{
myforms = document.forms;
for( i=0;i < myforms.length; i++ )
{
textareas = myforms[i].getElementsById('textarea');
for( y=0; y < textareas.length; y++ )
{
spelllink = document.createElement('a');
spelllink.setAttribute('href',"javascript:spellCheck(" + i + ", '" + textareas[y].name + "')");
spelllink.appendChild( spell_img.cloneNode(true) );
textareaParent = textareas[y].parentNode;
textareaParent.insertBefore( spelllink, textareas[y].nextSibling );
}
}
}
Step 1: declare variables. In JavaScript, this is done using var. var scopes the variable to the scope where the var was found; scopes in JavaScript are (currently) function-based.
var spell_img = new Image();
spell_img.src = '/images/standard/spellcheck.gif';
spell_img.setAttribute('title',_lang_spellcheck );
function find_text_boxes()
{
var myforms = document.forms;
for( var i=0;i < myforms.length; i++ )
{
var textareas = myforms[i].getElementsById('textarea');
for( var y=0; y < textareas.length; y++ )
{
var spelllink = document.createElement('a');
spelllink.setAttribute('href',"javascript:spellCheck(" + i + ", '" + textareas[y].name + "')");
spelllink.appendChild( spell_img.cloneNode(true) );
textareaParent = textareas[y].parentNode;
textareaParent.insertBefore( spelllink, textareas[y].nextSibling );
}
}
}
Step 2: getElementsById is not a thing that exists. It’s getElementsByTagName.
var spell_img = new Image();
spell_img.src = '/images/standard/spellcheck.gif';
spell_img.setAttribute('title',_lang_spellcheck );
function find_text_boxes()
{
var myforms = document.forms;
for( var i = 0; i < myforms.length; i++ )
{
var textareas = myforms[i].getElementsByTagName('textarea');
for( var y = 0; y < textareas.length; y++ )
{
var spelllink = document.createElement('a');
spelllink.setAttribute('href',"javascript:spellCheck(" + i + ", '" + textareas[y].name + "')");
spelllink.appendChild( spell_img.cloneNode(true) );
textareaParent = textareas[y].parentNode;
textareaParent.insertBefore( spelllink, textareas[y].nextSibling );
}
}
}
Step 3: wait, why are you even getting forms first?
var spell_img = new Image();
spell_img.src = '/images/standard/spellcheck.gif';
spell_img.setAttribute('title',_lang_spellcheck );
function find_text_boxes() {
var textareas = document.getElementsByTagName('textarea');
for(var i = 0; i < textareas.length; i++) {
var spelllink = document.createElement('a');
spelllink.setAttribute('href',"javascript:spellCheck(" + i + ", '" + textareas[y].name + "')");
spelllink.appendChild( spell_img.cloneNode(true) );
textareaParent = textareas[y].parentNode;
textareaParent.insertBefore( spelllink, textareas[y].nextSibling );
}
}
Step 4: javascript: URIs are bad. Inline JavaScript is bad. Inline JavaScript in inline URL in JavaScript? That’s really bad and is kind of like eval and all sorts of things. Create a function and make spellCheck accept an element object, not form index, yuck. title is a property as well as an attribute (like src), by the way:
var forEach = Array.prototype.forEach;
var spell_img = new Image();
spell_img.src = '/images/standard/spellcheck.gif';
spell_img.title = _lang_spellcheck;
function find_text_boxes() {
var textareas = document.getElementsByTagName('textarea');
forEach.call(textareas, function(textarea) {
var spellLink = document.createElement('a');
spellLink.href = "#";
spellLink.addEventListener("click", function(e) {
e.preventDefault();
spellCheck(textarea);
}, false);
spellLink.appendChild(spell_img.cloneNode(true));
textarea.parentNode.insertBefore(spelllink, textareas[y].nextSibling);
});
}
If you need to be compatible with old IE without shivs, that’s doable:
var spell_img = new Image();
spell_img.src = '/images/standard/spellcheck.gif';
spell_img.title = _lang_spellcheck;
function find_text_boxes() {
var textareas = document.getElementsByTagName('textarea');
for (var i = 0; i < textareas.length; i++) {
(function(textarea) {
var spellLink = document.createElement('a');
spellLink.href = "#";
spellLink.onclick = function() {
spellCheck(textarea);
return false;
};
spellLink.appendChild(spell_img.cloneNode(true));
textarea.parentNode.insertBefore(spelllink, textareas[y].nextSibling);
})(textareas[i]);
});
}
You can really put the cherry on top with some event delegation.
function addSpellLink(textarea) {
var link = document.createElement("a");
link.className = "spell-link";
link.href = "#";
link.appendChild(spell_img.cloneNode(true));
textarea.parentNode.insertBefore(link, textarea.nextSibling);
}
function findTextboxes() {
Array.prototype.forEach.call(document.getElementsByTagName("textarea"), addSpellLink);
}
document.addEventListener("click", function(e) {
if (e.target.classList.contains("spell-link")) {
e.preventDefault();
spellCheck(e.previousElementSibling);
}
}, false);
var spell_img = new Image();//place any one of these right at the top of your scope.
or
window.spell_img = new Image();//replace first line

Javascript regex classname issue

Apologies for the vague title of this question!
I have the following JS, it looks for img tags with images of certain sources. It then replaces the img tag with a span so that I can replace the images/icons with iconfonts.
var paths = [
"folder%2Fadd",
"folder%2Fclear",
"folder%2Fdelete",
"folder%2Fedit",
"folder%2Fmove",
"folder%2Fsort",
];
var fullPaths = paths.map(function(x) { return "img[src*='" + x + "']"; } );
var imgs = document.querySelectorAll(fullPaths);
for (var i = 0; i < imgs.length; i++) {
var span = document.createElement("span");
span.addClass("iconfont");
span.title = imgs[i].parentNode.title;
imgs[i].parentNode.replaceChild(span, imgs[i]);
}
Everything is working nicely so far, but there is one more issue that I cannot solve.
Apart from adding a class to the span of .iconfont, I also want to add two more classes to the span - 1) the original class of the replaced img element, and 2) the name of the image source as in my array, but without the 'folder/' bit in front.
So, at the moment I have:
<img class = "tinyicon" src="******/t/edit">
and my script creates this in the DOM:
<span class = "iconfont">
But I want my script to create the following:
<span class = "iconfont tinyicon edit">
That is what I am after :)
Thanks for having a look!
var paths = [
"folder%2Fadd",
"folder%2Fclear",
"folder%2Fdelete",
"folder%2Fedit",
"folder%2Fmove",
"folder%2Fsort",
];
var fullPaths = paths.map(function(x) { return "img[src*='" + x + "']"; } );
var imgs = document.querySelectorAll(fullPaths);
for (var i = 0; i < imgs.length; i++) {
var img = imgs[i],
iClass = img.className,
iSrc = img.src.split('/').pop(),
span = $('<span />', {'class': 'iconfont '+iClass+' '+iSrc,
title : img.parentNode.title
});
$(img).replaceWith(span);
}
Change this:
var span = document.createElement("span");
span.addClass("iconfont");
to this:
var span = document.createElement("span");
span.className = "iconfont tinyicon edit";
Your addClass() wouldn't work anyway because span is a DOM node, not a jQuery object.
var span = document.createElement("span");
var className = "iconfont " + imgs[i].className + ' ' + imgs[i].src.match(/([a-z])$/i, '')
span.className = className ;
span.title = imgs[i].parentNode.title;
imgs[i].parentNode.replaceChild(span, imgs[i]);

Categories

Resources