Bootstrap tab menu switch do not change variable - javascript

Hi I use Bootstrap tab menu and ShinDarth's Nestable++ menu editor
My problem live demo
$("a[data-toggle='tab']").on("shown.bs.tab", function(e) {
var hedef = $(e.target).attr("href");
alert(hedef);
if (hedef == "#footmenu") {
var nestabad = "#nestable2";
var menutip = "alt";
var nestableList = $("#nestable2 > .dd-list");
} else if (hedef == "#headmenu") {
var nestabad = "#nestable";
var menutip = "ust";
var nestableList = $("#nestable > .dd-list");
}
});
var deleteFromMenu = function () {
var targetId = $(this).data('owner-'+menutip+'-id');
alert(JSON.stringify($(this).data()));
var target = $('[data-'+menutip+'-id="' + targetId + '"]');
alert(JSON.stringify(target));
var result = confirm("Delete " + target.data('name') + " and all its subitems ?");
if (!result) {
return;
}
// Remove children (if any)
target.find("li").each(function () {
deleteFromMenuHelper($(this));
});
// Remove parent
deleteFromMenuHelper(target);
target.data();
// update JSON
updateOutput($('#nestable2').data('output', $('#json-output2')));
updateOutput($('#nestable').data('output', $('#json-output')));
};
always tabs menu change menutip variable defined.
I delete menu link before switch menu page menutip defined.
TWO confirm(1.undefined variable,2.defined variable) after menu link deleted
Help me!

Related

How to remove last <li> child together with it's local storage?

I'm doing a to do list and I want to add, remove and clear tasks together with their local storage. Add and clear work but I failed to make remove work.
I tried using element.lastChild but removing it didn't work.
var last = document.getElementById("list").lastChild.innerHTML;
Here is my code
var remove = function(){
var listItems = document.getElementById("list").getElementsByTagName("li");
var last = listItems[listItems.length - 1];
last.parentNode.removeChild(last);
removeStore(last);
}
// localStorage
function store() {
window.localStorage.myToDoList = list.innerHTML;
}
function clearStore() {
localStorage.clear();
}
function removeStore(item) {
localStorage.removeItem(item);
}
Remove works only for removing tasks but I'm getting an error after the first clicking on remove button
"TypeError: last.parentNode is null"
and after the last one:
TypeError: document.getElementById(...).lastChild is null
https://codepen.io/aggat/pen/PrQRYj
You can replace your javascript part of the code with my part. The changed part is commented in capitals and explained with the purpose of change.
var add = function(){
var listItems = document.getElementById("list").getElementsByTagName("li");
var what = document.getElementById('what').value;
var li = document.createElement('li');
if (what.length > 0) {
li.appendChild(document.createTextNode(what));
list.appendChild(li);
store()
//document.getElementById('what').placeholder = "What do I have to do?";
} else {
li.appendChild(document.createTextNode("Task number " + (listItems.length + 1)));
list.appendChild(li);
store();
}
}
// I HAVE TO CHANGE THE LOGIC OF THIS FUNCTION COMPLETELY
// THIS FUNCTION TAKES VALUE FROM LOCAL STORAGE, CHECKS FOR EXISISTENCE OF
// LAST li ELEMENT HTML AND IF FIND IT, THEN REMOVE IT FROM LOCAL STORAGE VALUE
// AND SET NEW VALUE BACK IN LOCAL STORAGE
function rem() {
//var a = document.getElementById("list").lastChild.innerHTML;
//localStorage.last = a;
var aValue = localStorage.getItem("myToDoList");
console.log(aValue);
var listItems = document.getElementById("list").getElementsByTagName("li");
console.log(listItems);
if (listItems.length > 0) {
var last = listItems[listItems.length - 1];
if (last) {
var lastHtml = last.outerHTML;
console.log(lastHtml);
var indexAtWhichLastElementPresent = aValue.indexOf(lastHtml);
if (indexAtWhichLastElementPresent > -1) {
// Removes the lastElementHtml part from local storage value
aValue = aValue.substring(0, indexAtWhichLastElementPresent) + aValue.substring(indexAtWhichLastElementPresent + lastHtml.length);
}
}
}
localStorage.setItem("myToDoList", aValue);
}
var remove = function(){
var listItems = document.getElementById("list").getElementsByTagName("li");
console.log(listItems);
var last = listItems[listItems.length - 1];
rem(); // CHANGED THE CALLING ORDER. FIRST REMOVE DATA FROM LOCAL STORAGE AND THEN ELEMENT WILL BE REMOVED
last.parentNode.removeChild(last);
// TAKE OUT THE REMOVE FUNCTION FROM INSIDE OF THIS FUNCTION SO THAT IT CAN
// BE USED BY SOME OTHER FUNCTION IN FUTURE
if (listItems.length === 0){
alert();
}
}
var clearAll = function(){
var myNode = document.getElementById("list");
while (myNode.firstChild) {
myNode.removeChild(myNode.firstChild);
clearStore();
}
alert();
}
// localStorage
function store() {
window.localStorage.myToDoList = list.innerHTML;
}
function clearStore() {
localStorage.clear();
}
/*function removeStore(item) {
localStorage.removeItem(item);
}*/
function getValues() {
var storedValues = window.localStorage.myToDoList;
if(!storedValues) {
list.innerHTML = '';
}
else {
list.innerHTML = storedValues;
}
}
getValues();
//modal box
var modal = document.getElementById("myModal");
//button that opens the modal
var btn = document.getElementById("myBtn");
//<span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
//open the modal
function alert() {
modal.style.display = "block";
}
//clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
//clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
Please comment if in case you face any problem in implementing this solution.
Your last is available only if you have entries in your todo list. Initially, and after clearing all items from your todo list, last in your remove() function will be undefined as your list is empty.
To avoid this error, conditionally check for the presence of entries in your todo list.
var remove = function(){
var listItems = document.getElementById("list").getElementsByTagName("li");
var last = listItems[listItems.length - 1];
if (last) {
last.parentNode.removeChild(last);
}
... rest of your code
}
And after removing item from your list, set your localstorage with current elements of your list. This will update your localstorage with currrent items in the list.
if (last) {
last.parentNode.removeChild(last);
window.localStorage.myToDoList = document.getElementById("list").innerHTML; // or call your store(); function
}
Hope this is helpful :)

