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.
Related
I have a menu with drop down on hover and when clicked it should open a new page.
Here is the HTML;
<ul class=“Mainmenu” id=“Mainmenu”>
<li class=“dropdown”><a onclick=“window.location.reload()”>Home</a></li>
<li class=“dropdown”><a href=“Page1.html” onclick=“Loadpage(); return false;”>About us</a>
<ul class=“dropdown-menu” id=“menu1”>
<li class=“dropdownlink” id=“link1”><a href=“#”>Domestic</a></li>
<li class=“dropdownlink” id=“link2”><a href=“#”>International</a></li>
</ul>
</li>
<li class=“dropdown”><a onclick=“Loadteampage(); return false;”>Team</a></li>
</ul>
Here is the JavaScript:
function Loadpage(){
window.location.href=“Page1.html”;
}
function Loadteampage(){
window.location.href=“Team.html”;
}
Here is the CSS
.Mainmenu{
height: 15px;
font-family: Calibri;
font-size 12. 5px;
display: inline;
position: absolute;
width: 100%;
line-height: 15px;
text-align: center;
list-style: none;
top 18px;
}
.Mainmenu a{
float: left;
font-size: 14px;
color: #FAF6AF;
text-align: center;
padding: 5px 10px;
text-decoration: none;
height: 15px;
line -height: 15px;
transition: all 0.7s ease;
}
ul.Mainmenu > li{
float: left;
position: relative;
}
ul.Mainmenu li > a{
height: 15px;
line-height: 15px;
text-align: Center;
display: block;
background: #000000;
color: #FAF6AF;
white-space: nowrap;
}
ul.Mainmenu li:hover > a{
background-color: #FAF6AF;
color #000000;
cursor: pointer;}
ul.Mainmenu > li ul {
display: none;
position: absolute;
}
ul.Mainmenu > li:hover ul{
display: block;
cursor: pointer;
}
ul.Mainmenu > li ul li{
display: block;
position: relative;
top: 25px;
left: -40px;
}
.dropdownlink a{
text-align: center;
line-height: 15px;
font-size: 12.5px;
padding: 0px 0px 0px 0px;
margin: 0;
width: 100%;
}
The “About us” should act as dropdown when hovered on and act as link when clicked. But the onclick and href on “About us” is not working. Even I tried alert(); in onclick but it’s not working.
Please find the JSFIDDLE Link below:
JSFIDDLE
Can someone help me fix this issue?
Edited to include my favorite expand a list javascript
/*
CollapsibleLists.js
An object allowing lists to dynamically expand and collapse
Created by Stephen Morley - http://code.stephenmorley.org/ - and released under
the terms of the CC0 1.0 Universal legal code:
http://creativecommons.org/publicdomain/zero/1.0/legalcode
*/
// create the CollapsibleLists object
var CollapsibleLists =
new function(){
/* Makes all lists with the class 'collapsibleList' collapsible. The
* parameter is:
*
* doNotRecurse - true if sub-lists should not be made collapsible
*/
this.apply = function(doNotRecurse){
// loop over the unordered lists
var uls = document.getElementsByTagName('ul');
for (var index = 0; index < uls.length; index ++){
// check whether this list should be made collapsible
if (uls[index].className.match(/(^| )collapsibleList( |$)/)){
// make this list collapsible
this.applyTo(uls[index], true);
// check whether sub-lists should also be made collapsible
if (!doNotRecurse){
// add the collapsibleList class to the sub-lists
var subUls = uls[index].getElementsByTagName('ul');
for (var subIndex = 0; subIndex < subUls.length; subIndex ++){
subUls[subIndex].className += ' collapsibleList';
}
}
}
}
};
/* Makes the specified list collapsible. The parameters are:
*
* node - the list element
* doNotRecurse - true if sub-lists should not be made collapsible
*/
this.applyTo = function(node, doNotRecurse){
// loop over the list items within this node
var lis = node.getElementsByTagName('li');
for (var index = 0; index < lis.length; index ++){
// check whether this list item should be collapsible
if (!doNotRecurse || node == lis[index].parentNode){
// prevent text from being selected unintentionally
if (lis[index].addEventListener){
lis[index].addEventListener(
'mousedown', function (e){ e.preventDefault(); }, false);
}else{
lis[index].attachEvent(
'onselectstart', function(){ event.returnValue = false; });
}
// add the click listener
if (lis[index].addEventListener){
lis[index].addEventListener(
'click', createClickListener(lis[index]), false);
}else{
lis[index].attachEvent(
'onclick', createClickListener(lis[index]));
}
// close the unordered lists within this list item
toggle(lis[index]);
}
}
};
/* Returns a function that toggles the display status of any unordered
* list elements within the specified node. The parameter is:
*
* node - the node containing the unordered list elements
*/
function createClickListener(node){
// return the function
return function(e){
// ensure the event object is defined
if (!e) e = window.event;
// find the list item containing the target of the event
var li = (e.target ? e.target : e.srcElement);
while (li.nodeName != 'LI') li = li.parentNode;
// toggle the state of the node if it was the target of the event
if (li == node) toggle(node);
};
}
/* Opens or closes the unordered list elements directly within the
* specified node. The parameter is:
*
* node - the node containing the unordered list elements
*/
function toggle(node){
// determine whether to open or close the unordered lists
var open = node.className.match(/(^| )collapsibleListClosed( |$)/);
// loop over the unordered list elements with the node
var uls = node.getElementsByTagName('ul');
for (var index = 0; index < uls.length; index ++){
// find the parent list item of this unordered list
var li = uls[index];
while (li.nodeName != 'LI') li = li.parentNode;
// style the unordered list if it is directly within this node
if (li == node) uls[index].style.display = (open ? 'block' : 'none');
}
// remove the current class from the node
node.className =
node.className.replace(
/(^| )collapsibleList(Open|Closed)( |$)/, '');
// if the node contains unordered lists, set its class
if (uls.length > 0){
node.className += ' collapsibleList' + (open ? 'Open' : 'Closed');
}
}
}();
the Html recommended is
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Vakram Mohan Help</title>
<link rel="stylesheet" href="reset.css" />
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:regular,bold,italic,thin,light,bolditalic,black,medium&lang=en">
<script type="text/javascript" src="CollapsibleLists.js"></script>
</head>
<body>
<div>
<UL id="Mainmenu">
<li>
<h2><span>Menu</span></h2>
<ul>
<li> <span><a onclick=“window.location.reload()”>Home</a></span></li>
<li><span>About us</span>
<ul>
<li><span><a href=“#”>Domestic</a></span></li>
<li><span><a href=“#”>International</a></span></li>
</ul>
</li>
</ul>
</li><!--Menu end -->
</UL> <!-- Main Menu end -->
</body>
<script language="javascript" type="text/javascript">
function btntest_onclick()
{
window.location.href = "http://www.google.com";
}
</script>
<script>
CollapsibleLists.applyTo(document.getElementById('Mainmenu'));
</script>
</head>
</html>
Notice i am not using your CSS file.
it was a mess
#para1 {
text-align: center;
color: red;
}
that is a ID selector
.center {
text-align: center;
color: red;
}
that is a Class selector.
Reset.css is here
html, body, header, footer, hgroup, nav, main, article, section, figure, figcaption, h1, h2, h3, ul, li, body, div, p, img
{
margin: 0;
padding: 0;
font-size: 100%;
vertical-align: baseline;
border: 0;
}
There are random number of div's as show below, I am trying to clone these div on click. when cloning I want to change the content to actual content + no of clones it has (based on content of span , not the id or classes of "clone-this")
eg.
If I click the first "chrome" div, since the body already have "chrome (1) and chrome (2)" , div with content "chrome (3)" Should appear .
If I click the 2nd div ie. "Mozilla Firefox", since there is no cloned version, a div with content "Mozilla Firefox (1)" should appear.
and so on.
I tried to make this, but when i clone the count is based on class , not the content . so clicking on "chrome" div will clone "chrome (5)" not "chrome (3)" .
Also in my implementation when i click the "chrome (1)" div, it will clone as "chrome (1)(5)" . I want this to be like "chrome (3)"
how can i achieve this?
note that there will be any number of divs at first. 5 is just for and example.
jsfiddle here
$(document).on('click', '.clone-this', function(){
var CloneContainer = $(this).clone();
var no = $('.clone-this').size();
CloneContainer.html(CloneContainer.html() + " (" + no + ")");
CloneContainer.appendTo('body');
});
.clone-this{
padding: 15px;
width: 100px;
text-align: center;
border: 1px solid #ccc;
margin: 10px auto;
cursor: pointer;
color: #444;
border: 1px solid #ccc;
border-radius: 3px;
font-family: monospace;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="clone-this"><span>Chrome</span></div>
<div class="clone-this"><span>Mozilla Firefox</span></div>
<div class="clone-this"><span>Safari</span></div>
<div class="clone-this"><span>Chrome (1)</span></div>
<div class="clone-this"><span>Chrome (2)</span></div>
To accomplish that, you should check "content" of each item and count the number of elements which have same text. But, there is one problem here; each element (for example Chrome, Chrome (1), Chrome (2)) has different content. So, you may split the text using parenthesis or you may use RegEx (recommended).
$(document).on('click', '.clone-this', function(){
var CloneContainer = $(this).clone();
var content = CloneContainer.find('span').html().split(' (')[0];
var no = $(".clone-this:contains('"+content+"')").size();
CloneContainer.html( CloneContainer.html() .split(' (')[0] + " (" + no + ")" );
CloneContainer.appendTo('body');
});
.clone-this{
padding: 15px;
width: 100px;
text-align: center;
border: 1px solid #ccc;
margin: 10px auto;
cursor: pointer;
color: #444;
border: 1px solid #ccc;
border-radius: 3px;
font-family: monospace;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="clone-this"><span>Chrome</span></div>
<div class="clone-this"><span>Mozilla Firefox</span></div>
<div class="clone-this"><span>Safari</span></div>
<div class="clone-this"><span>Chrome (1)</span></div>
<div class="clone-this"><span>Chrome (2)</span></div>
On the snippet above, you may see basic version of it. But you MUST consider the "similar content" issue like following.
Chrome
Chrome Mobile
Firefox
Firefox Mobile
Here is another way to get you going. I "trim" the clicked div to its base name and then loop through the divs and get the length of all which contain the same base name.
After that I modify the cloned element to fill in the right count of the cloned element appropriately:
var regExp = /\([0-9]+\)/;
$('.clone-this').click(function(e){
var target = e.target.textContent;
var matches = regExp.exec(target);
var elements = $('.clone-this');
var count = elements.length;
var index = 0;
if (null != matches) {
target = matches.input.substr(0, matches.input.lastIndexOf(" "));
}
for(var i = 0; i < count; i++){
index += (elements[i].textContent.indexOf(target) > -1) ? 1: 0;
}
var CloneContainer = $(this).clone();
CloneContainer.html(CloneContainer.html().split('(')[0] + "(" + index + ")" );
CloneContainer.appendTo('body');
});
.clone-this{
padding: 15px;
width: 100px;
text-align: center;
border: 1px solid #ccc;
margin: 10px auto;
cursor: pointer;
color: #444;
border: 1px solid #ccc;
border-radius: 3px;
font-family: monospace;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="clone-this"><span>Chrome</span></div>
<div class="clone-this"><span>Mozilla Firefox</span></div>
<div class="clone-this"><span>Safari</span></div>
<div class="clone-this"><span>Chrome (1)</span></div>
<div class="clone-this"><span>Chrome (2)</span></div>
How do I loop through two PARENT-CHILD-relationship (on simple ID PKEY and FKEY) JSON files and display them as a list of divs that are:
hierarchical - where child/FKEY divs only appear under the parent/PKEY div (show up as parent-child-child, parent-child-child-child, etc.)
expandable - these child/FKEY divs are display:none until you click the parent/PKEY div; i.e., items appear/disappear when you click the PKEY div, using jQuery's $(panelID).slideToggle(speed) method
able to be toggled with a separate checkbox div if the last key-value pair in the parent div OR child div exists and has key="DEPRECATED"
sortable - Just Kidding
jQuery offers me both parseJSON and cool display functions, and I give it atrociously horrible JS-debugging skills in return.
Edit: Here are the two JSON files in question:
types.json:
{"objtype":[{"NAME":"Animal","ID":"15","DEPRECATED":""},{"NAME":"Vegetable","ID":"8"},{"NAME":"Mineral","ID":"2","DEPRECATED":""}]}
objs.json:
{"objinstance":[{"DATEBOUGHT":"2014-08-26 00:00:00.0","OBJTYPEID":"8","OBJNAME":"Fruit salad consisting of oranges and mangoes","OBJID":"454","DATEEXPIRES":"2014-09-01 00:00:00.0","DEPRECATED":""},{"DATEBOUGHT":"2014-08-26 00:00:00.0","OBJTYPEID":"8","OBJNAME":"Spicy V-8 juice","OBJID":"499","DATEEXPIRES":"2015-01-02 00:00:00.0"},{"DATEBOUGHT":"2014-08-26 00:00:00.0","OBJTYPEID":"2","OBJNAME":"Rental agreement for new apartment","OBJID":"2885","DATEEXPIRES":"2015-08-25 00:00:00.0"},{"DATEBOUGHT":"2014-08-26 00:00:00.0","OBJTYPEID":"2","OBJNAME":"Salt","OBJID":"1033","DATEEXPIRES":"","DEPRECATED":""},{"DATEBOUGHT":"","OBJTYPEID":"15","OBJNAME":"Koko the Monkey","OBJID":"68","DATEEXPIRES":"","DEPRECATED":""},{"DATEBOUGHT":"","OBJTYPEID":"15","OBJNAME":"Bubbles the Clown","OBJID":"69","DATEEXPIRES":"","DEPRECATED":""}]}
Here is an extremely simple example of how you could generate HTML markup based on your data in JSON.
Algorithm:
Parse JSON string into Javascript objects
Iterate parent data
For each parent data, create parent div and add required content into it.
Iterate child data, search for common id
For each child data which matches the parent id, create child div, add required content into it, and finally append to the parent div
Append parent div to a container or body
Rinse, lather, repeat
Create CSS styles as per your taste
.
Demo Fiddle: http://jsfiddle.net/abhitalks/h3nbwc1f/
Snippet:
var typesString = '{"objtype":[{"NAME":"Animal","ID":"15","DEPRECATED":""},{"NAME":"Vegetable","ID":"8"},{"NAME":"Mineral","ID":"2","DEPRECATED":""}]}';
var objsString = '{"objinstance":[{"DATEBOUGHT":"2014-08-26 00:00:00.0","OBJTYPEID":"8","OBJNAME":"Fruit salad consisting of oranges and mangoes","OBJID":"454","DATEEXPIRES":"2014-09-01 00:00:00.0","DEPRECATED":""},{"DATEBOUGHT":"2014-08-26 00:00:00.0","OBJTYPEID":"8","OBJNAME":"Spicy V-8 juice","OBJID":"499","DATEEXPIRES":"2015-01-02 00:00:00.0"},{"DATEBOUGHT":"2014-08-26 00:00:00.0","OBJTYPEID":"2","OBJNAME":"Rental agreement for new apartment","OBJID":"2885","DATEEXPIRES":"2015-08-25 00:00:00.0"},{"DATEBOUGHT":"2014-08-26 00:00:00.0","OBJTYPEID":"2","OBJNAME":"Salt","OBJID":"1033","DATEEXPIRES":"","DEPRECATED":""},{"DATEBOUGHT":"","OBJTYPEID":"15","OBJNAME":"Koko the Monkey","OBJID":"68","DATEEXPIRES":"","DEPRECATED":""},{"DATEBOUGHT":"","OBJTYPEID":"15","OBJNAME":"Bubbles the Clown","OBJID":"69","DATEEXPIRES":"","DEPRECATED":""}]}';
var types = JSON.parse(typesString);
var objs = JSON.parse(objsString);
types.objtype.forEach(function(item, idx) {
var $parent = $("<div class='parent' />");
var $label = $("<label>").text(item.ID + ': ' + item.NAME).attr('for', 'c' + idx);
var $input = $('<input type="checkbox">').attr('id', 'c' + idx);
$parent.append($label);
$parent.append($input);
objs.objinstance.forEach(function(item2) {
if (item2.OBJTYPEID == item.ID) {
var $child = $("<div class='child' />");
var txt2 = item2.OBJID + ': ' + item2.OBJNAME;
$child.text(txt2);
$parent.append($child);
}
});
$("#wrap").append($parent);
});
div#wrap {
font-family: helvetica, sans-serif;
font-size: 17px;
}
div.parent {
border: 1px solid blue;
padding: 8px; margin: 4px;
}
div.child {
border: 1px solid green;
font-size: 15px;
padding: 0px; margin: 0px;
opacity: 0; height: 0px;
transition: all 250ms;
}
label {
cursor: pointer;
}
input[type=checkbox] {
display: none;
}
input[type=checkbox]:checked ~ div.child {
padding: 8px; margin: 8px;
opacity: 1; height: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrap"></div>
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){
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