When I edit panels name I want to update div content, that will have tab-pane name.
I tried to get the value and change it "onchange", but
I think I did something incorrectly.
http://jsfiddle.net/agata666/5zLmtqby/139/
var $foo = $(".tab-pane");
var $newPanelDefault = $foo.clone();
var hash = 1;
$(".add").on("click", function() {
var $newPanel = $newPanelDefault.clone();
var hashClass = 'zone-panel-' + generateHash();
$newPanel.find(".panel").data('hash', hashClass).attr("href", "#" + (++hash)).text("Zone " + hash);
$newPanel.attr("id", "tab" + hashClass);
var nextTab = $('.tabs li').size()+1;
$('<li class="' + hashClass + '">Zone ' + hash + ' <i class="fas fa-pencil-alt pencil"></i></li>').appendTo('.tabs');
$($newPanel).appendTo('.tab-content');
$(".pencil").click(function() {
$(".nav-tabs li.active").attr('contenteditable',$(".nav-tabs li.active").attr('contenteditable')==='true'?'false':'true' );
});
});
var panelDefault = document.querySelectorAll('.panel-default');
var exTabFirst = document.querySelectorAll('.exTabFirst');
var exTabSecond = document.querySelectorAll('.exTabSecond');
var addZoneButton = document.getElementById('add');
function generateHash() {
return Math.random().toString(16).substr(-5);
}
addZoneButton.addEventListener('click', function () {
var randomNumber = generateHash();
panelDefault.innerHTML = 'panel panel-default foo template ' + randomNumber;
exTabFirst.innerHTML = 'exTabFirst ' + randomNumber;
exTabSecond.innerHTML = 'exTabSecond ' + randomNumber;
});
$(".pencil").click(function() {
$(".nav-tabs li.active").attr('contenteditable',$(".nav-tabs li.active").attr('contenteditable')==='true'?'false':'true' );
});
Could you help me?
Related
i'm still learning ajax,jquery and js here.. So in this problem i want to get the json data and display each of it into div id="card-body" dynamically one by one per ID, but it seems my code doesn't work because the result only show one div that have all the data inside of it. Are there any suggestion that can be added or changed within the code here?
<div class="container">
<div class="card">
<div class="card-header">
</div>
<div class="addDiv">
<div id="card-body">
</div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
$(function () {
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts",
success: function (result) {
$.each(result, function (index, item) {
var userId = item.userId;
var typeId = item.id;
var titleId = item.title;
var bodyId = item.body;
var $info = $("<p/>").html("user id: " + userId + "<br>"
+ "id: " + typeId + "<br>"
+ "title: " + titleId + "<br>"
+ "body: " + bodyId);
var html = '<div id="card-body>';
for (let i = 0; i < $(result).length; i++) {
const element = $(result)[i];
}
html += '</div>';
$(".addDiv").append(html);
$("div#card-body").append($info);
});
// console.log('success', result);
// console.log(result[0].body);
// console.log($(result).length);
}
});
});
</script>
for (let i = 0; i < $(result).length; i++) {
const element = $(result)[i];
}
what is here going to do?
or you mean this? --- Updated
$(function() {
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts",
success: function(result) {
var container = $("div#list");
$.each(result, function (index, item) {
var userId = item.userId;
var id = "card-body-" + userId;
var el = $('div#' + id)
console.log(el)
var typeId = item.id;
var titleId = item.title;
var bodyId = item.body;
var $info = $('<div>').html(
"user id: " + userId + "<br>" +
"id: " + typeId + "<br>" +
"title: " + titleId + "<br>" +
"body: " + bodyId
);
if (!el.length) {
// not found, create new one
el = $('<div id="' + id + '">')
container.append(el)
}
el.append($info)
});
}
});
});
I am trying to create my own small Twitter.
It is all working fine but I cannot find a way to delete specific tweet on click of a button. I have tried splice() but it deletes the first object of an array always.
Here is my code:
var tweets = []
function postNewTweet() {
var today = new Date();
var date = today.getDate() + '-' + (today.getMonth() + 1) + '-' + today.getFullYear();
var time = today.getHours() + ':' + today.getMinutes();
var id = tweets.length + 1;
var li = document.createElement('li');
var inputValue = document.getElementById('newTweet').value;
var finalValue = id + ' ' + inputValue + ' ' + date + ' ' + time;
var t = document.createTextNode(finalValue);
li.appendChild(t);
tweets.push({
id: id,
content: inputValue,
date: date + ' ' + time
});
document.getElementById('list').appendChild(li);
document.getElementById('newTweet').value = "";
console.log(tweets);
var buttonDelete = document.createElement("button");
buttonDelete.innerHTML = '<i class="far fa-trash-alt"></i>';
buttonDelete.onclick = deleteItem;
function deleteItem(e) {
var ul = document.getElementById('list');
ul.removeChild(li);
var list = document.getElementById('list');
list.addEventListener('click', function(e) {
var index = e.target.getAttribute('value');
tweets.splice(index, 1);
console.log(tweets)
});
}
li.appendChild(buttonDelete);
}
<div id='post'>
<textarea maxlength="160" id='newTweet'></textarea>
<button id='postIt' onclick="postNewTweet()">Post</button>
</div>
<ul id='list'>
</ul>
So it deletes it in HTML, but not in array correctly.
The second part of your deleteItem function's body seems useless. While there are couple of ways to resolve it, I suggest the following:
function deleteItem(e) {
var ul = document.getElementById('list');
ul.removeChild(li);
var foundIndex = tweets.findIndex(function (tweet) {
return tweet.id == id;
});
if (foundIndex > -1) {
tweets.splice(foundIndex, 1);
}
}
There are two issues:
If you just take the length of the array as the id you will get duplicate entries, if you delete an entry. Perhaps go to a timestamp - i just used the one you already had there but added seconds
You retrieve the value-attribute but for splice you need the index of the element. I just added the timestampt as an attribute to the button and used it for removal.
Probably not my best code but I hope it gives you the right hints.
var tweets = []
function postNewTweet() {
var today = new Date();
var date = today.getDate() + '-' + (today.getMonth() + 1) + '-' + today.getFullYear();
var time = today.getHours() + ':' + today.getMinutes() + ':' + today.getSeconds();
var id = tweets.length + 1;
var li = document.createElement('li');
var inputValue = document.getElementById('newTweet').value;
var finalValue = id + ' ' + inputValue + ' ' + date + ' ' + time;
var t = document.createTextNode(finalValue);
li.appendChild(t);
tweets.push({
id: id,
content: inputValue,
date: date + ' ' + time
});
document.getElementById('list').appendChild(li);
document.getElementById('newTweet').value = "";
console.log(tweets);
var buttonDelete = document.createElement("button");
buttonDelete.innerHTML = '<i class="far fa-trash-alt" del-date="'+date + ' ' + time +'">del</i>';
buttonDelete.onclick = deleteItem;
function deleteItem(e) {
var ul = document.getElementById('list');
ul.removeChild(li);
var list = document.getElementById('list');
list.addEventListener('click', function(e) {
var delDate = e.target.getAttribute('del-date');
let index = tweets.map((item) => item.date).indexOf(delDate);
console.log(index);
tweets.splice(index, 1);
console.log(tweets)
});
}
li.appendChild(buttonDelete);
}
<div id='post'>
<textarea maxlength="160" id='newTweet'></textarea>
<button id='postIt' onclick="postNewTweet()">Post</button>
</div>
<ul id='list'>
</ul>
As you have access to li in your delete function, you have access to all the other data too. You can use them to find out the element to remove from the tweets array.
For example, in your current code, you can use the id:
tweets.splice(id - 1, 1)
Or you can use filter with any of the data that you store in tweets.And I don't see any use for this part:
var list = document.getElementById('list');
list.addEventListener('click', function(e) {
var index = e.target.getAttribute('value');
tweets.splice(index, 1);
console.log(tweets)
});
You can just remove the tweet under the ul.removeChild
Im trying to change the cursor logo when Im building a dynamic div. Depending on how much data it can take up a few seconds to load so I need the cursor change.
The problem Im having is that the cursor isnt changing until my code has fully executed.
Im have a dynamically generated chart with the points in the chart set to popup more data when they are clicked. This is the eventListener Ive created and it works fine apart from my CSS update not getting applied until it has exited the function.
Any idea how I can force it to update immediately
point.addEventListener('click', function (evt) {
document.body.className = 'waiting';
var evtPoint = document.getElementById(evt.currentTarget.id);
var index = evtPoint.id.substring(evtPoint.id.lastIndexOf('-') + 1, evtPoint.id.length);
var chartOptions = Charts.options[elementId];
var txnData = chartOptions.data.txn[index];
var txnFullData = chartOptions.data.txnFull;
var theDate = new Date(txnData.time);
// pop up
var txnsPerMinutePopUp = document.getElementById('txnsPerMinutePopUp');
txnsPerMinutePopUp.innerHTML = '<div id = "txnsPerMinutePopUp-bg"></div>' +
'<div id = "txnsPerMinutePopUp-body">' +
'<div id = "txnsPerMinutePopUp-body-heading"></div>' +
'<div id = "txnsPerMinutePopUp-body-txns">';
var txnsPerMinutePopUpHeading = document.getElementById('txnsPerMinutePopUp-body-heading');
var txnsPerMinutePopUpBody = document.getElementById('txnsPerMinutePopUp-body-txns');
function addZero(i) {
if (i < 10) {
i = '0' + i;
}
return i;
}
for (var i = 0; i < txnFullData.length; i++) {
// console.log("loop" + i, txnFullData);
var date = new Date(txnFullData[i].time);
if (date.getTime() === theDate.getTime()) {
txnsPerMinutePopUpHeading.innerHTML = '<div class="txnsPerMinutePopUp-body-heading-title">Tweets</div><div class="txnsPerMinutePopUp-body-heading-time">' + addZero(theDate.getHours()) + ':' + addZero(theDate.getMinutes()) + '</div>';
var child = '<div class = "txnsPerMinutePopUp-txns">' +
'<div class = "txnsPerMinutePopUp-txns-img">' +
'<object data = "' + txnFullData[i].profile_image_url + '" class = "border-rad-25 cross-series-profile-img" width = "50px" height = "50px" type = "image/jpeg">' +
'<img src = "assets/img/engager_profile_default-47.svg" class = "border-rad-25 cross-series-profile-img" width = "50px" height = "50px" alt = "' + txnFullData[i].screen_name + ' profile image" />' +
'</object>' +
'</div>' +
'<div class = "txnsPerMinutePopUp-txns-screen-name">' +
'#' + txnFullData[i].screen_name + '' +
'</div>' +
'<div class = "txnsPerMinutePopUp-txns-text">' + Charts.lineChart.parseText(txnFullData[i].text) + '</div>' +
'</div>';
txnsPerMinutePopUpBody.innerHTML += child;
}
}
txnsPerMinutePopUp.innerHTML += '</div>' +
'</div>';
//document.body.style.cursor='default';
txnsPerMinutePopUp.style.visibility = 'visible';
var bg = document.getElementById('txnsPerMinutePopUp-bg');
bg.addEventListener('click', function (evt) {
txnsPerMinutePopUp.style.visibility = 'hidden';
});
}, false);
My CSS then is just
body.waiting * { cursor: wait; }
UPDATE
From researching potential causes I found out that most browsers wont update the DOM immediately and I need to interrupt the javascript to allow for the DOM to get updated.
Ive updated my code to move the bulk of the operations out to a separate function and tried to set a timeout value on it and its still not updating the cursor until everything completes.
I also tried to add a mousedown event to try and get ahead of the javascript in the on click but it didnt work either
EventListener
point.addEventListener('click', function (evt) {
//document.body.className = 'waiting';
// setTimeout(function() {
Charts.lineChart.changeCursor();
// },10);
var evtPoint = document.getElementById(evt.currentTarget.id);
var index = evtPoint.id.substring(evtPoint.id.lastIndexOf('-') + 1, evtPoint.id.length);
var chartOptions = Charts.options[elementId];
var txnData = chartOptions.data.txn[index];
var txnFullData = chartOptions.data.txnFull;
var theDate = new Date(txnData.time);
function addZero(i) {
if (i < 10) {
i = '0' + i;
}
return i;
}
setTimeout(function() {
Charts.lineChart.breakOut( txnFullData,theDate );
},100);
document.body.style.cursor='default';
txnsPerMinuteTweetsPopUp.style.visibility = 'visible';
}, false);
and the following code was moved into the breakout function
breakOut
Charts.lineChart.breakOut = function(txnFullData,theDate){
function addZero(i) {
if (i < 10) {
i = '0' + i;
}
return i;
}
var txnsPerMinutePopUp = document.getElementById('txnsPerMinutePopUp');
txnsPerMinutePopUp.innerHTML = '<div id = "txnsPerMinutePopUp-bg"></div>' +
'<div id = "txnsPerMinutePopUp-body">' +
'<div id = "txnsPerMinutePopUp-body-heading"></div>' +
'<div id = "txnsPerMinutePopUp-body-txns">';
var txnsPerMinutePopUpHeading = document.getElementById('txnsPerMinutePopUp-body-heading');
var txnsPerMinutePopUpBody = document.getElementById('txnsPerMinutePopUp-body-txns');
for (var i = 0; i < txnFullData.length; i++) {
// console.log("loop" + i, txnFullData);
var date = new Date(txnFullData[i].time);
if (date.getTime() === theDate.getTime()) {
txnsPerMinutePopUpHeading.innerHTML = '<div class="txnsPerMinutePopUp-body-heading-title">Tweets</div><div class="txnsPerMinutePopUp-body-heading-time">' + addZero(theDate.getHours()) + ':' + addZero(theDate.getMinutes()) + '</div>';
var child = '<div class = "txnsPerMinutePopUp-txns">' +
'<div class = "txnsPerMinutePopUp-txns-img">' +
'<object data = "' + txnFullData[i].profile_image_url + '" class = "border-rad-25 cross-series-profile-img" width = "50px" height = "50px" type = "image/jpeg">' +
'<img src = "assets/img/engager_profile_default-47.svg" class = "border-rad-25 cross-series-profile-img" width = "50px" height = "50px" alt = "' + txnFullData[i].screen_name + ' profile image" />' +
'</object>' +
'</div>' +
'<div class = "txnsPerMinutePopUp-txns-screen-name">' +
'#' + txnFullData[i].screen_name + '' +
'</div>' +
'<div class = "txnsPerMinutePopUp-txns-text">' + Charts.lineChart.parseText(txnFullData[i].text) + '</div>' +
'</div>';
txnsPerMinutePopUpBody.innerHTML += child;
}
}
txnsPerMinutePopUp.innerHTML += '</div>' +
'</div>';
var bg = document.getElementById('txnsPerMinutePopUp-bg');
bg.addEventListener('click', function (evt) {
txnsPerMinutePopUp.style.visibility = 'hidden';
});
}
In default.aspx page, there is a user control side_menu.ascx.
This is part of the code in side_menu.ascx
<script src="../library/scripts/side_menu.js" type="text/javascript"></script>
<script src="../library/scripts/side_menu_items.js" type="text/jscript"></script>
<script src="../library/scripts/side_menu_tpl.js" type="text/jscript"></script>
<script language="JavaScript" type="text/javascript">
<!--
new menu(SIDE_MENU_ITEMS, SIDE_MENU_POS, SIDE_MENU_STYLES);
// -->
</script>
The function menu is defined in side_menu.js. SIDE_MENU_ITEMS is an array containing all the menu items and the path.
var SIDE_MENU_ITEMS =[
["Administration", null,
["Report a Bug", "administration/bugs/report_bug.aspx"], // /TOrders/
["Bug Tracker", "administration/bugs/bug_tracker.aspx?fmtid=bugs"], // /TOrders/
["Feature Request", "administration/features/request_feature.aspx"], // /TOrders/
["Feature Tracker", "administration/features/feature_tracker.aspx"] // /TOrders/
]
When a menu item is clicked it, it loads the page /localhost/administration/bugs/whateverpage.aspx. This works fine. However, when a menu item is clicked the second time the path becomes /localhost/administration/bugs/administration/bugs/whateverpage.aspx. THE PATH is getting appended. I just cant figure out where to go and clear the array. When I click on the the menu item, the menu_onnclick() is called and this.item[id] is already populated with the wrong path. Not sure where to clear it.
Here are some of the function in side_menu.js
function menu (item_struct, pos, styles) {
this.item_struct = item_struct;
this.pos = pos;
this.styles = styles;
this.id = menus.length;
this.items = [];
this.children = [];
this.add_item = menu_add_item;
this.hide = menu_hide;
this.onclick = menu_onclick;
this.onmouseout = menu_onmouseout;
this.onmouseover = menu_onmouseover;
this.onmousedown = menu_onmousedown;
var i;
for (i = 0; i < this.item_struct.length; i++)
new menu_item(i, this, this);
for (i = 0; i < this.children.length; i++)
this.children[i].visibility(true);
menus[this.id] = this;
}
function menu_add_item (item) {
var id = this.items.length;
this.items[id] = item;
return (id);
}
function menu_onclick (id) {
var item = this.items[id];
return (item.fields[1] ? true : false);
}
function menu_item (path, parent, container) {
this.path = new String (path);
this.parent = parent;
this.container = container;
this.arrpath = this.path.split('_');
this.depth = this.arrpath.length - 1;
// get pointer to item's data in the structure
var struct_path = '', i;
for (i = 0; i <= this.depth; i++)
struct_path += '[' + (Number(this.arrpath[i]) + (i ? 2 : 0)) + ']';
eval('this.fields = this.container.item_struct' + struct_path);
if (!this.fields) return;
// assign methods
this.get_x = mitem_get_x;
this.get_y = mitem_get_y;
// these methods may be different for different browsers (i.e. non DOM compatible)
this.init = mitem_init;
this.visibility = mitem_visibility;
this.switch_style = mitem_switch_style;
// register in the collections
this.id = this.container.add_item(this);
parent.children[parent.children.length] = this;
// init recursively
this.init();
this.children = [];
var child_count = this.fields.length - 2;
for (i = 0; i < child_count; i++)
new menu_item (this.path + '_' + i, this, this.container);
this.switch_style('onmouseout');
}
function mitem_init() {
document.write (
'<a id="mi_' + this.container.id + '_'
+ this.id +'" class="m' + this.container.id + 'l' + this.depth
+'o" href="' + this.fields[1] + '" style="position: absolute; top: '
+ this.get_y() + 'px; left: ' + this.get_x() + 'px; width: '
+ this.container.pos['width'][this.depth] + 'px; height: '
+ this.container.pos['height'][this.depth] + 'px; visibility: hidden;'
+' background: black; color: white; z-index: ' + (this.depth + 10000) + ';" ' // changed this.depth to (this.depth + 10000)
+ 'onclick="return menus[' + this.container.id + '].onclick('
+ this.id + ');" onmouseout="menus[' + this.container.id + '].onmouseout('
+ this.id + ');window.status=\'\';return true;" onmouseover="menus['
+ this.container.id + '].onmouseover(' + this.id + ');window.status=\''
+ this.fields[0] + '\';return true;"onmousedown="menus[' + this.container.id
+ '].onmousedown(' + this.id + ');"><div class="m' + this.container.id + 'l'
+ this.depth + 'i">' + this.fields[0] + "</div></a>\n"
);
this.element = document.getElementById('mi_' + this.container.id + '_' + this.id);
}
Change your array to:
var url="http://"+window.location.hostname;
var SIDE_MENU_ITEMS =[
["Administration", null,
["Report a Bug", url+"/administration/bugs/report_bug.aspx"], // /TOrders/
["Bug Tracker", url+"/administration/bugs/bug_tracker.aspx?fmtid=bugs"], // /TOrders/
["Feature Request", url+"/administration/features/request_feature.aspx"], // /TOrders/
["Feature Tracker", url+"/administration/features/feature_tracker.aspx"] // /TOrders/
]
];
Or (The more general way for support the urls with port numbers such as http://localhost:51143/):
function getUrl(){
url = window.location.href.split('/');
return url[0]+'//'+url[2];
}
var SIDE_MENU_ITEMS =[
["Administration", null,
["Report a Bug", getUrl()+"/administration/bugs/report_bug.aspx"], // /TOrders/
["Bug Tracker", getUrl()+"/administration/bugs/bug_tracker.aspx?fmtid=bugs"], // /TOrders/
["Feature Request", getUrl()+"/administration/features/request_feature.aspx"], // /TOrders/
["Feature Tracker", getUrl()+"/administration/features/feature_tracker.aspx"] // /TOrders/
]
];
I have this function which returns some XML datas from a foreign website :
function sendData()
{
var dev_statut = jQuery("select[name='statut']").val();
var dev_fdpaysid = jQuery("select[name='pays']").val();
var dev_fddeffet = jQuery("input[name='date_effet']").val();
var dev_fdnbadu = jQuery('select[name="nb_adultes"]').val();
var dev_fdnbenf = jQuery('select[name="nb_enfants"]').val();
var date_naiss_a_val = jQuery("input[name^=date_naissance_a]").map(function() {
var dev_date_naiss_a = 'dev_fadnaiss_';
return dev_date_naiss_a + this.id + '=' + this.value;
}).get().join('&');
var date_naiss_e_val = jQuery("input[name^=date_naissance_e]").map(function() {
var dev_date_naiss_e = 'dev_fadnaiss_';
return dev_date_naiss_e + this.id + '=' + this.value;
}).get().join('&');
var xdr = getXDomainRequest();
xdr.onload = function()
{
alert(xdr.responseXML);
var xml = xdr.responseXML;
var prod = xml.documentElement.getElementsByTagName("produit");
var proddata = [];
proddata.push('<ul>');
var len = prod.length;
for (var i = 0; i < len; i++) {
var nomprod = xml.getElementsByTagName('nomprod')[i].firstChild.nodeValue;
var url = xml.getElementsByTagName('url')[i].firstChild.nodeValue;
var desc = xml.getElementsByTagName('desc')[i].firstChild.nodeValue;
var texte = xml.getElementsByTagName('texte')[i].firstChild.nodeValue;
proddata.push("<li><div class='resultat_produit'>" + "<h1>" + nomprod + "</h1>" + "<p class='from_devis_desc'>" + desc + "</p>" + "<p class='form_devis_texte'>" + texte + "</p>" + "<a href='" + url + "'class='btn_url'>Faire un devis</a>" + "</div></li>");
}
proddata.push('</ul>');
jQuery('#mydiv2').append(proddata.join("\n"));
jQuery('.resultat_produit a').click(function(e)
{
e.preventDefault();
var href = jQuery(this).attr('href');
jQuery('#myDiv').empty();
jQuery('#myDiv').append('<iframe src="'+ href +'" scrolling="auto" width="960" height="100%"></iframe>');
});
}
xdr.open("GET", "http://www.MYURL.fr/page.php?dev_statut="+ dev_statut +"&dev_fdpaysid="+ dev_fdpaysid +"&dev_fddeffet="+ dev_fddeffet +"&dev_fdnbadu="+ dev_fdnbadu +"&dev_fdnbenf="+ dev_fdnbenf +"&"+ date_naiss_a_val +"&"+ date_naiss_e_val +"");
xdr.send();
}
It works fine on any major browsers (Chrome, FF, etc) but not on ... IE ! I've opened the console and it says : "DocumentElement is undefined ..."
I'm tired and can't fix that, any help will be very very appreciated !!