Toggle li don't work after json load? - javascript

i tried to build an color system management but i'm newbies and it's so difficult for me !
My problem is :
when i load my html page, all work fine, but when i click on the "li" element for load json, all my toggle elements don't work !!! strange , where is the problem please ? syntax?
HTML CODE :
<div id="content">
<div class="theme-item">
<ul class="color-list one">
<li>
<span class="in"></span>
</li>
</ul>
</div>
<ul class="elements-list">
<li class="elements-item">
<span class="tog">test one</span>
<div class="togcont hidden">
<h5 data-title="">text text</h5>
</div>
</li>
</ul>
</div>
jQUERY CODE :
$(document).ready(function() {
// ----------------------
// JSON INFOS
// ----------------------
$(".color-list li").click(function(event){
$.getJSON('result.json', function(jd) {
$('ul.elements-list').html('<li class="elements-item"><span class="tog">' + jd.name + '</span><div class="togcont"><p>Name: ' + jd.name + '</p></div></li>');
$('ul.elements-list').append('<li class="elements-item"><span class="tog">' + jd.age + '</span><div class="togcont hidden">Name: ' + jd.age + '</div></li>');
$('ul.elements-list').append('<li class="elements-item"><span class="tog">' + jd.sex + '</span><div class="togcont hidden">Name: ' + jd.sex + '</div></li>');
});
});
// ----------------------
// TOGGLE BULLZ
// ----------------------
$(".tog").click(function(){
var obj = $(this).next();
if($(obj).hasClass("hidden")){
$(obj).removeClass("hidden").slideDown();
$(this).addClass("bounce");
} else {
$(obj).addClass("hidden").slideUp();
$(this).removeClass("bounce");
}
});
});
CSS CODE (PART) :
ul.elements-list {
list-style-position: inside;
list-style-type: none;
}
ul.elements-list li {
margin: 20px 0;
background-color: #393939;
border-radius: 16px;
text-transform: uppercase;
font-weight: 300;
}
ul.elements-list li .tog {
color: #FFF;
cursor:pointer;
width: 100%;
display: inline-block;
box-sizing: border-box;
cursor:pointer;
}
div.togcont {
padding:15px 20px;
overflow:hidden;
margin-bottom:20px;
display: none;
text-transform: none;
line-height: 1.8em;
font-size: 1.0em;
color: #CCC;
text-shadow: 0 2px 0 rgba(0,0,0,0.3);
}

