How to save results to localStorage - javascript

I am new in HTML and jQuery, and this was my first implementation, and I am not sure it's correct, I need your help, I tried to make simple counter to begin counting per click, and to store the results in localStorage, this is all I could do
but it didn't work, may you tell me what I've done wrong?
Thanks
$(function() {
$('.container li').click(function() {
var btn = $(this).attr("data-page");
var element = $('.counter[data-page="' + btn + '"]').html();
element++
$('.counter[data-page="' + btn + '"]').html(element);
localStorage.setItem('save', $('.counter[data-page="' + btn + '"]').html());
if (localStorage.getItem('save')) {
$('.counter[data-page="' + btn + '"]').html(localStorage.getItem('save'));
}
});
});
ul {
padding: 0;
margin: 0;
list-style: none;
}
a {
text-decoration: none;
background: blue;
color: #fff;
padding: 10px;
}
ul li {
display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="container">
<li data-page="facebook">
4100
</li>
<li data-page="twitter">
4100
</li>
</ul>

You need to init first your buttons with values from localStorage. Then you don't need to retrieve them again, you just need to manipulate the value inside the html and to set the new counter in the localStorage.
Also you need to have one counter by button in your localStorage
// Just to make this snippet work,
// because localStorage is forbiden here
// database = localStorage
database = {
store: {},
getItem: function(key) {
return this.store[key];
},
setItem: function(key, val) {
this.store[key] = val;
},
}
$(function() {
$(".counter").each((_, element) => {
const $btn = $(element);
const key = `save-${$btn.attr("data-page")}`;
$btn.html(database.getItem(key) || 0);
});
$(".container li").click(function() {
const $btn = $(this).find(".counter");
const key = `save-${$btn.attr("data-page")}`;
const counter = (+$btn.html()) + 1;
$btn.html(counter);
database.setItem(key, counter);
});
});
ul {
padding: 0;
margin: 0;
list-style: none;
}
a {
text-decoration: none;
background: blue;
color: #fff;
padding: 10px;
}
ul li {
display: inline-block;
}
<ul class="container">
<li data-page="facebook">
4100
</li>
<li data-page="twitter">
4100
</li>
</ul>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

You need to load the data from the local storage when the page loads. Right now it only loads after saving, which has no effect.
Each element is also saving to the same part of the local storage, so they will be the same every time the page loads. You need to save to an index based on the data-page.

Here you go with one more solution https://jsfiddle.net/thrh78u0/
$(function() {
$('.container li').click(function() {
var btn = $(this).attr("data-page");
var element = $('.counter[data-page="' + btn + '"]').html();
element++
$('.counter[data-page="' + btn + '"]').html(element);
localStorage.setItem('save' + btn, element);
if (localStorage.getItem('save')) {
$('.counter[data-page="' + btn + '"]').html(localStorage.getItem('save'));
}
});
});
ul {
padding: 0;
margin: 0;
list-style: none;
}
a {
text-decoration: none;
background: blue;
color: #fff;
padding: 10px;
}
ul li {
display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="container">
<li data-page="facebook">
4100
</li>
<li data-page="twitter">
4100
</li>
</ul>
Hope this will help you.

Try this simple one:
$('.container li').click(function() {
if (localStorage.count) {
localStorage.count++
} else {
localStorage.count = 1;
}
})

Updated script using different variables for different counters. It loads counters values from localStorage or sets them to 0 if not available. It also uses two separate variables to store the values.
I used your code so you can see what is different and what you missed in your solution
$(function() {
var cntfb = localStorage.getItem('save-facebook');
$('.counter[data-page="facebook"]').html(cntfb ? cntfb : 0);
var cnttw = localStorage.getItem('save-twitter');
$('.counter[data-page="twitter"]').html(cnttw ? cnttw : 0);
$('.container li').click(function() {
var btn = $(this).attr("data-page");
var element = $('.counter[data-page="' + btn + '"]').html();
element++;
$('.counter[data-page="' + btn + '"]').html(element);
localStorage.setItem('save-' + btn, $('.counter[data-page="' + btn + '"]').html());
if (localStorage.getItem('save-' + btn)) {
$('.counter[data-page="' + btn + '"]').html(localStorage.getItem('save-' + btn));
}
});
});

Related

Copy selected <li> to another <ul> with js

function addSelected(clicked_id) {
// alert(clicked_id);
const ul = document.getElementById("sortable2");
const listItems = ul.getElementsByTagName("li");
// const ul2 = document.getElementById('slottable1');
// Loop through the NodeList object.
for (let i = 0; i <= listItems.length - 1; i++) {
if (listItems[i].className == "selectedli") console.log(listItems[i]);
//need to copy these <li> tags in another <ul> list
}
}
<ul id="slottable">
//need to copy selected <li> here and also remove class from those selected <li> before adding here
</ul>
output of the console:
<li id="pc_103" class="selectedli">B73</li>
<li id="pc_104" class="selectedli">B74</li>
I have successfully printed li which I want to copy to another ul in console logs but not able to find the right code to copy them to my another ul. I also need to remove the class 'selectedli' from the li before adding it to the ul 'slottable'.
It's done by creating dynamic tag inside slottable.
See below example:
const getChild = document.getElementById("sortable2").children;
function addSelected() {
let createUl = document.createElement("ul");
createUl.id = "slottable";
document.getElementById("tagBox").appendChild(createUl);
for (let i = 0; i < getChild.length; i++) {
if (getChild[i].className == "selectedli")
{
var createLi = document.createElement("li");
createLi.id = getChild[i].id
createLi.classList.add(getChild[i].classList);
createLi.innerHTML = getChild[i].textContent;
createUl.appendChild(createLi);
console.log(getChild[i]);
}
}
document.getElementById("sortable2").innerHTML = "";
}
ul
{
list-style: none;
}
#sortable2
{
padding: 10px;
background: red;
width: 30px;
}
#slottable
{
padding: 10px;
background: green;
width: 30px;
}
<body>
<div id="tagBox">
</div>
<ul id="sortable2">
<li id="pc_103" class="selectedli">B73</li>
<li id="pc_104" class="selectedli">B74</li>
</ul>
<input type="button" onclick="addSelected()" value="submit">
</body>
The appendChild() method should work.
Like this:
sortable2.appendChild(selectedli)
To remove classes, use selectedli.classList.remove(selectedli)
You looking for something like that?
It copied from one ul to the new ul and removes the class.
classList.remove and appendChild:
lis.map((el) => {
el.classList.remove('selectedli');
el.innerText += ' (copied and without classs slectedli)'
ul2.appendChild(el)
})
const btn = document.getElementById('transfer');
btn.addEventListener('click', () => {
// copy from slottable to sortable2
const ul = document.getElementById("slottable").children;
const ul2 = document.getElementById("sortable2");
let lis = Object.values(ul);
lis.map((el) => {
el.classList.remove('selectedli');
el.innerText += ' (copied and without classs slectedli)'
ul2.appendChild(el)
})
ul.innerHTML = '';
});
.green {
background: green;
}
.gray {
background: gray;
}
<ul id="slottable" class="gray">
<li id="pc_103" class="selectedli">B73</li>
<li id="pc_104" class="selectedli">B74</li>
</ul>
<ul id="sortable2" class="green"></ul>
<button id="transfer">click </button>

Why is my text output from next() and prev() toggle incorrect?

When clicking the arrows to change the displayed option, the incorrect options is shown.
The user should be able click on the option menu to toggle it open/cosed and be able to click on a option to select it. Alternatively, the arrows could be used to toggle through the options instead.
This is the problematic code:
<script>
$("#arrow_left_physics").click(function() {
var $selected = $(".left_menu_option_selected").removeClass("left_menu_option_selected");
var divs = $("#left_menu__variant_physics").children();
divs.eq((divs.index($selected) - 1) % divs.length).addClass("left_menu_option_selected");
$("#left_menu_open .button-text").text($($selected).text());
});
$("#arrow_right_physics").click(function() {
var $selected = $(".left_menu_option_selected").removeClass("left_menu_option_selected");
var divs = $selected.parent().children();
divs.eq((divs.index($selected) + 1) % divs.length).addClass("left_menu_option_selected");
$("#left_menu_open .button-text").text($($selected).text());
});
</script>
$("#menu_open").click(function() {
$("#menu").toggle();
});
$(".menu_option").click(function() {
if ($(this).hasClass(".menu_option_selected")) {} else {
$(".menu_option").removeClass("menu_option_selected");
$(this).addClass("menu_option_selected");
$("#menu_open .button_text").text($(this).text());
}
});
$("#arrow_left").click(function() {
var $selected = $(".menu_option_selected").removeClass("menu_option_selected");
var options = $("#menu").children();
options.eq((options.index($selected) - 1) % options.length).addClass("menu_option_selected");
$("#menu_open .button_text").text($($selected).text());
});
$("#arrow_right").click(function() {
var $selected = $(".menu_option_selected").removeClass("menu_option_selected");
var options = $("#menu").children();
options.eq((options.index($selected) + 1) % options.length).addClass("menu_option_selected");
$("#menu_open .button_text").text($($selected).text());
});
.menu_open {
Cursor: pointer;
}
.menu {
display: none;
position: absolute;
border: 1px solid;
}
.menu_option {
Cursor: pointer;
Padding: 5px;
}
.menu_option:hover {
Background-Color: black;
Color: white;
}
.menu_option_selected {
color: green;
Background-color: #00ff0a4d;
}
.menu_option_selected:hover {
color: green;
}
.arrow {
Cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input class="arrow" type="button" id="arrow_left" value="❮" />
<input class="arrow" type="button" id="arrow_right" value="❯" />
</div>
<div>
<button class="menu_open" id="menu_open">
<span class="button_text">option1</span>
</button>
</div>
<div class="menu" id=menu>
<div class="menu_option menu_option_selected">option1</div>
<div class="menu_option">option2</div>
<div class="menu_option">option3</div>
<div class="menu_option">option4</div>
<div class="menu_option">option5</div>
<div class="menu_option">option6</div>
</div>
-It seems that the first click of the arrows isn't working and that the index function is incorrect somewhere.
The problem is this line:
$("#menu_open .button_text").text($($selected).text());
$($selected) is the option that was previously selected, so you're showing the text of the previous option, not the current option. (BTW, there's no need to wrap $selected in $(), since it's already a jQuery object.)
You should use $(".menu_option_selected").text() instead of $($selected).text() to get the current option.
You should also make the initial text of the button option1, so it matches the selected option.
$("#menu_open").click(function() {
$("#menu").toggle();
});
$(".menu_option").click(function() {
if ($(this).hasClass(".menu_option_selected")) {} else {
$(".menu_option").removeClass("menu_option_selected");
$(this).addClass("menu_option_selected");
$("#menu_open .button_text").text($(this).text());
}
});
$("#arrow_left").click(function() {
var $selected = $(".menu_option_selected").removeClass("menu_option_selected");
var options = $("#menu").children();
options.eq((options.index($selected) - 1) % options.length).addClass("menu_option_selected");
$("#menu_open .button_text").text($(".menu_option_selected").text());
});
$("#arrow_right").click(function() {
var $selected = $(".menu_option_selected").removeClass("menu_option_selected");
var options = $("#menu").children();
options.eq((options.index($selected) + 1) % options.length).addClass("menu_option_selected");
$("#menu_open .button_text").text($(".menu_option_selected").text());
});
.menu_open {
Cursor: pointer;
}
.menu {
display: none;
position: absolute;
border: 1px solid;
}
.menu_option {
Cursor: pointer;
Padding: 5px;
}
.menu_option:hover {
Background-Color: black;
Color: white;
}
.menu_option_selected {
color: green;
Background-color: #00ff0a4d;
}
.menu_option_selected:hover {
color: green;
}
.arrow {
Cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input class="arrow" type="button" id="arrow_left" value="❮" />
<input class="arrow" type="button" id="arrow_right" value="❯" />
</div>
<div>
<button class="menu_open" id="menu_open">
<span class="button_text">option1</span>
</button>
</div>
<div class="menu" id=menu>
<div class="menu_option menu_option_selected">option1</div>
<div class="menu_option">option2</div>
<div class="menu_option">option3</div>
<div class="menu_option">option4</div>
<div class="menu_option">option5</div>
<div class="menu_option">option6</div>
</div>
Just another version, refactoring your javascript code with some Arrow functions.
const setButtonText = () => {
$("#menu_open .button_text").text(
$(".menu_option_selected").text()
);
}
const moveSelection = direction => {
var selected = $(".menu_option_selected")
var options = $("#menu").children()
var newIndex;
if (direction == 'right') {
newIndex = (options.index(selected) + 1) % options.length
} else {
newIndex = (options.index(selected) - 1) % options.length
}
selected.removeClass("menu_option_selected")
options.eq(newIndex).addClass("menu_option_selected")
setButtonText()
}
// inizilize menu button_text
setButtonText()
$("#arrow_left").click(() => moveSelection('left'));
$("#arrow_right").click( () => moveSelection('right'));
$("#menu_open").click( () => $("#menu").toggle());
$(".menu_option").click( function() {
$(".menu_option_selected").removeClass("menu_option_selected")
$(this).addClass("menu_option_selected")
setButtonText()
});

Tooltipster content doubling up each time it is opened

I'm using Tooltipster to show a list of items that the user can click so as to enter the item into a textarea. When a tooltip is created, I get its list of items with selectors = $("ul.alternates > li");
However, each time a tooltip is opened the item clicked will be inserted a corresponding number of times; for example if I've opened a tooltip 5 times then the item clicked will be inserted 5 times. I've tried deleting the variable's value after a tooltip is closed with functionAfter: function() {selectors = null;} but that had no effect.
I have a Codepen of the error here that should make it clearer.
// set list to be tooltipstered
$(".commands > li").tooltipster({
interactive: true,
theme: "tooltipster-light",
functionInit: function(instance, helper) {
var content = $(helper.origin).find(".tooltip_content").detach();
instance.content(content);
},
functionReady: function() {
selectors = $("ul.alternates > li");
$(selectors).click(function() {
var sampleData = $(this).text();
insertText(sampleData);
});
},
// this doesn't work
functionAfter: function() {
selectors = null;
}
});
// Begin inputting of clicked text into editor
function insertText(data) {
var cm = $(".CodeMirror")[0].CodeMirror;
var doc = cm.getDoc();
var cursor = doc.getCursor(); // gets the line number in the cursor position
var line = doc.getLine(cursor.line); // get the line contents
var pos = {
line: cursor.line
};
if (line.length === 0) {
// check if the line is empty
// add the data
doc.replaceRange(data, pos);
} else {
// add a new line and the data
doc.replaceRange("\n" + data, pos);
}
}
var code = $(".codemirror-area")[0];
var editor = CodeMirror.fromTextArea(code, {
mode: "simplemode",
lineNumbers: true,
theme: "material",
scrollbarStyle: "simple",
extraKeys: { "Ctrl-Space": "autocomplete" }
});
body {
margin: 1em auto;
font-size: 16px;
}
.commands {
display: inline-block;
}
.tooltip {
position: relative;
opacity: 1;
color: inherit;
}
.alternates {
display: inline;
margin: 5px 10px;
padding-left: 0;
}
.tooltipster-content .alternates {
li {
list-style: none;
pointer-events: all;
padding: 15px 0;
cursor: pointer;
color: #333;
border-bottom: 1px solid #d3d3d3;
span {
font-weight: 600;
}
&:last-of-type {
border-bottom: none;
}
}
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.25.2/theme/material.min.css" rel="stylesheet"/>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/235651/jquery-3.2.1.js"></script>
<script src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/235651/tooltipster.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.25.2/codemirror.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.25.2/addon/mode/simple.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.25.2/addon/hint/show-hint.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.25.2/addon/scroll/simplescrollbars.js"></script>
<div class="container">
<div class="row">
<div class="col-md-6">
<ul class="commands">
<li><span class="command">Hover for my list</span><div class="tooltip_content">
<ul class="alternates">
<li>Lorep item</li>
<li>Ipsum item</li>
<li>Dollar item</li>
</ul>
</li>
</div>
</ul>
</div>
<div class="col-md-6">
<textarea class="codemirror-area"></textarea>
</div>
</div>
</div>
Tooltipster's functionReady fires every time the tooltip is added to the DOM, which means every time a user hovers over the list, you are binding the event again.
Here are two ways to prevent this from happening:
Attach a click handler to anything that exists in the DOM before the tooltip is displayed. (Put it outside of tooltipspter(). No need to use functionReady.)
Example:
$(document).on('click','ul.alternates li', function(){
var sampleText = $(this).text();
insertText(sampleText);
})
Here's a Codepen.
Unbind and bind the event each time functionReady is triggered.
Example:
functionReady: function() {
selectors = $("ul.alternates > li");
$(selectors).off('click').on('click', function() {
var sampleData = $(this).text();
insertText(sampleData);
});
}
Here's a Codpen.
You are binding new clicks every time.
I would suggest different code style but in that format you can just add before the click event
$(selectors).unbind('click');
Then do the click again..

Removing a bootstrap popover dynamically using jquery

This following works when a list item is selected and then hovered and a popover is shown. But when I try to remove popover data attributes from list tag, all the tag removes but the popover does not remove. How to remove the popover such that when an item is not selected, the popover is not shown?
/* Latest compiled and minified JavaScript included as External Resource */
// Checked list box items
$(function() {
$('.list-group.checked-list-box .list-group-item').each(function() {
// Settings
var $widget = $(this),
$checkbox = $('<input type="checkbox" class="hidden" />'),
color = ($widget.data('color') ? $widget.data('color') : "primary"),
style = ($widget.data('style') == "button" ? "btn-" : "list-group-item-"),
settings = {
on: {
icon: 'glyphicon glyphicon-check'
},
off: {
icon: 'glyphicon glyphicon-unchecked'
}
};
$widget.css('cursor', 'pointer')
$widget.append($checkbox);
// Event Handlers
$widget.on('click', function() {
$checkbox.prop('checked', !$checkbox.is(':checked'));
$checkbox.triggerHandler('change');
updateDisplay();
});
$checkbox.on('change', function() {
var id = $(this).closest('li').attr('id');
var isChecked = $checkbox.is(':checked');
if (isChecked) addPopOver(id);
else removePopOver(id);
updateDisplay();
});
function addPopOver(id) {
id = "#" + id;
$(id).attr('data-toggle', "popover");
$(id).attr('data-trigger', "hover");
$(id).attr('data-original-title', $(id).text());
$(id).attr('data-content', "(No items selected)");
$('[data-toggle=popover]').popover();
}
function removePopOver(id) {
id = "#" + id;
$(id).removeAttr("data-toggle");
$(id).removeAttr("data-trigger");
$(id).removeAttr("data-original-title");
$(id).removeAttr("data-content");
}
// Actions
function updateDisplay() {
var isChecked = $checkbox.is(':checked');
// Set the button's state
$widget.data('state', (isChecked) ? "on" : "off");
// Set the button's icon
$widget.find('.state-icon')
.removeClass()
.addClass('state-icon ' + settings[$widget.data('state')].icon);
// Update the button's color
if (isChecked) {
$widget.addClass(style + color + ' active');
} else {
$widget.removeClass(style + color + ' active');
}
}
// Initialization
function init() {
if ($widget.data('checked') == true) {
$checkbox.prop('checked', !$checkbox.is(':checked'));
}
updateDisplay();
// Inject the icon if applicable
if ($widget.find('.state-icon').length == 0) {
$widget.prepend('<span class="state-icon ' + settings[$widget.data('state')].icon + '"></span>');
}
}
init();
});
$('#get-checked-data').on('click', function(event) {
event.preventDefault();
var checkedItems = {},
counter = 0;
$("#check-list-box li.active").each(function(idx, li) {
checkedItems[counter] = $(li).text();
counter++;
});
$('#display-json').html(JSON.stringify(checkedItems, null, '\t'));
});
});
/* Check Box For item required */
.state-icon {
left: -5px;
}
.list-group-item-primary {
color: rgb(255, 255, 255);
background-color: rgb(66, 139, 202);
}
/* DEMO ONLY - REMOVES UNWANTED MARGIN */
.well .list-group {
margin-bottom: 0px;
}
.list-inline>li {
display: inline-block;
padding-right: 12px;
padding-left: 20px;
margin-bottom: 3px;
font-size: 17px;
}
#check-list-box {
padding: 10px;
}
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<ul id="check-list-box" class="list-group checked-list-box list-inline ">
<li class="list-group-item event-item" id="venue" data-color="danger">Venue</li>
<li class="list-group-item event-item" id="catering" data-color="info">Catering</li>
<li class="list-group-item event-item" id="desserts" data-color="warning">Desserts</li>
<li class="list-group-item event-item" id="photographer" data-color="success">Photographer</li>
<li class="list-group-item event-item" id="bus" data-color="danger">Party buses</li>
<li class="list-group-item event-item" id="castles" data-color="danger">Bouncy Castles</li>
<li class="list-group-item" data-color="danger">Other</li>
<!--<input type="textbox" name ="other" >-->
</ul>
You could use .popover('destroy').
function removePopOver(id) {
id = "#" + id;
$(id).popover('destroy')
}
To destroy the shown popover you can use the following code-snippet:
function removePopOver(id) {
id = "#" + id;
$(id).popover('dispose'); // JQuery > 4.1
// $(id).popover('destroy'); // JQuery < 4.1
}
You can also remove all created popovers from your DOM via .popover class (of course each popover has its own id, so by knowing the IDs you can be more precise)
$('.popover').remove();

Custom html tab implementation problems

my use case : create tab like experience. clicking on add button creates a (horz tab button) and a corresponding div, which is linked via onclick listener, dynamically.
problems :
on clicking add button, values from previous tabs are reset (which is obvious wrt to the way $tabs_prev & $menu_prev is populated) and
their respective js goes away (which I can't understand, why?)
a remove tab implementation (because the way I've coded these tabs, removing a tab and corresponding div isn't really simple, so, any clues in this direction, maybe?)
code : fiddle : http://jsfiddle.net/g58fzs75/1/
HTML:
<body>
<input id="hidden" type="hidden" value="1"></input>
<div id="template_tabBtn" style="display:none">
<input type="button" value="add" onclick="addTab()"></input>
</div>
<ul id="menu">
</ul>
<div id="tabs">
</div>
<div id="template_tabBar" style="display:none">
<li>
<input type="button" id="tab_btn" class="template_tabBar" value="Tab" onclick="tabClick(this)"></input>
</li>
</div>
<div id="template_tabs" style="display:none">
<div id="tabs" class="template_tabs tab_div" value="1">
<input type="text" id="txt" class="template_tabs" value="alert"></input>
<input type="button" id="btn" class="template_tabs" value="alert"></input>
</div>
</div>
</body>
CSS:
<style>
ul#menu {
padding: 0;
}
ul#menu li {
display: inline;
}
ul#menu li input {
background-color: black;
color: white;
padding: 10px 20px;
text-decoration: none;
border-radius: 4px 4px 0 0;
}
ul#menu li input:hover {
background-color: orange;
}
</style>
jQuery :
<script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script>
<script>
$tabs_prev = "";
$menu_prev = "";
$add_btn = "";
$current_tabID = "";
function tabClick(id) {
showCurrent($(id).attr('id'));
}
function addTab() {
var tabCount = parseInt($('#hidden').val()) + 1;
$('#hidden').val(tabCount);
run(tabCount);
showCurrent($('#tabs-' + tabCount).attr('id'));
}
$(document).ready(function() {
$add_btn = "<li>" + $('#template_tabBtn').html() + "</li>";
run(1);
});
function run(tabCount) {
//$tabs_prev += main($('#template_tabs'),tabCount);//alert("tabs\n"+$tabs_prev);
$menu_prev += main($('#template_tabBar'), tabCount); //alert("menu\n"+$menu_prev);
$('#tabs').html($('#tabs').html() + main($('#template_tabs'), tabCount));
$('#menu').html($menu_prev + $add_btn);
logic(tabCount);
}
function main(target, tabCount) {
$htmlBackup = $(target).html();
$('.' + $(target).attr('id')).each(function() {
$(this).attr('id', $(this).attr('id') + "-" + tabCount).removeClass($(target).attr('id'));
$(this).attr('value', $(this).attr('value') + "-" + tabCount);
});
$html = $(target).html();
$(target).html($htmlBackup);
return $html;
}
function logic(tabCount) {
$('#btn-' + tabCount).click(function() {
alert($('#txt-' + tabCount).val());
});
}
function showCurrent(current_id) {
$('.tab_div').each(function() {
var id = $(this).attr('id');
var id_num = id.substr(id.lastIndexOf('-') + 1, id.length);
var current_id_num = current_id.substr(current_id.lastIndexOf('-') + 1, current_id.length);
if (id_num == current_id_num) {
$("#tabs-" + id_num).show();
$('#tab_btn-' + id_num).css({
"background-color": "orange"
});
} else {
$("#tabs-" + id_num).hide();
$('#tab_btn-' + id_num).css({
"background-color": "black"
});
}
});
}
</script>
The reason why your javascript is disappearing is because resetting the innerHTML deletes the onclick handlers on the elements. Why: the original elements are destroyed, including references to events and new elements are created.
The code responsible for this:
$('#tabs').html($('#tabs').html() + main($('#template_tabs'), tabCount));
Please use jQuery's appending of an element by cloning the template tab:
$('#tabs').append($('#template_tabs').clone(true));
Append appends htmlstrings or elements to an parent element. It's a buffed up version of the documents native 'appendChild'.
clone clone the template element (makes a copy). You can do this in your function main and return it to the append function.
function main(tabCount)
{
var node = $('#template_tabs').clone(true));
//do things with the node, like setting an onclick handler, or id.
//example
node.setAttribute("id", "tab" + tabCount);
}
Removing can be done also:
function removeNode(node)
{
//provide a node via jQuery
//example: removeNode($("#tab2")) <-- now tab2 will be removed from the DOM.
node.remove();
}

Categories