Javascript append keep adding elements - javascript

I am trying to append list[i].name and list[i].email once every time sponsorListTree li is being clicked. I can append the document.getElementById("name").appendChild(div_group); but the problem occurs when i click the div a few times, the same data will add up instead of displaying the result only once
$.ajax({
url: 'test.php',
method: 'GET',
success: function(data){
var list = data;
for (i = 0; i < list.length; i++) {
$('#sponsorListTree li').attr('id', function(i) {
return 'sponsorListTree'+(i+1);
});
$('#sponsorListTree').append('<li class="button"><tbody><tr><td><span id="information" class="details"><br/><br/> '+ 'Email: ' + list[i].email + '</br></br> '+ 'Contact No: ' + list[i].contact.phone + ' </br></br> '+ 'Joined date: ' + list[i].date + ' </br> </br>'+ 'InvestedAmount: ' + list[i].account.investedAmount + '</span></td></tr></tbody><table></li>');
}
$("#sponsorListTree li").click(function() {
var name = $(this)[0].innerHTML;
var details = $(this).find('span')[0].innerHTML
var div_name = document.createElement('div');
var div_details = document.createElement('div');
div_name.innerHTML = name;
div_details.innerHTML = details;
div_name.className ="nameDetail";
div_details.className ="detail";
var div_group = document.createElement('div');
div_group.append(div_name);
div_group.append(div_details);
document.getElementById("name").append(div_group);
});
$(".button").click(function() {
$("span").toggleClass("details");
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul style=" overflow-x: auto; width: 400%; height: 600px;">
<li>
<a id="root" href="#"></a>
<ul id ="sponsorListTree">
</ul>
</li>
</ul>
<div id = "name" class="control-label"></div>

Related

Blogspot json - load post content on click

$.ajax({
url: 'https://mailliw88.blogspot.com/feeds/posts/default?start-index=1&max-results=2&alt=json-in-script',
type: 'get',
dataType: "jsonp",
success: function(data) {
var entry = data.feed.entry;
for (var i = 0; i < entry.length; i++) {
postTitle = entry[i].title.$t;
postTitleLink = entry[i].title.$t.replace(/\s+/g, '-').toLowerCase();
items = '<div class="items"><h2>' + postTitle + '</h2></div>';
document.getElementById('showlists').innerHTML += items;
postContent = entry[i].content.$t;
content = '<div class="contentWrap"><div id="close">CLOSE</div><h1>' + postTitle + '</h1><div>' + postContent + '</div></div>';
document.getElementById('showlists').innerHTML += content;
}
}
});
h1 {margin:0}
.contentWrap {border:1px solid red;
padding:5px}
#close {color:red;text-align:right}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='showlists'>
</div>
How to load post content only when clicking the title?
I can use .toggle in jquery but I need to load and "unload" content, not just showing and hiding it. I hope i'm making sense.
My skill is limited to css only, thank you for your help.
You can use display:none to <div class="contentWrap"> and on click of a tag you can show the content using closest() and next().And on click of close again use "display", "none" to hide that content div .
Demo Code :
$.ajax({
url: 'https://mailliw88.blogspot.com/feeds/posts/default?start-index=1&max-results=2&alt=json-in-script',
type: 'get',
dataType: "jsonp",
success: function(data) {
var entry = data.feed.entry;
for (var i = 0; i < entry.length; i++) {
postTitle = entry[i].title.$t;
postTitleLink = entry[i].title.$t.replace(/\s+/g, '-').toLowerCase();
items = '<div class="items"><h2>' + postTitle + '</h2></div>';
document.getElementById('showlists').innerHTML += items;
postContent = entry[i].content.$t;
//added display none and added class = close
content = '<div style="display:none"class="contentWrap"><div class="close">CLOSE</div><h1>' + postTitle + '</h1><div>' + postContent + '</div></div>';
document.getElementById('showlists').innerHTML += content;
}
}
});
//on click of a tag show content
$(document).on("click","a",function(){
//a->closest div->next content->show
$(this).closest(".items").next(".contentWrap").css("display", "block");
})
//onclick of close -> hide again
$(document).on("click",".close",function(){
$(this).closest(".contentWrap").css("display", "none");
})
h1 {margin:0}
.contentWrap {border:1px solid red;
padding:5px}
.close {color:red;text-align:right}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='showlists'>
</div>
Update 1 :
You can assign i value some custom attribute and then use same index value to access post content.In below code snippets i have not send again request to server to load json on click of a instead i have use some variable to store content of data.feed.entry in some variable and then use this to add content .
Demo Code :
var datas = "";
$.ajax({
url: 'https://mailliw88.blogspot.com/feeds/posts/default?start-index=1&max-results=2&alt=json-in-script',
type: 'get',
dataType: "jsonp",
success: function(data) {
//adding entry content in datas to use later
datas = data.feed.entry;
var entry = data.feed.entry;
for (var i = 0; i < entry.length; i++) {
postTitle = entry[i].title.$t;
postTitleLink = entry[i].title.$t.replace(/\s+/g, '-').toLowerCase();
//passing index no i.e : " i " in custom attribute
items = '<div class="items"><h2><a data-val=' + i + ' href="#' + postTitleLink + '">' + postTitle + '</a></h2></div>';
document.getElementById('showlists').innerHTML += items;
}
}
});
$(document).on("click", "a", function() {
$(".contentWrap").remove(); //remove previous div
var ids = $(this).attr('data-val');
console.log(ids)
//getting data that index position got from a tag
postTitle = datas[ids].title.$t;
postTitleLink = datas[ids].title.$t.replace(/\s+/g, '-').toLowerCase();
postContent = datas[ids].content.$t;
content = '<div class="contentWrap"><div class="close">CLOSE</div><h1>' + postTitle + '</h1><div>' + postContent + '</div></div>';
document.getElementById('showlists').innerHTML += content;
})
h1 {margin:0}
.contentWrap {border:1px solid red;
padding:5px}
.close {color:red;text-align:right}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="showlists"></div>

Create second or next <li> under default <li> after reload page | jQuery, LocalStorage

I try to create LocalStorage data for My Folder Creation .
HTML :
This is my default li. I call it All audience folder's
<!-- Result goes here -->
<ul class="nav">
<li>
<div class="zf-folder" style="width: 232px;">
<div class="_tabFolder _itemPosition" style="height: 50px;border-bottom:1px groove; user-select: none;">
<div class="_sideFolder"></div>
<div class="_iconText" style="width: 215px">
<div class="ellipsis">
<div class="_1i5w">
<div class="_icon-col">
</div>
</div>
All Audiences<span class="hyperspan" style="position:absolute; width:100%; height:100%; left:0; top:0;"></span>
</div>
</div>
</div>
</div>
</li>
</ul>
jQuery :
var count = 1;
$(".submitButton").click(function() {
let label = count++;
// make a function that returns the DOM with updated count
function getNewList(foldername) {
var addFolder = '<li>' +
'<div class="zf-folder" style="width: 232px;">' +
'<div class="_tabFolder _itemPosition" style="height: 50px;border-bottom:1px groove; user-select: none;">' +
'<div class="_sideFolder"></div>' +
'<div class="_iconText" style="width: 215px">' +
'<div class="ellipsis">' +
'<div class="_iconFolder">' +
'<div class="_icon-col">' +
'</div>' +
'</div>' +
'<a href="#folder' + label +
'" data-toggle="tab" style="text-decoration: none;">' +
foldername + '<span class="hyperspan" style="width:100%; height:100%; left:0; top:0;"></span></a>' +
'</div>' +
'</div>' +
'</div>' +
'</div>' +
'</li>';
return addFolder;
}
var inputan = $("#input_nameFolder").val();
// update the result array
var result = JSON.parse(localStorage.getItem("folderList"));
if (result == null) {
result = [];
}
let newfolderHTML = getNewList(inputan);
result.push({
folder: newfolderHTML
});
// save the new result array
localStorage.setItem("folderList", JSON.stringify(result));
// append the new li
$(".nav").append(newfolderHTML); // i want include myDiv
//clear input
$("#input_nameFolder").val('');
});
// on init fill the ul
var result = JSON.parse(localStorage.getItem("folderList"));
if (result != null) {
//get the nav reference in DOM
let nav = $(".nav");
//clear the html contents
nav.html('');
for (var i = 0; i < result.length; i++) {
var item = result[i];
$(".nav").append(item.folder);
}
}
How to adding new <li> tag under my default li (all audience)
after reload page/click run jsfiddle when user input a new value?
You can see after adding an input and reload web / jsfiddle, new input folder's (second li) overwrite all audience (first li).
JSFiddle
you just have to save the initial element upon initialization, see:
// on init fill the ul
var result = JSON.parse(localStorage.getItem("folderList"));
if (result != null) {
//get the nav reference in DOM
let nav = $(".nav");
//clear the html contents
nav.html('');
for (var i = 0; i < result.length; i++) {
var item = result[i];
$(".nav").append(item.folder);
}
} else {
//Save the "All Audiences" content upon empty folderList
let initialElement = [];
initialElement.push({
folder: $('ul.nav').html()
});
localStorage.setItem("folderList", JSON.stringify(initialElement));
}
See: JSFiddle

How to insert fields using jQuery?

I'm trying to realise this code in the snippet, for the moment I'm working only on the button Label, so when I click on this button, it adds a small formular that allows to creat this a label in the right side by clicking on OK. However, even if I click on OK nothing happens, normally a label should appear with the name inserted in the textfield "label".
Does anyone know where is the problem? Thank you in advance.
$(function(){
$('button').click(function(){
var typeButton = $(this).text();
if(typeButton=='Label'){
$('hr').remove();
$('#formule').remove();
$('#droite').append('<hr>');
var elementLabel = 'Texte du label';
var elementTexte = '<input type="text" name="label"/>';
var elementButton = '<button>OK</button>';
var elementSpan = elementLabel+' '+elementTexte+' '+elementButton;
var elementDiv = '<div id="formule">'+elementSpan+'</div>'
$(elementDiv).insertAfter('hr');
};
if(typeButton=='OK'){
$('hr').remove();
var elementNom = $('input[name=label]').val();
var elementSpan = '<span>'+elementNom+'</span>';
$('#formule').remove();
$('#gauche').append('elementSpan');
};
});
});
body {
margin: 0;
}
#gauche {
float: left;
width: 70%;
height: 1000px;
background-color: #EFECCA;
}
#droite {
background-color: #CEFFF8;
height: 1000px;
padding : 10px;
padding-left: 71%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div id="gauche">
</div>
<div id="droite">
Utilisez ces boutons pour créer votre formulaire<br><br>
<button>Label</button>
<button>Zone de texte</button>
<button>Bouton</button>
</div>
you need to delegate dynamically added elements using on event handler attachment with the document.
$(document).on('click', 'button', function () {
var typeButton = $(this).text();
if (typeButton == 'Label') {
$('hr').remove();
$('#formule').remove();
$('#droite').append('<hr>');
var elementLabel = 'Texte du label';
var elementTexte = '<input type="text" name="label"/>';
var elementButton = '<button>OK</button>';
var elementSpan = elementLabel + ' ' + elementTexte + ' ' + elementButton;
var elementDiv = '<div id="formule">' + elementSpan + '</div>'
$(elementDiv).insertAfter('hr');
};
if (typeButton == 'OK') {
$('hr').remove();
var elementNom = $('input[name=label]').val();
var elementSpan = '<span>' + elementNom + '</span>';
$('#formule').remove();
$('#gauche').append(elementSpan);
};
});
It's because the button that gets generated to the DOM (OK) doesn't have an event listener attached to it, so it has nothing to do when being pressed. $('button').click() doesn't get updated any time the DOM changes, so you have to do it yourself.
$(function() {
function listenToButtons() {
$('button').off().on('click', function() {
var typeButton = $(this).text();
if (typeButton == 'Label') {
$('hr').remove();
$('#formule').remove();
$('#droite').append('<hr>');
var elementLabel = 'Texte du label';
var elementTexte = '<input type="text" name="label"/>';
var elementButton = '<button>OK</button>';
var elementSpan = elementLabel + ' ' + elementTexte + ' ' + elementButton;
var elementDiv = '<div id="formule">' + elementSpan + '</div>'
$(elementDiv).insertAfter('hr');
listenToButtons();
};
if (typeButton == 'OK') {
$('hr').remove();
var elementNom = $('input[name=label]').val();
var elementSpan = '<span>' + elementNom + '</span>';
$('#formule').remove();
$('#gauche').append('elementSpan');
};
});
}
listenToButtons();
});

Masonry sometimes lays out in one column straight line

I have masonry initialized on some "tiles" that include an image. Most of the time I am not having issues but sometimes the tiles lay out in one column when there should be 3 columns. Do you have any idea what the issue might be?
On ready initialization:
$(document).ready(function() {
var $container = $('#news');
$container.masonry({
itemSelector: '.pageNewsItem',
transitionDuration: 0
});
$container.masonry( 'on', 'layoutComplete', function( msnryInstance, laidOutItems ) {debounced = true;} )
});
Dynamically append tiles:
var count = 0;
function placeNewsTiles(news){ //places news tiles
var length = (news.data.length > 20) ? 20 : news.data.length;
var elems ="";
for(var i = 0; i < length; i++){
elems += '<div class="pageNewsItem inactive" id="'+ count + i + '">\
<div class="outerTextWrap">\
<div class="textWrap">\
<a href="' + news.data[i]._url + '">\
<strong>' + news.data[i]._title + '</strong>\
</a>\
<span class="source">' + news.data[i]._source + '</span>\
</div>\
</div>\
<div class="imageWrap"></div>\
<div class="thumbsOverlay" style="display:none">\
<div class="thumbs">\
<div>\
\
\
</div>\
</div>\
<div class="title">\
<div>\
<a href="' + news.data[i]._url + '">\
<div class="theTitle">Read Article</div>\
</a>\
</div>\
</div>\
</div>\
</div>';
getTileImage({total: news.count, i:count + "" + i, url:news.data[i]._url});
}
elems = $(elems);
$('#news').append(elems).imagesLoaded(function(){
//for(var i = 0; i < length; i++) $('.pageNewsItem').removeClass('inactive'); //$('.pageNewsItem').show(1000);
$('#news').masonry( 'appended', elems);
});
newsPage = 0;
count++;
hoverTiles();
}
getTileImage function is called to conduct an ajax call to obtain the tile image. Masonry layout happens on complete:
var cnt = 0;
function getTileImage(args){
var _t = localStorage.getItem("token"),
url = args.url,
i = args.i;
$.ajax({
type: "GET",
url: apiHost+'/api/tileImg?url=' + url + '&token='+_t,
dataType: "json",
success: function(data) {
var img = (data && data.image.src) ? data.img.src : (data && data.image) ? data.image: "";
if(img.indexOf("spacer") > -1|| img.indexOf("blank") > -1 || img === ""){ $('.pageNewsItem#' + i).hide(); }
else $('.pageNewsItem#' + i).find('.imageWrap').append('<img src="' + img + '" />');
},
error: function(e) {
if (e.status == 404) {
//need to get a new token
getToken(getTileImage, url);
}
}, complete: function(){
cnt++;
if ((cnt ==20) || cnt == args.total) {
var $container = $('#news');
$container.imagesLoaded( function() {
$container.masonry( 'layout' );
$('.pageNewsItem').removeClass('inactive');
//$('.pageNewsItem').show();
});
cnt = 0;
}
/*$('#news').imagesLoaded( function() {
$('.pageNewsItem#' + i + ' .thumbs').height($('.pageNewsItem#' + i).outerHeight() - $('.pageNewsItem#' + i + ' .title').height() - 5);
//$('.pageNewsItem').show();
});*/
}
});//end ajax call
}
CSS:
.pageNewsItem {
width: 33.333%;
padding: 10px;
min-height: 150px;
opacity: 1;
transition: opacity 1s ease;
}
#news {
margin-right: 20px;
margin-top: 25px;
}
Try using the console and manually initialize masonry:
$('#news').masonry();
If it is not working, masonry might be already initialized and therefore it's not repositioning the elements. In that case you have to remove masonry from the div and reinitialize it:
$('#news').masonry('destroy');
$('#news').masonry();

what is cause not work right my autocomplete and slow speed it?

this autocomplete not work right.
this worked for class search_hotel but not worked for class guide_search. not have problem code php result it is true but js not true
why of its slow operating speed (slow speed)?
what do i do?
js:
$('.auto_complete').keyup(function () {
var specific = '.' + $(this).closest('div.auto_box').find('b').attr('class');
var id = '#' + this.id;
var url = $(id).attr('alt')+ $(id).attr('id') + '/' + $(id).attr('class');
var dataObj = $(this).closest('form').serialize();
$.ajax({
type: "POST",
url: url,
data: dataObj,
cache: false,
dataType: 'json',
success: function (data) {
var cl_list = '.' + $('.auto_box '+ specific +' ul').attr('class');
$(cl_list).show().html('');
if(data==0){
//alert('nist')
$(cl_list).show().html('<li><b>وجود ندارد<b></li>').css('color','red');
}else{
$.each(data, function(a,b){
$(cl_list).append('<li>' + b.name + '</li>');
});
$(cl_list + ' li a').click( function(e) {
e.preventDefault();
var ac = $(this).attr('id');
$('<b>' + ac + '، <input type="text" name="hotel[]" value="' + ac + '" style="border: none; display: none;" /></b>').appendTo($('.auto_box' + add + ' span'));
$(this).remove();
return false;
});
$('.auto_box span b').live('click', function(e) {
e.preventDefault();
$(this).remove();
return false;
});
}
if($('.auto_complete').val()==''){
$(cl_list + " li").hide().remove();
$(".list_name").show().html('');
}
$('body').click(function(){
$(cl_list + " li").hide().remove();
$('.auto_complete').val('');
$(cl_list).show().html('');
});
},
"error": function (x, y, z) {
// callback to run if an error occurs
alert("An error has occured:\n" + x + "\n" + y + "\n" + z);
}
});
});
html:
<div class="auto_box">
<b class="search_hotel">
<span></span>
<div class="mediumCell"><input type="text" style="border: none; float: right;" alt="<?= base_url();?>admin/" id="tour" class="auto_complete" name="search_hotel" placeholder="هتل" title="هتل" /></div>
<ul class="list_autobox_hotel"></ul>
</b>
</div>
<div class="auto_box">
<b class="guide_search">
<span></span>
<div class="mediumCell"><input type="text" style="border: none; float: right;" alt="<?= base_url();?>admin/" id="tour" class="auto_complete" name="guide_search" placeholder="راهنما" title="ارلاین"></div>
<ul class="list_autobox_guide"></ul>
</b>
</div>

Categories

Resources