jQuery Double-click event display pop-window with aggregated data? [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
How to display pop-window with aggregated data when Double-click event in jQuery?I use below code to get aggregated data, each quessionId has many related reasons. when I click/choose questionId button/event, OnClick select questionId and Double-click to remove/cancel, when OnClick select a questionId, related reasons dictonary will display below questionId, if Double-click remove that questionId, and related reasons dictonary will display in a `pop-windows' as below picture(User can click 'Confirmed' button after 5
seconds, when confimed, closed pop-windows automatically).
Below is my partial code of .js code in jQuery, all related data is fine by below code:
function fmtQuestionsByID(id,callback){
if(!DATA.questions[id] || !$('#card_'+id) )return;
var project = DATA.projects[DATA.questions[id].projectId];
if(!project)return;
var issueQuestionLists = DATA.alltags.reduce(function(a,b){
if(a[b['quessionId']]) {
a[b['quessionId']].push({name:b['name'],color:b['color'],description:b['description'],reason:b['reason'],question:b['question'],issueId:b['issueId'],department:b['department'],_id:b['quessionId']})
} else{
a[b['quessionId']] = [{name:b['name'],color:b['color'],description:b['description'],reason:b['reason'],question:b['question'],issueId:b['issueId'],department:b['department'],_id:b['quessionId']}]
}
return a;
},{});
var d = 0;
for(var i=0;i < DATA.questions[id].tags.length;i++){
var lid = DATA.questions[id].tags[i];
for(var l in issueQuestionLists){
var lb = issueQuestionLists[l]
for(var c=0;c< lb.length;c++){
var lc = lb[c];
if(lc._id == lid){
d++;
var info = lc;
console.log('info', info);
$('.tags_question').append(d + '['+info.name+']' + info.description + '。' + 'Reason: '+info.reason+ '。' ||'[no data]' );
}
}
}
}
}
Below code to OnClick to select and Double-click to remove.
function _fmtQuetionTags(){
fmtUsers( DATA.lastShowID ,function(html){
html = '<span class="add_plus_pic question projectinfo_addquestion" title="" href="#" aria-label=""><i class="fa fa-plus"></i></span>' + html;
$('#projectinfoUsers').html( html );
$('#projectinfoUsers .js-question').attr('title','Double-click remove question').unbind().on('dblclick',function(){
var id = $(this).data('id');
doSubmitSetQuestion(DATA.questionid,DATA.lastID,id,function () {
});
});
});
}
And I use below html to get above data
<div id="questioninfo">
<span class="tags_question"></span>
</div>

Based on your description, I created the following example code.
$(function() {
$("#showAlert").click(function() {
$(".alert.dialog").show("fast", function() {
setTimeout(function() {
$(".alert.dialog button[disabled]").prop("disabled", false);
}, 5000);
});
});
$(".ok.btn").click(function() {
$(this).closest(".dialog").hide("fast", function() {
$(".ok", this).prop("disabled", true);
});
});
$(".dialog li").click(function() {
$(this).removeClass("marked").addClass("selected");
}).dblclick(function() {
$(this).removeClass("selected").addClass("marked");
})
});
.alert {
width: 340px;
border: 1px solid #ccc;
border-radius: 6px;
padding: 0;
display: none;
}
.title {
width: 100%;
background: #eee;
text-align: center;
font-weight: bold;
border-bottom: 1px solid #ccc;
padding-top: 6px;
padding-bottom: 6px;
}
.response {
width: 95%;
margin-top: 10px;
padding-left: 6px;
}
.button-set {
width: 100%;
margin: 5px;
text-align: center;
}
.button-set .default {
font-weight: bold;
}
.selected {
background-color: #FF0;
}
.marked {
background-color: #F00;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="showAlert">Alert</button>
<div class="alert dialog">
<div class="title">Alert 1</div>
<div class="response">This is an alert description
<ul>
<li>Option 1</li>
</ul>
</div>
<div class="button-set">
<button class="ok btn default" disabled="disabled">Okay</button>
</div>
</div>
Hopefully this is similar to what you're doing and what type of functions you're trying to achieve. This example makes use of various methods, .click() and .dblclick(). It also uses setTimeout() in the callback for .show().
See More:
https://api.jquery.com/click/
https://api.jquery.com/dblclick/
https://api.jquery.com/show/
https://api.jquery.com/hide/
https://www.w3schools.com/jsref/met_win_settimeout.asp

Related

How to show/hide menu based on checkbox(s) value with JavaScript?

Update 10/4/18: I've updated the Snippet to reflected changes for anyone who may stumble upon this thread in seek of help. Existing check-boxes and newly added check-boxes will open/close the menu.
var statusChangeMenu, activeList, itemCheckBox, activeItems;
statusChangeMenu = document.getElementById("status-change-menu");
activeList = document.getElementById("active-items");
itemCheckBox = activeList.getElementsByClassName("item-checkbox");
activeItems = activeList.getElementsByClassName("active-item-text");
function addNewItem(event) {
event.preventDefault();
activeList.insertAdjacentHTML("afterbegin", "\
<li class=\"item\">\
<input class=\"item-checkbox\" type=\"checkbox\" name=\"checkbox\" />\
<span class=\"active-item-text\"></span>\
<button class=\"btn-complete\">complete</button>\
</li>");
activeItems[0].textContent = document.getElementById("new-item-text").value;
}
document.getElementById("btn-add-item").addEventListener("click", addNewItem, false);
activeList.addEventListener("change", function() {
var i, len;
for (i = 0, len = itemCheckBox.length; i < len || (i = 0); ++i) {
if (itemCheckBox[i].checked) {
i = 40;
break;
}
}
statusChangeMenu.style.height = i + "px";
}, false);
*{
margin: 0;
padding: 0;
}
body{
background-color: #393F4D;
}
header{
background-color: #1D1E22;
color: #FEDA6A;
text-align: center;
font-size: 10px;
}
main{
background-color: #707070;
max-width: 700px;
margin: auto;
margin-top: 20px;
padding: 15px;
}
#status-change-menu{
background-color: rgb(218, 123, 123);
margin-top: 10px;
height: 0px;
overflow: hidden;
transition: all .25s ease-in-out;
}
#status-change-menu>button>img{
height: 40px;
}
form{
background-color: #D4D4DC;
padding: 10px;
text-align: right;
box-shadow: 1px 1px 3px;
}
#new-item-text{
width: 100%;
}
#btn-add-item{
padding: 5px;
box-shadow: 1px 1px 3px;
}
.item-list-container{
background-color: #D4D4DC;
margin-top: 20px;
box-shadow: 1px 1px 3px;
}
.item{
background-color: rgb(165, 233, 222);
list-style: none;
display: grid;
grid-template-columns: auto 1fr max-content;
grid-template-rows: 30px;
margin-top: 10px;
}
.item-checkbox{
grid-column: 1/2;
width: 30px;
margin:auto;
}
.active-item-text{
grid-column: 2/3;
background: rgb(252, 252, 252);
overflow: hidden;
}
.btn-complete{
grid-column: 3/4;
}
.item>input{
height: 20px;
}
<body id="the-list">
<header>
<h1>The List V4</h1>
</header>
<main>
<form action="#">
<textarea name="textbox" id="new-item-text" cols="30" rows="1"></textarea>
<button type="submit" id="btn-add-item">Add</button>
</form>
<div id="status-change-menu" class="change-menu">
<h3>Status Change Menu</h3>
<button class="btn-bar-hold">BTN1<img src="img/btn_hold.svg" alt=""></button>
<button class="btn-bar-delete">BTN2<img src="img/btn_delete.svg" alt=""></button>
</div>
<div class="item-list-container">
<ul id="active-items" class="item-list">
<li class="item">
<input class="item-checkbox" type="checkbox" name="checkbox">
<span class="active-item-text">random text text random</span>
<button class="btn-complete">complete</button>
</li>
<li class="item">
<input class="item-checkbox" type="checkbox" name="checkbox">
<span class="active-item-text">random text text random</span>
<button class="btn-complete">complete</button>
</li>
</ul>
</div>
</main>
</body>
I'm working on a simple checklist web app using pure vanilla HTML, CSS, javascript. I've been stuck in one part all weekend. Hoping someone can shed some light on what I'm missing or doing wrong. Here's where I'm at.
My Goal
Whenever an item in the checklist (ul) is selected (via checkbox), a hidden menu slides out with various options to manipulate the selected item(s). The menu must stay visible if any of the checkboxes on the list are checked. The menu must close if no checkboxes are checked.
Where I'm Stuck
I'm able to get the menu to slide out during a 'change' event of the checkbox, but I can't get the menu element to react after the initial change event. During debugging, it also appears the menu element is not reacting to the checkbox is in a 'checked' state, but simply just reacting to the checkbox being changed in general. Here's the JS code I have, but I've tested various other configurations with no success.
Code Pen with Full Code & Snippet of related JS code below.
Updated Codepen 10/4/18
https://codepen.io/skazx/pen/mzeoEO?
var itemCheckBox = document.querySelectorAll('input[type="checkbox"]')
var statusChangeMenu = document.getElementById("status-change-menu")
for(var i = 0 ; i < itemCheckBox.length; i++){
itemCheckBox[i].addEventListener("change", function(){
if (!itemCheckBox.checked)
{statusChangeMenu.style.height = "40px";}
else
{statusChangeMenu.style.height = "0px";}
})}
I've read a few dozen different post and articles, but most were related to only having 1 checkbox or used jquery. Let me know if you need any further details. Thank you!
itemCheckBox refers to a NodeList returned by querySelectorAll, not an individual element, so saying itemCheckBox.checked doesn't really make sense.
You should be checking if any checkbox in the list is checked, which you can use with the .some() function, like so:
Here's a working demo
for (var i = 0; i < itemCheckBox.length; i++) {
itemCheckBox[i].addEventListener("change", function(event) {
if (!event.target.checked) {
statusChangeMenu.style.height = "40px";
} else {
statusChangeMenu.style.height = "0px";
}
});
}
var itemCheckBox = document.querySelectorAll('input[type="checkbox"]');
var statusChangeMenu = document.getElementById("status-change-menu");
function changeHandler (event) {
// get the list of checkboxes in real time in case any were added to the DOM
var checkboxes = document.querySelectorAll('input[type="checkbox"]');
var anyChecked = [].some.call(checkboxes, function(checkbox) { return checkbox.checked; });
// alternatively (instead of using .some()):
// var anyChecked = false;
// checkboxes.forEach(function (checkbox) {
// if (checkbox.checked) {
// anyChecked = true;
// }
// });
if (anyChecked) {
statusChangeMenu.style.height = "40px";
} else {
statusChangeMenu.style.height = "0px";
}
}
for (var i = 0; i < itemCheckBox.length; i++) {
itemCheckBox[i].addEventListener("change", changeHandler);
}
for (var i = itemCheckBox.length; i < itemCheckBox.length + 2; i++) {
// add some checkboxes dynamically
var newCheckbox = document.createElement("input");
var newLabel = document.createElement("label");
newLabel.innerText = "Checkbox " + (i + 1);
newCheckbox.type = "checkbox";
// -- IMPORTANT-- bind event listener on dynamically added checkbox
newCheckbox.addEventListener("change", changeHandler);
newLabel.appendChild(newCheckbox);
newLabel.appendChild(document.createElement("br"));
document.body.appendChild(newLabel);
}
#status-change-menu {
height: 0;
background-color: red;
overflow: hidden;
color: white;
font-weight: bold;
}
<div id="status-change-menu">I should be visible if any checkboxes are checked</div>
<label>Checkbox 1<input type="checkbox"/></label><br/>
<label>Checkbox 2<input type="checkbox"/></label><br/>
<label>Checkbox 3<input type="checkbox"/></label><br/>
mhodges is correct in that itemCheckBox is a NodeList, not an individual element. Another issue is that you are trying to test if the box that changed is checked, and if it isn't, you are closing the menu. As you described, that is not what you want.
You need another way to check to see if all check boxes are unchecked before you close the menu. A simple way to do that is just another inner loop in the onChange function:
for(var i = 0 ; i < itemCheckBox.length; i++){
itemCheckBox[i].addEventListener("change", function(){
showMenu = false
for(var j = 0; j < itemCheckBox.length; j++)
{
if(itemCheckBox[j].checked)
showMenu = true
}
if (showMenu)
{statusChangeMenu.style.height = "40px";}
else
{statusChangeMenu.style.height = "0px";}
})}
Heres a modified Snippet

onmouseover not working in option [duplicate]

I am trying to show a description when hovering over an option in a select list, however, I am having trouble getting the code to recognize when hovering.
Relevant code:
Select chunk of form:
<select name="optionList" id="optionList" onclick="rankFeatures(false)" size="5"></select>
<select name="ranks" id="ranks" size="5"></select>
Manipulating selects (arrays defined earlier):
function rankFeatures(create) {
var $optionList = $("#optionList");
var $ranks = $("#ranks");
if(create == true) {
for(i=0; i<5; i++){
$optionList.append(features[i]);
};
}
else {
var index = $optionList.val();
$('#optionList option:selected').remove();
$ranks.append(features[index]);
};
}
This all works. It all falls apart when I try to deal with hovering over options:
$(document).ready(
function (event) {
$('select').hover(function(e) {
var $target = $(e.target);
if($target.is('option')) {
alert('yeah!');
};
})
})
I found that code while searching through Stack Exchange, yet I am having no luck getting it to work. The alert occurs when I click on an option. If I don't move the mouse and close the alert by hitting enter, it goes away. If I close out with the mouse a second alert window pops up. Just moving the mouse around the select occasionally results in an alert box popping up.
I have tried targeting the options directly, but have had little success with that. How do I get the alert to pop up if I hover over an option?
You can use the mouseenter event.
And you do not have to use all this code to check if the element is an option.
Just use the .on() syntax to delegate to the select element.
$(document).ready(function(event) {
$('select').on('mouseenter','option',function(e) {
alert('yeah');
// this refers to the option so you can do this.value if you need..
});
});
Demo at http://jsfiddle.net/AjfE8/
try with mouseover. Its working for me. Hover also working only when the focus comes out from the optionlist(like mouseout).
function (event) {
$('select').mouseover(function(e) {
var $target = $(e.target);
if($target.is('option')) {
alert('yeah!');
};
})
})
You don't need to rap in in a function, I could never get it to work this way. When taking it out works perfect. Also used mouseover because hover is ran when leaving the target.
$('option').mouseover(function(e) {
var $target = $(e.target);
if($target.is('option')) {
console.log('yeah!');
};
})​
Fiddle to see it working. Changed it to console so you don't get spammed with alerts. http://jsfiddle.net/HMDqb/
That you want is to detect hover event on option element, not on select:
$(document).ready(
function (event) {
$('#optionList option').hover(function(e) {
console.log(e.target);
});
})​
I have the same issue, but none of the solutions are working.
$("select").on('mouseenter','option',function(e) {
$("#show-me").show();
});
$("select").on('mouseleave','option',function(e) {
$("#show-me").hide();
});
$("option").mouseover(function(e) {
var $target = $(e.target);
if($target.is('option')) {
alert('yeah!');
};
});
Here my jsfiddle https://jsfiddle.net/ajg99wsm/
I would recommend to go for a customized variant if you like to ease
capture hover events
change hover color
same behavior for "drop down" and "all items" view
plus you can have
resizeable list
individual switching between single selection and multiple selection mode
more individual css-ing
multiple lines for option items
Just have a look to the sample attached.
$(document).ready(function() {
$('.custopt').addClass('liunsel');
$(".custopt, .custcont").on("mouseover", function(e) {
if ($(this).attr("id") == "crnk") {
$("#ranks").css("display", "block")
} else {
$(this).addClass("lihover");
}
})
$(".custopt, .custcont").on("mouseout", function(e) {
if ($(this).attr("id") == "crnk") {
$("#ranks").css("display", "none")
} else {
$(this).removeClass("lihover");
}
})
$(".custopt").on("click", function(e) {
$(".custopt").removeClass("lihover");
if ($("#btsm").val() == "ssm") {
//single select mode
$(".custopt").removeClass("lisel");
$(".custopt").addClass("liunsel");
$(this).removeClass("liunsel");
$(this).addClass("lisel");
} else if ($("#btsm").val() == "msm") {
//multiple select mode
if ($(this).is(".lisel")) {
$(this).addClass("liunsel");
$(this).removeClass("lisel");
} else {
$(this).addClass("lisel");
$(this).removeClass("liunsel");
}
}
updCustHead();
});
$(".custbtn").on("click", function() {
if ($(this).val() == "ssm") {
$(this).val("msm");
$(this).text("switch to single-select mode")
} else {
$(this).val("ssm");
$(this).text("switch to multi-select mode")
$(".custopt").removeClass("lisel");
$(".custopt").addClass("liunsel");
}
updCustHead();
});
function updCustHead() {
if ($("#btsm").val() == "ssm") {
if ($(".lisel").length <= 0) {
$("#hrnk").text("current selected option");
} else {
$("#hrnk").text($(".lisel").text());
}
} else {
var numopt = +$(".lisel").length,
allopt = $(".custopt").length;
$("#hrnk").text(numopt + " of " + allopt + " selected option" + (allopt > 1 || numopt === 0 ? 's' : ''));
}
}
});
body {
text-align: center;
}
.lisel {
background-color: yellow;
}
.liunsel {
background-color: lightgray;
}
.lihover {
background-color: coral;
}
.custopt {
margin: .2em 0 .2em 0;
padding: .1em .3em .1em .3em;
text-align: left;
font-size: .7em;
border-radius: .4em;
}
.custlist,
.custhead {
width: 100%;
text-align: left;
padding: .1em;
border: LightSeaGreen solid .2em;
border-radius: .4em;
height: 4em;
overflow-y: auto;
resize: vertical;
user-select: none;
}
.custlist {
display: none;
cursor: pointer;
}
.custhead {
resize: none;
height: 2.2em;
font-size: .7em;
padding: .1em .4em .1em .4em;
margin-bottom: -.2em;
width: 95%;
}
.custcont {
width: 7em;
padding: .5em 1em .6em .5em;
/* border: blue solid .2em; */
margin: 1em auto 1em auto;
}
.custbtn {
font-size: .7em;
width: 105%;
}
h3 {
margin: 1em 0 .5em .3em;
font-weight: bold;
font-size: 1em;
}
ul {
margin: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>
customized selectable, hoverable resizeable dropdown with multi-line, single-selection and multiple-selection support
</h3>
<div id="crnk" class="custcont">
<div>
<button id="btsm" class="custbtn" value="ssm">switch to multi-select mode</button>
</div>
<div id="hrnk" class="custhead">
current selected option
</div>
<ul id="ranks" class="custlist">
<li class="custopt">option one</li>
<li class="custopt">option two</li>
<li class="custopt">another third long option</li>
<li class="custopt">another fourth long option</li>
</ul>
</div>

Chat with only javascript? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have been trying to make a chat in a long time, but I had no succes in making it.
I tried alot of ways, but making it insert the msg to my database and then with javascript refresh the chat every second, and get the msg from database, but that dosent work that well.
I was wondering is theire a way to make a chat with only javascript?
So it appends to a div all the users can see.
I saw some sites do this but I haven't been able to do it myself.
Yes - You can make a chat client that takes advantage of Websockets.
The only thing required is that you run a server in order to forward requests to other clients as they arrive.
The server can be written in a variety of different languages -- some of the most popular are C/C++ (Qt), node.js, Python, and go.
There are more languages which can provide this as ability as well ---
This came from http://www.tutorials.kode-blog.com/websocket-chat-client
var output;
var websocket;
function WebSocketSupport() {
if (browserSupportsWebSockets() === false) {
document.getElementById("ws_support").innerHTML = "<h2>Sorry! Your web browser does not supports web sockets</h2>";
var element = document.getElementById("wrapper");
element.parentNode.removeChild(element);
return;
}
output = document.getElementById("chatbox");
websocket = new WebSocket('ws:localhost:999');
websocket.onopen = function(e) {
writeToScreen("You have have successfully connected to the server");
};
websocket.onmessage = function(e) {
onMessage(e)
};
websocket.onerror = function(e) {
onError(e)
};
}
function onMessage(e) {
writeToScreen('<span style="color: blue;"> ' + e.data + '</span>');
}
function onError(e) {
writeToScreen('<span style="color: red;">ERROR:</span> ' + e.data);
}
function doSend(message) {
var validationMsg = userInputSupplied();
if (validationMsg !== '') {
alert(validationMsg);
return;
}
var chatname = document.getElementById('chatname').value;
document.getElementById('msg').value = "";
document.getElementById('msg').focus();
var msg = '#<b>' + chatname + '</b>: ' + message;
websocket.send(msg);
writeToScreen(msg);
}
function writeToScreen(message) {
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = message;
output.appendChild(pre);
}
function userInputSupplied() {
var chatname = document.getElementById('chatname').value;
var msg = document.getElementById('msg').value;
if (chatname === '') {
return 'Please enter your username';
} else if (msg === '') {
return 'Please the message to send';
} else {
return '';
}
}
function browserSupportsWebSockets() {
if ("WebSocket" in window) {
return true;
} else {
return false;
}
}
body {
font: 12px arial;
color: #222;
text-align: center;
padding: 35px;
}
#controls,
p,
span {
margin: 0;
padding: 0;
}
input {
font: 12px arial;
}
a {
color: #0000FF;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
#wrapper,
#loginform {
margin: 0 auto;
padding-bottom: 25px;
background: #66CCFF;
width: 504px;
border: 1px solid #ACD8F0;
}
#chatbox {
text-align: left;
margin: 0 auto;
margin-bottom: 25px;
padding: 10px;
background: #fff;
height: 270px;
width: 430px;
border: 1px solid #ACD8F0;
overflow: auto;
}
#chatname {
width: 395px;
border: 1px solid #ACD8F0;
margin-left: 25px;
float: left;
}
#msg {
width: 395px;
border: 1px solid #ACD8F0;
}
#submit {
width: 60px;
}
<!DOCTYPE html>
<html>
<head>
<title>WebSocket PHP Open Group Chat App</title>
<link type="text/css" rel="stylesheet" href="style.css" />
<script src="websocket_client.js"></script>
</head>
<body onload="javascript:WebSocketSupport()">
<div id="ws_support"></div>
<div id="wrapper">
<div id="menu">
<h3 class="welcome">Welcome to WebSocket PHP Open Group Chat App v1</h3>
</div>
<div id="chatbox"></div>
<div id="controls">
<label for="name"><b>Name</b>
</label>
<input name="chatname" type="text" id="chatname" size="67" placeholder="Type your name here" />
<input name="msg" type="text" id="msg" size="63" placeholder="Type your message here" />
<input name="sendmsg" type="submit" id="sendmsg" value="Send" onclick="doSend(document.getElementById('msg').value)" />
</div>
</div>
</body>
</html>

javascript object: variable global can not read in different function [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have this script
var b = {
c: {
a: document.querySelector(".a"),
init: function() {
this.a.style.backgroundColor = "red";
this.a.addEventListener("click", b.c.change);
},
change: function() {
this.a.style.width = "100px";
}
}
}
b.c.init();
.a {
width: 10px;
height: 10px;
background: black;
cursor: pointer;
}
<div class="a"></div>
Why this.a style "undefine"???
Inside the change event handler, this refers to the dom element. So just change this.a.style.... to this.style.... .
var b = {
c: {
a: document.querySelector(".a"),
init: function(){
this.a.style.backgroundColor="red";
this.a.addEventListener("click", b.c.change);
},
change: function(){
this.style.width="100px";
}
}
}
b.c.init();
.a {
width: 10px;
height: 10px;
background: black;
cursor: pointer;
}
<div class="a"></div>
First, in change event, this is pointing to DOM element and not object. So you can directly update style using this.
Second, inside a, this will point to c, so instead of b.c.change, you can directly do this.change
var b = {
c: {
a: document.querySelectorAll(".a"),
init: function() {
for (var i = 0; i < this.a.length; i++) {
this.a[i].style.backgroundColor = "red";
this.a[i].addEventListener("click", this.change);
}
},
change: function() {
console.log(this.innerHTML)
this.style.width = "100px";
}
}
}
b.c.init();
.a {
width: 10px;
height: 10px;
background: black;
cursor: pointer;
margin: 5px;
padding: 5px;
}
<div class="a">1</div>
<div class="a">2</div>
<div class="a">3</div>
<div class="a">4</div>
<div class="a">5</div>
Try once this will work..
var b = {
c: {
a: document.getElementById("a"),
init: function(){
this.a.style.backgroundColor="red";
this.a.addEventListener("click", b.c.change);
},
change: function(){
this.style.width="100px";
}
}
}
b.c.init();
#a {
width: 10px;
height: 10px;
background: black;
cursor: pointer;
}
<div id="a"></div>

Basic shopping cart using array.push(); [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I would like to make a basic shopping cart app in which you can click on items, every click should add the item to an array. At the end you should be able to press a total button and see all the items you have added, but so far it's not working.
Code so far:
function add() {
var shoppingCart = [];
document.getElementById("itemOne").addEventListener("click", function() {
shoppingCart.push("One");
});
document.getElementById("itemTwo").addEventListener("click", function() {
shoppingCart.push("Two")
});
document.getElementById("total").addEvenetListener("click", function() {
document.getElementById("display").innerHTML =
shoppingCart;
})
}
Jsfiddle: https://jsfiddle.net/xpb8oarx/
Typo # addEventListener
Never called add() you do not need that anyways
var shoppingCart = [];
document.getElementById("itemOne").addEventListener("click", function() {
shoppingCart.push("One");
});
document.getElementById("itemTwo").addEventListener("click", function() {
shoppingCart.push("Two");
});
document.getElementById("total").addEventListener("click", function() {
document.getElementById("display").innerHTML = shoppingCart;
});
.container {
width: 70%;
background-color: black;
height: 300px;
margin: 0 auto;
}
#itemOne,
#itemTwo {
width: 100px;
height: 100px;
border: 1px solid white;
margin: 1%;
color: white;
}
#display {
color: white;
text-align: center;
}
<div class="container">
<div id="itemOne" class="itemOne">
<button class=" item">Chicken</button>
</div>
<div id="itemTwo">
<button class="item">Veggies</button>
</div>
<button id="total">Total</button>
<h1 id="display"></h1>
</div>
You'll find a tutorial HERE which explain how to implement a cart in pure HTML5 and Vanilla.
Tuto written by a french JS ninja

Categories

Resources