Remove items from a list if they exist and repopulate the list

I have some code that builds elements of a list on a sidebar. If a button is clicked I want to clear the list and repopulate it with new results. Right now the information just adds to the list. I would like to clear all of the items in the list so I can readd them.
function buildLocationList(data) {
for (i = 0; i < data.locations.length; i++) {
var currentFeature = data.locations[i];
var prop = currentFeature.locations;
var listings = document.getElementById('listings');
var listing = listings.appendChild(document.createElement('div'));
listing.className = 'item';
listing.id = "listing-" + i;
var link = listing.appendChild(document.createElement('a'));
link.href = '#';
link.className = 'title';
link.dataPosition = i;
link.innerHTML = '<b>' + currentFeature.company; + '</b>'
var address = listing.appendChild(document.createElement('div'));
address.innerHTML = currentFeature.address;
var csz = listing.appendChild(document.createElement('div'));
csz.innerHTML = currentFeature.csz;
/*var hours = listing.appendChild(document.createElement('div'));
hours.innerHTML = currentFeature.hours[0].days + ': ' + currentFeature.hours[0].hours;
hours.style.color = 'gray'; */
link.addEventListener('click', function(e){
// Update the currentFeature to the store associated with the clicked link
var clickedListing = data.locations[this.dataPosition];
// 1. Fly to the point
flyToStore(clickedListing);
// 2. Close all other popups and display popup for clicked store
createPopUp(clickedListing);
// 3. Highlight listing in sidebar (and remove highlight for all other listings)
var activeItem = document.getElementsByClassName('active');
if (activeItem[0]) {
activeItem[0].classList.remove('active');
}
this.parentNode.classList.add('active');
});
}
}
For your particular case, add this before you do anything else:
document.getElementById('listings').innerHTML = "";

JQuery with several Elements issue