Try using delegation:
$(document).on('click', ".tog", function(){
Since the click handler is attached before you append the new elements, you need to delegate this click handler for the event to be caught.
Check the documentation for .on()
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). - Which means "$(document).on(" is a safe card

Try .on()
$(document).on("click", ".tog", function(){
You need event delegation

Related

jQuery problem with each() and prepend function for ul and li elements

Add JavaScript + jQuery code that will number the list items after loading the document
by adding the next item number in bold at the beginning;
1 Poland
2 Germany
3 Italy
My code si below:
<script type="text/javascript">
$(function (){
$('li').prepend(
each(function(index){
index++;
index + ": " + $( this ).text();
}))
;
});
</script>
</head>
<body>
<ul>
<li>Poland</li>
<li>Germany</li>
<li>Italy</li>
</ul>
</body>
Not work. I tried many times without results.
If i understand right you, you don't need to use javascript for this.
Please check below,
ul {
counter-reset: my-awesome-counter;
max-width: 350px;
counter-reset: my-awesome-counter;
list-style: none;
padding-left: 40px;
}
ul li {
margin: 0 0 0.5rem 0;
counter-increment: my-awesome-counter;
position: relative;
}
ul li:before {
content: counter(my-awesome-counter);
color: #fcd000;
font-size: 1.5rem;
font-weight: bold;
position: absolute;
left:-40px;
line-height: 20px;
width:30px;
height:30px;
top: 0;
background: black;
text-align: center;
}
<ul>
<li>Poland</li>
<li>Germany</li>
<li>Italy</li>
</ul>
And more information if you need;
https://css-tricks.com/custom-list-number-styling/
You can use ol in html (ordered list) or nice to make it using javascript or jquery because some time you may not use ol and ul maybe you want to make a counter in a table, I write a simple code for you If you have any question tell me.
// Using For Loop
/*for (let i = 0; i < $("#ul li").length; i= i + 1 ) {
$("#ul li").eq(i).prepend("<span class='counter'>" + (i + 1) + "</span> ")
}*/
// Using Each Loop
$( "#ul li" ).each(function( index ) {
$(this).prepend("<span class='counter'>" + (index + 1) + "</span> ")
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="ul">
<li>Poland</li>
<li>Germany</li>
<li>Italy</li>
</ul>

JsTree: Show more options

Is there any way to have a show more option/link in jsTree?
I want to show only part of the children and have a link to expand to show all elements.
I tried a few google searches but could not find a solution. Any help/hint would be useful.
Let's say parent-1 has 10 child nodes and the Main Root has 5 parent nodes.
Main Parent
- Parent - 1
- child-1
- child-2
- child-3
show 7 more parent-1 elements //LINK
- Parent - 2
- child-1
- child-2
- Parent - 3
- child-1
- child-2
show 2 more Main Parent elements //LINK
I'm trying to achieve the following result
Is this possible? Are there any available plugins for this? Are there any alternatives for jsTree that support this?
You could feasibly use classes/childElement count to work this. Depending on what you want to show, you could use ids/classes to leave the elements you want to stay visible or optionally show/hide. The same principle can be applied to both child elements (say list items in a list) and higher parent elements, so once you have the first function, it can easily be adapted.
I've included a list example here to give you the idea (it's in plain javascript and you could tweak it a bit..) Jquery would make the js shorter, but it's always good to know the vanilla i reckon..
var x = document.getElementById("show");
//var root = document.getElementsByTagName('body')[0];
var count = x.childElementCount;
var btn1 = document.getElementById("ulmore");
btn1.innerHTML = "+ Show all " + count + " li children";
document.getElementById("ulmore").addEventListener("click", showmore);
function showmore() {
//var d = document.getElementsByClassName("tg1").length;
//use d if you want to show "show d more children" instead of the full amount of children
var el = document.getElementsByTagName("li");
var i;
for (i = 0; i < el.length; i++) {
if (el[i].classList.contains("tg1")) {
//el[i].style.display = "block"; works
el[i].classList.toggle('more');
if (el[i].classList.contains("more")) {
btn1.innerText = "Hide children";
} else {
btn1.innerText = "+ Show all " + count + " li children";
}
}
}
}
body {
padding: 1em;
font-size: 10pt;
}
ul {
list-style: none;
width: 10em;
padding: 0px;
}
li {
text-align: left;
line-height: 1.5;
background: lightblue;
border: 1px solid #444;
margin: 1px 0px;
padding: 2px;
}
span {
display: inline-block;
}
div {
display: inline-block;
width: 100%;
float: left;
margin: 1em 2em 1em 0em;
}
.tg1 {
background: lightsteelblue;
display: none;
}
.more {
background: lightsteelblue;
display: block;
}
/*.tog2 {
display: none;
}
.grow {
background: yellow;
display: inline-block;
}*/
<body>
<div id="ulbit">
<h4>Demo List</h4>
<ul id="show">
<li>One</li>
<li>Two</li>
<li class="tg1">Three</li>
<li class="tg1">Four</li>
<li class="tg1">Five</li>
<li class="tg1">Six</li>
<li class="tg1">Seven</li>
<li class="tg1">Eight</li>
</ul>
<span id="ulmore"></span>
</div>
<!-- <div class="tog2">
Div 2 hello
</div>
<div class="tog2">
Div 3
</div>
<span id="divmore"></span>-->
</body>
Here's a fiddle link (with body 'parent' elements) included in code.
(Note: even a <br> tag [when used between divs] will be regarded as a top-level element .. I'd think that count by tagName (or className) would be most useful if you want to count different types of 'parent' elements (as opposed to counting children of body). Examples of both (children of body and getElementsByTagName) are included in the fiddle)
Hope this helps
did you try to use "before_open.jstree" event to show the tree the way you need?
see the example (I use part of the demo page from the jstree site):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jstree basic demos</title>
<style>
html { margin:0; padding:0; font-size:62.5%; }
body { max-width:800px; min-width:300px; margin:0 auto; padding:20px 10px; font-size:14px; font-size:1.4em; }
h1 { font-size:1.8em; }
.demo { overflow:auto; border:1px solid silver; min-height:100px; }
</style>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" />
</head>
<body>
<h1>Interaction and events demo</h1>
<button id="evts_button">select node with id 1</button> <em>either click the button or a node in the tree</em>
<div id="evts" class="demo"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>
<script>
// interaction and events
$('#evts_button').on("click", function () {
var instance = $('#evts').jstree(true);
instance.deselect_all();
instance.select_node('1');
});
$('#evts')
.on("changed.jstree", function (e, data) {
if(data.selected.length) {
alert('The selected node is: ' + data.instance.get_node(data.selected[0]).text);
}
})
.on("before_open.jstree", function (e, data,a,b,c,d) {
$('#' + data.node.id + ' ul li:nth-child(n + 2)').hide();
var str = '<li class="jstree-node jstree-leaf jstree-last" role="treeitem">press to show ' + $('#' + data.node.id + ' ul li:nth-child(n + 2)').length + ' more items</li>';
var li = $(str).on('click', function(a,b,c,d) {$(a.target).parent().find('li').show(); $(a.target).hide()});
$('#' + data.node.id + ' ul').append(li);
})
.jstree({
'core' : {
'multiple' : false,
'data' : [
{ "text" : "Root node", "children" : [
{ "text" : "Child node 1", "id" : 1 },
{ "text" : "Child node 2" }
]}
]
}
});
</script>
</body>
</html>
I hope this helped.

Toggle colour link colour on click

I have a program where a series of labels are shown and each time you click on them, they appear within a div (<div id = "div1"> </ div>), and to remove the labels, you must return to click but this time on the labels that have appeared inside div1.
What I'm trying now is that every time I click on the labels outside the div1, they turn blue and if I delete them from div1, they go back to the same color they were.
Can you help me? Can i do it in html + css? or i need js?
This is my JS:
var ar = new Array();
function myFunction(tagName, tagId) {
if (!document.getElementById(tagName)) {
document.getElementById("div1").innerHTML +=
'<label class="tags" id="' + tagName + '" onclick="rem(\'' + tagName + '\', \'' + tagId+ '\')">' + tagName + ', </label>';
ar.push(tagId);
document.getElementById("hiddenfield").value = ar;
}
}
function rem(tagName, tagId) {
document.getElementById(tagName).remove();
ar.splice(ar.indexOf(tagId), 1);
document.getElementById("hiddenfield").value = ar;
}
This is my PHP:
<p>
Introduce tags:
</p>
<div id="div1">
</div>
<h3>
<?php
while($row = $result->fetch_assoc()) {
echo "<label><a class=\"trigger blue lighten-4\" data-toggle=\"modal\" data-target=\"#conditionModal\" onclick=\"myFunction('" . $row["tag_name"] ."', '" . $row["tag_id"] ."')\">" . $row["tag_name"] ." </a></label>";
}
?>
</h3>
This is my CSS:
.trigger {
padding: 1px 10px;
font-size: 20px;
font-weight: 400;
border-radius: 10px;
background-color: aliceblue;
color: #212121;
display: inline-block;
margin: 2px 5px;
cursor:pointer;
}
a:hover {
color: black;
background-color: red;/* #e6e6e6 */
}
/* selected link */
a:active {
color: white;
}
.tags {
font-family: Arial, Helvetica, sans-serif;
cursor:pointer;
padding: 1px 10px;
font-size: 15px;
font-weight: 400;
border-radius: 10px;
background-color: aliceblue;
color: #212121;
display: inline-block;
margin: 2px 5px;
}
.tags:hover {
color: red;
}
What I would like is something like this:
http://jsfiddle.net/Shef/L6VqK/
But instead of clicking the same link, the link is inside Div1
These are the basics. Just have two elements containing your labels. ( I use a list here, since it makes sense to use a list when listing multiple items. ) Then have the color be determined by the list they belong to, instead of having the color on the items themselves.
Switching from one list to the other is as easy as just appending the target to the new list.
const tags = [ ...document.querySelectorAll( '.tag' )];
const input = document.querySelector( '#tags_input' );
const output = document.querySelector( '#tags_output' );
const move = event => {
const list = event.target.parentNode.parentNode;
if ( list.id === 'tags_input' ) output.appendChild( event.target.parentNode );
else if ( list.id === 'tags_output' ) input.appendChild( event.target.parentNode );
};
tags.forEach( tag => tag.addEventListener( 'click', move ));
#tags_input .tag {
background-color: lightblue;
}
#tags_output .tag {
background-color: grey;
}
<ul id="tags_input">
<li class="tag">First tag</li>
<li class="tag">Second tag</li>
<li class="tag">Third tag</li>
<li class="tag">Fourth tag</li>
<li class="tag">Fifth tag</li>
<li class="tag">Sixth tag</li>
<li class="tag">Seventh tag</li>
</ul>
<ul id="tags_output"></ul>
Keep in mind that this is very similar to basic link functionality, where already clicked links use the :visited color, which can be fully done in CSS ( by using a:visited, a:hover, a:active, etc ).
It's only moving the items and resetting the link color back to the original , as if the link is not clicked yet, that cannot be fully done in CSS.

Onsubmit form creating new div with id and class

I'm building a tabbed content page. I was trying to build a form that would take a value from the form and create a new tab and also create a new div that would attach to the tab, that would be triggered by an on click function. I was having some trouble creating the div, it didn't seem to launch. When the value is entered, the tab is supposed to go active so the content would show up. I think I'm either doing something wrong with the new div or the on click function. I wasn't sure if those two code pieces should be combined, since they seemed to be in conflict. Thanks.
jQuery(document).ready(function() {
jQuery('.tabs .tab-links a').on('click', function(e) {
var currentAttrValue = jQuery(this).attr('href');
$('.tabs ' + currentAttrValue).show();
$('.tabs ' + currentAttrValue).animate({
opacity: 1,
paddingLeft: '30%'
}, 400);
$('.tabs ' + currentAttrValue).siblings().css({
opacity: 0,
paddingLeft: '0%'
});
$('.tabs ' + currentAttrValue).fadeIn(400).siblings().hide();
jQuery(this).parent('li').addClass('active').siblings().removeClass('active');
e.preventDefault();
});
});
$(function() {
var $textInput = $('input:text');
$('#examine').on('submit', function(e) {
e.preventDefault();
var newText = $textInput.val();
$('ul:last').append('<li>Searching...</li>');
$('#tab-content').append('<div id ="tab5' + '"class="tab active"><p>the quick brown fox</p></div>');
jQuery(this).parent('li').addClass('active').siblings().removeClass('active');
$textInput.val('');
});
});
.tab-links {
float: left;
}
.tab-links:after {
display: block;
clear: both;
content: '';
}
.tab-links li {
list-style-type: none;
background-color: #303030;
border-bottom: 3px solid #858585;
font-family: 'Jacques Francois', serif;
text-transform: uppercase;
letter-spacing: 0.09em;
margin-left: -25%;
}
.tab-links li a {
color: #f2f2f2;
display: block;
padding: 3px 10px 3px 10px;
text-decoration: none;
}
.tab-links a:hover {
background: #a7cce5;
text-decoration: none;
}
.tab-links li.active,
.tab-links li.hover {
background-color: #e5e5e5;
border-bottom: 3px solid #e5e5e5;
}
.tab-links li.active a,
.tab-links li a:hover {
color: #666;
background-color: #e5e5e5;
}
/*----- Content of Tabs -----*/
.tab-content {
background-color: #e5e5e5;
color: #666;
min-height: 150px;
overflow: auto;
}
#tab1 {
padding-left: 30%;
}
#tab2,
#tab3,
#tab4,
#tab5 {
display: none;
opacity: 0;
padding-left: 0%;
}
.tab-content p {
margin: 20px;
text-indent: -40%;
}
.tab-content.active {
display: block;
text-indent: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="sidebar">
<div id="explore">
<form id="examine">
<p>Search</p>
<input type="search" name="explore" placeholder="Search Items" />
<p>Choose Your Search Restrictions</p>
<input type="radio" name="location" required="required" value="Your School" />Inside
<input type="radio" name="location" required="required" value="Whole system" />Outside
<input type="submit" value="Search" />
</form>
</div>
<div class="tabs">
<ul class="tab-links">
<li class="active">Tab1
</li>
<li>Tab2
</li>
<li>Tab3
</li>
<li>Tab4
</li>
</ul>
<div class="tab-content">
<div id="tab1" class="tab active">
<p>Tab1 content</p>
</div>
<div id="tab2" class="tab">
<p>Tab2 content</p>
</div>
<div id="tab3" class="tab">
<p>Tab3 content</p>
</div>
<div id="tab4" class="tab">
<p>Tab4 content</p>
</div>
First off you do not need two document ready handlers.
For clarity, I have added the NEW index to the "Searching..." string so you may need to edit that.
Use the index to get the new ID and append that to the list.
cache the tab and not process DOM for the tab
I assume you have some need for $textInput.val(''); so I left it
put your click handler on the .tab-links so new ones will have it (not on a1)
consider using classes and indexes instead of new IDs for tab5 etc.
if you use classes you could then clone the last tab and put in new content into the clone, making it more maintainable if the markup changes
I put a trigger on the newly added tab to activate it - it SEEMED as if that was your desire?
Consider a BUTTON rather than <input type="submit"...
Revised code:
jQuery(document).ready(function() {
jQuery('.tabs').find('.tab-links').on('click', 'a', function(e) {
var currentAttrValue = jQuery(this).attr('href');
// cache instead of multiple
var thisTab = $(currentAttrValue);
thisTab.show().animate({
opacity: 1,
paddingLeft: '30%'
}, 400);
thisTab.siblings().css({
opacity: 0,
paddingLeft: '0%'
});
thisTab.fadeIn(400).siblings().hide();
jQuery(this).parent('li').addClass('active').siblings().removeClass('active');
e.preventDefault();
});
var $textInput = $('input:text');
$('#examine').on('submit', function(e) {
e.preventDefault();
var newText = $textInput.val();
var newIndex = $('.tab-links').find('li').length + 1;
$('.tab-content').append('<div id="tab' + newIndex + '" class="tab"><p>the quick brown fox ' + newIndex + '</p></div>');
$textInput.val('');
$('.tab-links').append('<li>Searching...' + newIndex + '</li>');
$('.tab-links').find('a').eq(newIndex - 1).trigger('click');
});
});f
EDIT: Per comment, update if already at max count:
This is not super efficient but you can get started with this.
jQuery(document).ready(function() {
jQuery('.tabs').find('.tab-links').on('click', 'a', function(e) {
var currentAttrValue = jQuery(this).attr('href');
// console.log(currentAttrValue);
var thisTab = $(currentAttrValue);
thisTab.show().animate({
opacity: 1,
paddingLeft: '30%'
}, 400);
thisTab.siblings().css({
opacity: 0,
paddingLeft: '0%'
});
thisTab.fadeIn(400).siblings().hide();
jQuery(this).parent('li').addClass('active').siblings().removeClass('active');
e.preventDefault();
});
var maxTabCount = 5;
var $textInput = $('input[type=search]');
$('#examine').on('submit', function(e) {
e.preventDefault();
var newText = $textInput.val();
var tabCount = $('.tab-links').find('li').length;
var newIndex = tabCount + 1;
var newText = $textInput.val() ? $textInput.val() : "Default Tab Text";
if (tabCount < maxTabCount) {
$('.tab-content').append('<div id="tab' + newIndex + '" class="tab"><p>the quick brown fox ' + newIndex + '</p></div>');
$('.tab-links').append('<li>Searching...' + newIndex + '</li>');
} else {
$('.tab-content').find('div.tab').last().find('p').html("New Search Content");
$('.tab-links').find('li').last().find('a').html(newText);// new tab text
}
$textInput.val('');
$('.tab-links').find('a').last().trigger('click');
});
});
You are using id for tab-content instead of class. Use the following line:
$('.tab-content').append('<div id ="tab5' + '"class="tab active">...</div>');
Replace this line jQuery('.tabs .tab-links a').on('click', function(e) with the following:
jQuery(document).on("click",".tabs .tab-links a",function() {

Javascript isn't correctly adding and subtracting floats

I've been messing about with an inventory-like system for a website I'm working on.
I don't usually use JavaScript, So this little problem has been driving me crazy.
I'm trying to add two floats together using two different functions.
One is addition, One is subtraction.
This is the code:
function addItem(item){
$("#item-" + item.toString()).insertAfter("#selected h1");
$("#item-" + item.toString() + " a").attr("onclick","remItem(" + item.toString() + ")");
updateTotal(item, 0);
}
function remItem(item){
$("#item-" + item.toString()).insertAfter("#my h1");
$("#item-" + item.toString() + " a").attr("onclick","addItem(" + item.toString() + ")");
updateTotal(item, 1);
}
function updateTotal(item, action){
if(action=0){
var value = $("#item-" + item.toString() + " a .value").text().replace("$ ", "");
var oldVal = $(".total").text().replace("$ ", "");
var newVal = parseFloat(value) + parseFloat(oldVal);
$(".total").text(newVal);
} else {
var value = $("#item-" + item.toString() + " a .value").text().replace("$ ", "");
var oldVal = $(".total").text().replace("$ ", "");
var newVal = parseFloat(value) - parseFloat(oldVal);
$(".total").text(newVal);
}
}
.wrapper{
text-align: center;
}
.item-holder{
width: 45%;
text-align: left;
padding: 5px;
overflow: auto;
display: inline-block;
background-color: #222;
min-height: 160px;
}
.item-holder h1{
color: white;
margin: 0;
padding: 0;
text-align: center;
}
.smallimg{
margin: 2px 2%;
width: 96%;
}
.item {
margin: 2px 2px 2px 2px !important;
cursor: pointer;
color: #333;
background: rgba(200,200,200,0.9);
text-align: center;
min-width: 60px;
max-width: 100px;
width: 18%;
border: solid medium gray;
display: inline-block;
}
.value{
font-size: 10pt;
font-weight: bold;
padding-top: 5px;
}
.rarity{
font-style: italic;
font-weight: bold;
}
.total{
font-weight: bold;
}
.Consumer{
border-color: rgb(176, 195, 217);
}
.Mil-Spec{
border-color: rgb(75, 105, 255);
}
.Industrial{
border-color: rgb(94, 152, 217);
}
.Restricted{
border-color: rgb(136, 71, 255);
}
.Classified{
border-color: rgb(211, 44, 230);
}
.Covert{
border-color: rgb(235, 75, 75);
}
#selected{
color: white !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<span class="total">$ 0.00</span><br /><br />
<!-- START ITEM HOLDER-->
<div id="my" class="item-holder">
<h1>Your Items</h1>
<div class="item Industrial" id="item-22">
<a onClick="addItem(22);">
<div class="value">$ 0.05</div>
<img class="smallimg" src="http://cdn.steamcommunity.com/economy/image/7xs5DOPUQVgttOnINvLH41dX872npE8Y-Xo60tIUj0QmEA73usgHSo1t9TYQkpttT1Co-q67Txz_cT3A0wKYTilSGv2rzABDnRzxPBPYiHxLRuPi6u4BBfNwDMCbUs4XGA4Ox7nMBUq2J_ktDuKNfElG9JLx4gcd6DBlgc5SmRYmGE6o_s4QSYgi9G4Z2Jl8CEbm-Ky8VUKqJ2qCzFLOQyUZUOijyg==/99fx66f" title="SG 553 | Waves Perforated (Field-Tested)">
<div class="rarity">Field-Tested</div>
</a>
</div>
<div class="item Restricted" id="item-21">
<a onClick="addItem(21);">
<div class="value">$ 11.40</div>
<img class="smallimg" src="http://cdn.steamcommunity.com/economy/image/7xs5DOPUQVgttOnINvLH41dX872npE8Y-Xo60tIUj0QmEA73usgHSo1t9TYQkpttT1Co-q67Txz_cT3A0wKYTilSGv2rzABDnRzxPBPYiHxLRuPi6u4BBfNwDMCbUs4XGA4Ox7nMBUq2J_ktDuKNfElG9JLx4gcd6DBlgc5SmRYmGE6o_s4QSYgi9G4Z2Jl8CEbm-Ky8VUKqJ2qCzFLOQyUZUOijyg==/99fx66f" title="SG 553 | Waves Perforated (Field-Tested)">
<div class="rarity">Field-Tested</div>
</a>
</div>
<div class="item Covert" id="item-20">
<a onClick="addItem(20);">
<div class="value">$ 7.65</div>
<img class="smallimg" src="http://cdn.steamcommunity.com/economy/image/7xs5DOPUQVgttOnINvLH41dX872npE8Y-Xo60tIUj0QmEA73usgHSo1t9TYQkpttT1Co-q67Txz_cT3A0wKYTilSGv2rzABDnRzxPBPYiHxLRuPi6u4BBfNwDMCbUs4XGA4Ox7nMBUq2J_ktDuKNfElG9JLx4gcd6DBlgc5SmRYmGE6o_s4QSYgi9G4Z2Jl8CEbm-Ky8VUKqJ2qCzFLOQyUZUOijyg==/99fx66f" title="SG 553 | Waves Perforated (Field-Tested)">
<div class="rarity">Field-Tested</div>
</a>
</div>
</div>
<!-- END ITEM HOLDER -->
<div id="selected" class="item-holder">
<h1>Selected Items</h1>
</div>
</div>
The first item works fine, You add the item, It updates the total.
Add a second item, It subtracts the new item value from the old one.
Remove the first item and it adds the value to the total.
It's a little messed up, it randomly adds and subtracts.
I'm really not sure why it's causing this, so I came here.
Any ideas what I'm doing what?
Thanks in advance!
CodePen
Inu, in addition to fixing the if(action = 0) bug, you might also like to consider the following :
attach click handlers in javascript, not as HTML attributes.
things will simplify with more carefully chosen jQuery selectors and method chaining.
by delegating click handling to static wrappers (#selected and #my), you can avoid the need to dynamically swap out 'addItem' and 'remItem'. The click action of each item will be automatically determined by the current wrapper.
in the click handlers, this refers to the clicked a element, therefore no need to rediscover it with a jQuery selector, and .closest() will avoid the need to find items by id.
to maintain a reliable total, you should really recalculate from scratch by looping through all items, rather than applying deltas.
by putting values in spans with the '$' outisde, you can get the values directly, without stripping out the symbol.
Put everything together and you should end up with something like this :
HTML
....
<div class="value">$ <span>11.40</span></div>
....
Javascript
$('#my').on('click', '.item a', function(e) {
e.preventDefault();
$(this).closest('.item').insertAfter("#selected h1");
calcTotal();
});
$('#selected').on('click', '.item a', function(e) {
e.preventDefault();
$(this).closest('.item').insertAfter("#my h1");
calcTotal();
});
function calcTotal(item, sign) {
var total = 0;
$("#selected .value span").each(function() {
total += Number($(this).text());
});
$(".total").text(total);
}
untested
You are using the assignment operator = here: if(action=0){ when you should be using the comparisson operator == as if(action==0){

Categories