i got an anchor in the DOM and the following code replaces it with a fancy button. This works well but if i want more buttons it crashes. Can I do it without a for-loop?
$(document).ready(buttonize);
function buttonize(){
//alert(buttonAmount);
//Lookup for the classes
var button = $('a.makeabutton');
var buttonContent = button.text();
var buttonStyle = button.attr('class');
var link = button.attr('href');
var linkTarget = button.attr('target');
var toSearchFor = 'makeabutton';
var toReplaceWith = 'buttonize';
var searchButtonStyle = buttonStyle.search(toSearchFor);
if (searchButtonStyle != -1) {
//When class 'makeabutton' is found in string, build the new classname
newButtonStyle = buttonStyle.replace(toSearchFor, toReplaceWith);
button.replaceWith('<span class="'+newButtonStyle
+'"><span class="left"></span><span class="body">'
+buttonContent+'</span><span class="right"></span></span>');
$('.buttonize').click(function(e){
if (linkTarget == '_blank') {
window.open(link);
}
else window.location = link;
});
}
}
Use the each method because you are fetching a collection of elements (even if its just one)
var button = $('a.makeabutton');
button.each(function () {
var btn = $(this);
var buttonContent = btn.text();
var buttonStyle = btn.attr('class');
var link = btn.attr('href');
var linkTarget = btn.attr('target');
var toSearchFor = 'makeabutton';
var toReplaceWith = 'buttonize';
var searchButtonStyle = buttonStyle.search(toSearchFor);
...
};
the each method loops through all the elements that were retrieved, and you can use the this keyword to refer to the current element in the loop
var button = $('a.makeabutton');
This code returns a jQuery object which contains all the matching anchors. You need to loop through them using .each:
$(document).ready(buttonize);
function buttonize() {
//alert(buttonAmount);
//Lookup for the classes
var $buttons = $('a.makeabutton');
$buttons.each(function() {
var button = $(this);
var buttonContent = button.text();
var buttonStyle = button.attr('class');
var link = button.attr('href');
var linkTarget = button.attr('target');
var toSearchFor = 'makeabutton';
var toReplaceWith = 'buttonize';
var searchButtonStyle = buttonStyle.search(toSearchFor);
if (searchButtonStyle != -1) {
newButtonStyle = buttonStyle.replace(toSearchFor, toReplaceWith);
button.replaceWith('<span class="'
+ newButtonStyle
+ '"><span class="left"></span><span class="body">'
+ buttonContent
+ '</span><span class="right"></span></span>');
$('.buttonize').click(function(e) {
if (linkTarget == '_blank') {
window.open(link);
} else window.location = link;
}); // end click
} // end if
}); // end each
}

simple code to Show / Hide with cookie

Does anyone know a code as simple as possible to show / hide HTML.
With:
-Store the cookies option
-Effect to the Show / Hide
The jquery cookie plugin could simplify cookie management. As far as showing/hiding HTML is concerned you may take a look at the show() and hide() methods.
It really depends on the event/reason the content needs to show/hide...
Is it user specific content that must appear for a particular user, if so, how are you identifying the user (sessions, openID)?
Or is it event driven, ie, a user clicks on a button and content shows/hides and the cookie stores the show/hide state?
Damo
Probably more than you need, but I use this with the tablesorter plugin to collapse/expand sections of tables, store the state in the cookie and with .toggle() you can get a nice effect.
function tableContainer(id,visible,sortColumn,sortOrder){
this.ID = id;
this.Visible = visible;
this.SortColumn = sortColumn;
this.SortOrder = sortOrder;
}
function bindTableHeaders(element){
//Bind click handler to the table THs to update object as to current sort column.
$("thead th","#" + element).bind("click",function(){
var order = this.order
var column = this.column
var $table = $(this).closest("table")
var visible = $table.attr("expanded") //Technically I suppose if you can click these then it must be visible
var id = $table.attr("id")
var tableObj = new tableContainer(id,visible,column,order);
$.cookie(element, JSON.stringify(tableObj), { secure: true }); //Write the current state into the section cookie
});
};
function recoverState(element) {
// pull cookie for page state and visibility
var elementData = $.cookie(element);
if (elementData != null){
// parse JSON based on object representation
var json = JSON.parse(elementData)
var id = json.ID;
var visible = json.Visible;
var sortColumn = json.SortColumn == undefined ? 0 : json.SortColumn
var sortOrder = json.SortOrder == undefined ? 0 : json.SortOrder
} else {
var id = element;
var visible = "true"
var sortColumn = 0;
var sortOrder = 0;
}
// switch visibility
if(visible == "false"){
toggleElement(element)
}
// Determine if this section has any data (eg. a <tbody>)
if ($("tbody","#" + id).length == 0 || $("tbody","#" + id).html() == "")
return
if (pageAction == "Edit"){
$("#" + id).tablesorter({widgets: ['zebra'], sortList: [[sortColumn,sortOrder]]});
} else {
$("#" + id)
.collapsible("td.collapsible",{
collapse:true
})
.tablesorter({widgets: ['zebra'], sortMultiSortKey:'false', sortList: [[sortColumn,sortOrder]]});
}
}
function toggleElement(element) {
if ($("#" + element).attr("expanded") == "true"){
$("#" + element).attr("expanded","false")
$("#" + element).hide();
var isVisible = "false"
} else {
$("#" + element).attr("expanded","true")
$("#" + element).show();
var isVisible = "true"
}
//Rewrite the cookie for this section changing only the visibility
var elementData = $.cookie(element);
var visible = isVisible;
if (elementData != null){
var json = JSON.parse(elementData)
var id = json.ID;
var sortColumn = json.SortColumn;
var sortOrder = json.SortOrder;
} else {
var id = element
var sortColumn = 0;
var sortOrder = 0;
}
var tableObj = new tableContainer(id,visible,sortColumn,sortOrder);
$.cookie(element, JSON.stringify(tableObj), { secure: true }); //Write the current state into the section cookie
}

Trouble hiding/showing divs in using DOM/js/css

I am trying to make a debugger that will be dynamiaclly created with some variables. The names on the left div need to show a div for the corresponding variables Description,Variable ID, and initial Value as well as another div that will show history and lock status when variables are updated later. Where I am having trouble is properly adding the show/hide to the dom I think. Everything starts hidden and then when I click a name the Variables for that name show up but the next click doesn't hide the values from the former. Also any cleanup/optimization advice?
<script type="text/javascript">
var variableIDArray = {};
function loadVariables(variables) {
if (typeof variables != "object") { alert(variables); return; }
var namearea = document.getElementById('namearea');
var description = document.getElementById('description');
var varid = document.getElementById('varid');
var initialvalue = document.getElementById('initialvalue');
var valuelock = document.getElementById('valuelock');
for (var i = 0; i < variables.length - 1; i++) {
var nameDiv = document.createElement('div');
nameDiv.id = variables[i].variableID + "namearea";
nameDiv.className = "nameDiv";
nameDiv.onclick = (function (varid) {
return function () { showvariable(varid); };
})(variables[i].variableID);
nameDiv.appendChild(document.createTextNode(variables[i].name));
namearea.appendChild(nameDiv);
var descriptionDiv = document.createElement('div');
descriptionDiv.id = variables[i].variableID + "description";
descriptionDiv.className = "descriptionDiv";
descriptionDiv.appendChild(document.createTextNode("Description : " + variables[i].description));
description.appendChild(descriptionDiv);
var varidDiv = document.createElement('div');
varidDiv.id = variables[i].variableID + "varid";
varidDiv.className = "varidDiv";
varidDiv.appendChild(document.createTextNode("Var ID : " + variables[i].variableID));
varid.appendChild(varidDiv);
var initialvalueDiv = document.createElement('div'); ;
initialvalueDiv.id = variables[i].variableID + "initialvalue";
initialvalueDiv.className = "initialvalueDiv";
initialvalueDiv.appendChild(document.createTextNode("Initial Value : " + variables[i].value));
initialvalue.appendChild(initialvalueDiv);
var valuelockDiv = document.createElement('div');
valuelockDiv.id = variables[i].variableID + "valuelock";
valuelockDiv.className = "valuelockDiv ";
valuelockDiv.appendChild(document.createTextNode("Value : " + variables[i].value));
valuelockDiv.appendChild(document.createTextNode("Lock : " + variables[i].locked.toString()));
valuelock.appendChild(valuelockDiv);
variableIDArray[variables[i].variableID];
}
};
function showvariable(varid) {
for (v in variableIDArray)
hide(variableIDArray[v]);
show(varid + "description");
show(varid + "varid");
show(varid + "initialvalue");
show(varid + "valuelock");
}
function show(elemid) {
document.getElementById(elemid).style.display = "block";
}
function hide(elemid) {
document.getElementById(elemid).style.display = "none";
}
Yes. jQuery. Will reduce your code to about 6 lines. :) http://jquery.com

Categories