Javascript dropdown menu delete event bug - javascript

first of all, I am just a beginner on javascript. and I am trying to coding a todo-list application, I ran into a problem with the deleting future that located in every task. When I try to delete specific task on the application, the application has to compare the id information and delete the task in the relevant id,but aplication not work well, no matter which task I click, it deletes it sequentially from beginning to end.
I also tried with the for-in loop as a solution, but I still got the same result. Where am I going wrong? can you help me?
<!DOCTYPE html>
<html lang="en">
<head>
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap#4.3.1/dist/css/bootstrap.min.css"
/>
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.2/css/all.min.css"
/>
<style>
.dropdown-toggle::after {
display:none;
}
.task {
display: flex;
align-items: center;
justify-content: space-between;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-12">
<div class="card-header">Todo List</div>
<div class="card-body">
<form>
<div class="input-group">
<input
type="text"
name="txtTaskName"
id="txtTaskName"
class="form-control"
/>
<button
type="button"
class="btn btn-primary"
id="btnAddNewTask"
>
Ekle
</button>
</div>
</form>
</div>
<div class="card mt-3">
<div class="card-header">
<button
class="btn btn-danger btn-sm float-sm-right"
id="btnDeleteTask"
>
Temizle
</button>
</div>
<ul class="list-group list-group-flush" id="task-list"></ul>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js"></script>
<script>
dynamicList = [
{ Id: 1, gorevAdi: "Görev 1" },
{ Id: 2, gorevAdi: "Görev 2" },
{ Id: 3, gorevAdi: "Görev 3" },
];
displayTasks();
function displayTasks() {
let = ul = document.getElementById("task-list");
ul.innerHTML = "";
for (let index of dynamicList) {
let li = `
<li class="list-group-item task">
<div class="form-check">
<input type="checkbox" id="${index.Id}" class="form-check-input">
<label for="${index.Id}" class="form-check-label">${index.gorevAdi}</label>
</div>
<div class="dropdown">
<button class="btn btn-link dropdown-toggle" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown" aria-expanded="false">
<i class="fas fa-ellipsis-h"></i>
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenuButton1">
<li><a onclick = "deleteTask(${index.Id})" class="dropdown-item" href="#"><i class="fas fa-trash-alt"></i> Delelte</a></li>
<li><a class="dropdown-item" href="#"><i class="fas fa-pen"></i> Edit here</a></li>
</ul>
</div>
</li>`;
ul.insertAdjacentHTML("beforeend", li);
}
}
document
.querySelector("#btnAddNewTask")
.addEventListener("click", newTask);
document
.querySelector("#txtTaskName")
.addEventListener("keypress", function (event) {
if (event.key == "Enter") {
event.preventDefault();
document.getElementById("btnAddNewTask").click();
}
});
function newTask(event) {
let taskInput = document.querySelector("#txtTaskName");
if (taskInput.value == "") {
alert("Todo' ya bir içerik girmelisiniz.");
} else {
dynamicList.push({
Id: dynamicList.lenght + 1,
gorevAdi: taskInput.value,
});
taskInput.value = " ";
displayTasks();
}
event.preventDefault();
}
function deleteTask(id) {
let deletedId;
for (let i of dynamicList) {
if (i.id = id) {
deletedId = i
}
}
dynamicList.splice(deletedId, 1);
displayTasks()
}
</script>
</body>
</html>
In this section I add function that create tasks and togle menus on tasks
function displayTasks() {
let = ul = document.getElementById("task-list");
ul.innerHTML = "";
for (let index of dynamicList) {
let li = `
<li class="list-group-item task">
<div class="form-check">
<input type="checkbox" id="${index.Id}" class="form-check-input">
<label for="${index.Id}" class="form-check-label">${index.gorevAdi}</label>
</div>
<div class="dropdown">
<button class="btn btn-link dropdown-toggle" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown" aria-expanded="false">
<i class="fas fa-ellipsis-h"></i>
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenuButton1">
<li><a onclick = "deleteTask(${index.Id})" class="dropdown-item" href="#"><i class="fas fa-trash-alt"></i> Delelte</a></li>
<li><a class="dropdown-item" href="#"><i class="fas fa-pen"></i> Edit here</a></li>
</ul>
</div>
</li>`;
ul.insertAdjacentHTML("beforeend", li);
}
}
In this section I create delete task function
}
function deleteTask(id) {
let deletedId;
for (let i of dynamicList) {
if (i.id = id) {
deletedId = i
}
}
dynamicList.splice(deletedId, 1);
displayTasks()
}

Related

Why does my delete button does not delete the card

I want to delete the card when we click on the delete button after adding a TODO note
I have created a website which uses localstorage to store notes and display when clicking the create TODO button and it all works but when I click the delete button after the note is created (You have to create a TODO first) it does not delete the div itself
I want to delete the card when we click on the delete button
CODE:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TODO List</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
<style>
.main-title {
text-align: center;
}
.input {
border: 2px solid grey;
}
.all-todo {
display: flex;
margin: 30px;
}
</style>
</head>
<body>
<nav class="navbar navbar-expand-lg bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="#">TODO List</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse"
data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false"
aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
</ul>
<form class="d-flex" role="search">
<input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success" type="submit">Search</button>
</form>
</div>
</div>
</nav>
<h1 class="main-title">TODO List</h1>
<div class="container">
<div class="mb-3">
<label for="exampleFormControlInput1" class="form-label">Task Name</label>
<input type="text" class="form-control input" id="exampleFormControlInput1">
</div>
<div class="mb-3">
<label for="exampleFormControlTextarea1" class="form-label">Task Details</label>
<textarea class="form-control input" id="exampleFormControlTextarea1" rows="3"></textarea>
</div>
<button type="submit" class="btn btn-primary" id="main-btn">Create TODO</button>
<button type="button" class="btn btn-warning" id="clr">Clear LocalStorage</button>
</div>
<div class="all-todo"></div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.2/dist/js/bootstrap.bundle.min.js"
integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3"
crossorigin="anonymous"></script>
</body>
<script>
let button = document.getElementById("main-btn")
button.onclick = () => {
let key = document.getElementById("exampleFormControlInput1").value
let value = document.getElementById("exampleFormControlTextarea1").value
if (key != "" && value != "") {
iHTML = ""
localStorage.setItem(key, value)
iHTML += `
<div class="card" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title">${key}</h5>
<p class="card-text">${localStorage.getItem(key)}</p>
<button type="button" id="note" onclick='${key}.innerHTML=""' class="btn btn-danger '${key}'">Delete</button>
</div>
</div>
`
document.getElementsByClassName("all-todo")[0].innerHTML += iHTML
}
else {
alert("Task Name or Details cannot be empty!")
}
}
let clr_btn = document.getElementById("clr")
clr_btn.onclick = () => {
localStorage.clear()
}
</script>
</html>
The error is thrown on this line onclick='${key}.innerHTML=""'. You will want to first remove the item from local storage e.g: localStorage.removeItem('${key}') and then remove the html. Theres many way of achieveing this but this.parentElement.parentElement.remove() should be sufficient
The complete button should look something like <button type="button" id="note" onclick="localStorage.removeItem('${key}'); this.parentElement.parentElement.remove()" class="btn btn-danger '${key}'">Delete</button>
Heres a working example:
https://jsfiddle.net/qt83bshd/
Well, i post you a simple solution for your problem.
Instead of use innerhtml to introuce your todos, yo can create the elements.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TODO List</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
<style>
.main-title {
text-align: center;
}
.input {
border: 2px solid grey;
}
.all-todo {
display: flex;
margin: 30px;
}
/* add css in this poiint to optimize code*/
.card {
width: 18rem;
}
</style>
</head>
<body>
<nav class="navbar navbar-expand-lg bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="#">TODO List</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse"
data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false"
aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
</ul>
<form class="d-flex" role="search">
<input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success" type="submit">Search</button>
</form>
</div>
</div>
</nav>
<h1 class="main-title">TODO List</h1>
<div class="container">
<div class="mb-3">
<label for="exampleFormControlInput1" class="form-label">Task Name</label>
<input type="text" class="form-control input" id="exampleFormControlInput1">
</div>
<div class="mb-3">
<label for="exampleFormControlTextarea1" class="form-label">Task Details</label>
<textarea class="form-control input" id="exampleFormControlTextarea1" rows="3"></textarea>
</div>
<button type="submit" class="btn btn-primary" id="main-btn">Create TODO</button>
<button type="button" class="btn btn-warning" id="clr">Clear LocalStorage</button>
</div>
<div class="all-todo"></div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.2/dist/js/bootstrap.bundle.min.js"
integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3"
crossorigin="anonymous"></script>
</body>
<script>
let button = document.getElementById("main-btn")
button.onclick = () => {
// collect the div that contains all the todos
let alltodo = document.querySelector(".all-todo");
let key = document.getElementById("exampleFormControlInput1").value
let value = document.getElementById("exampleFormControlTextarea1").value
// and if it any todo create the card
if (key != "" && value != "") {
localStorage.setItem(key, value)
// with create element we can create the card more easy
var todo = document.createElement("div");
todo.setAttribute("class", "card");
var button = document.createElement("button");
button.textContent = "eliminar";
var titulo = document.createElement("h5");
titulo.textContent = key;
button.onclick = () => {
console.log(button.parentElement.remove())
// in this point we can also remove the todo from the local storage wih localstorage.removeItem()
}
// introduce all items in dom
todo.appendChild(titulo)
todo.appendChild(button);
alltodo.appendChild(todo);
// iHTML = ""
// localStorage.setItem(key, value)
// iHTML += `
// <div class="card" style="width: 18rem;">
// <div class="card-body">
// <h5 class="card-title">${key}</h5>
// <p class="card-text">${localStorage.getItem(key)}</p>
// <button type="button" id="note" onclick='${key}.innerHTML=""' class="btn btn-danger '${key}'">Delete</button>
// </div>
// </div>
// `
// document.getElementsByClassName("all-todo")[0].innerHTML += iHTML
}
else {
alert("Task Name or Details cannot be empty!")
}
}
let clr_btn = document.getElementById("clr")
clr_btn.onclick = () => {
localStorage.clear()
}
</script>
</html>

javascript Array Error inside object,cant access push of undefine

Here error is coming is can't access a property of undefined, In this.dataLog when I'm trying to push something in it. Please resolve the same. It is showing this.dataLog array as undefined.Here error is coming is can't access a property of undefined, In this.dataLog when I'm trying to push something in it. Please resolve the same. It is showing this.dataLog array as undefined.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://kit.fontawesome.com/9147344c85.js" crossorigin="anonymous" defer></script>
<!-- <link href="https://unpkg.com/tailwindcss#^1.0/dist/tailwind.min.css" rel="stylesheet"> -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<link rel="stylesheet" href="index.css">
<script src="index.js" type="text/javascript" defer></script>
<title>Document</title>
</head>
<body>
<div class="alert alert-success height" role="alert">
<img src="https://source.unsplash.com/random/70x100" id="main-img" class="">
<span>NatureFresh.com</span>
</div>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a id="login-link" class="navbar-brand" href="#">Login</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false">
Dropdown
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#">Something else here</a>
</div>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
</nav>
<div class="dropdown">
<a class="btn btn-secondary dropdown-toggle side-anchor" href="#" role="button" id="dropdownMenuLink"
data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Important links
</a>
<div id="login-back">
<form id="login">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" aria-describedby="basic-addon1" placeholder="Username">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Email">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control"placeholder="Password" id="exampleInputPassword1">
</div>
<div class="form-group form-check">
<input type="checkbox" class="form-check-input" id="exampleCheck1">
<label class="form-check-label" for="exampleCheck1">Check me out</label>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
<div class="alert alert-success sucessful" role="alert">
<h4 class="alert-heading">Welcome Back!</h4>
<hr>
<p></p>
</div>
<div class="dropdown-menu inside-anchor" aria-labelledby="dropdownMenuLink">
<a class="dropdown-item" href="https://www.facebook.com/">Facebook</a>
<a class="dropdown-item" href="#">Twitter</a>
<a class="dropdown-item" href="#">Gmail</a>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js"
integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"
integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI"
crossorigin="anonymous"></script>
</body>
</html>
class LoginDisplay {
constructor() {
this.dataLog=[];
}
render() {
// let loginLink = document.querySelector("#login-link");
let loginBack = document.querySelector("#login-back");
let loginForm = document.querySelector("#login");
let inputName = document.querySelector("#name");
let inputEmail = document.querySelector("input[type=\"email\"]");
let inputPassword = document.querySelector("input[type=\"password\"]");
loginBack.classList.toggle("visible");
loginForm.classList.toggle("visible");
inputName.value = "";
inputEmail = "";
inputPassword = "";
}
validation() {
let loginForm = document.querySelector("#login");
let loginBack = document.querySelector("#login-back");
let sucessAlert = document.querySelector("div[class=\"alert alert-success sucessful\"]");
let inputName = document.querySelector("#name");
let inputEmail = document.querySelector("input[type=\"email\"]");
let inputPassword = document.querySelector("input[type=\"password\"]");
let patt = /^[A-Za-z0-9]{2,}#[a-zA-Z0-9]{1,10}.com$/;
let para = sucessAlert.querySelector("p");
if (patt.test(inputEmail.value) && inputPassword.value === "dhawan") {
loginBack.classList.toggle("visible");
loginForm.classList.toggle("visible");
para.innerHTML = `<h4>Namste! ${inputName.value} <i class="fas fa-check"></i></h4>`;
inputName.value = "";
inputEmail = "";
inputPassword = "";
sucessAlert.classList.toggle("visible");
debugger;
this.dataLog.push(para);
}
// else{
// para.innerHTML=`<h4>`
// }
}
ve(){
console.log(this.dataLog.push("Sudhir"));
}
}
let login = new LoginDisplay();
let loginLink = document.querySelector("#login-link");
let btn= document.querySelectorAll("button[type=\"submit\"]")[1];
loginLink.addEventListener("click", login.render);
btn.addEventListener("click",login.validation)
This is the solution to your problem, but I think it has many ways to do it.
class LoginDisplay {
constructor() {
this.dataLog = [];
}
render() {
// let loginLink = document.querySelector("#login-link");
let loginBack = document.querySelector("#login-back");
let loginForm = document.querySelector("#login");
let inputName = document.querySelector("#name");
let inputEmail = document.querySelector('input[type="email"]');
let inputPassword = document.querySelector('input[type="password"]');
loginBack.classList.toggle("visible");
loginForm.classList.toggle("visible");
inputName.value = "";
inputEmail = "";
inputPassword = "";
}
validation() {
let loginForm = document.querySelector("#login");
let loginBack = document.querySelector("#login-back");
let sucessAlert = document.querySelector(
'div[class="alert alert-success sucessful"]'
);
let inputName = document.querySelector("#name");
let inputEmail = document.querySelector('input[type="email"]');
let inputPassword = document.querySelector('input[type="password"]');
let patt = /^[A-Za-z0-9]{2,}#[a-zA-Z0-9]{1,10}.com$/;
let para = sucessAlert.querySelector("p");
let a = patt.test(inputEmail.value) && inputPassword.value === "dhawan";
console.log(!a);
if (!a) {
loginBack.classList.toggle("visible");
loginForm.classList.toggle("visible");
para.innerHTML = `<h4>Namste! ${inputName.value} <i class="fas fa-check"></i></h4>`;
inputName.value = "";
inputEmail = "";
inputPassword = "";
sucessAlert.classList.toggle("visible");
//debugger;
return para;
}
// else{
// para.innerHTML=`<h4>`
// }
}
ve() {
console.log(this.dataLog.push("Sudhir"));
}
}
let login = new LoginDisplay();
let loginLink = document.querySelector("#login-link");
let btn = document.querySelectorAll('button[type="submit"]')[1];
loginLink.addEventListener("click", login.render);
btn.addEventListener("click", () => {
if (login.validation) {
let result = login.validation();
login.dataLog.push(result);
console.log(login.dataLog); // Here you have your element tag HTML in your Array!
}
});

Change class after changing list

I have a dual list in which data is printing a ul li pattern from a JSON file. You can move any li to any side list. I am stuck at a point.
I want to enable a property that the <p> tag content only in <li> in right-list gets display: block and not the left-list side <li>. I have tried different JS code but they didn't work for me .
$('.content').hide();
$('.listelement').on('click', function() {
if (!($(this).children('.content').is(':visible'))) {
$('.content').slideUp();
$(this).children('.content').slideDown();
} else {
$('.content').slideUp();
}
});
$(function() {
$('body').on('click', '.show', function() {
css("display", "block");
});
$('body').on('click', '.list-group .list-group-item', function() {
$(this).toggleClass('active');
});
$('.listarrows button').click(function() {
var $button = $(this),
actives = '';
if ($button.hasClass('move-left')) {
actives = $('.list-right ul li.active');
actives.clone().appendTo('.list-left ul');
actives.remove();
} else if ($button.hasClass('move-right')) {
actives = $('.list-left ul li.active');
actives.clone().appendTo('.list-right ul');
actives.remove();
}
});
$('[name="SearchDualList"]').keyup(function(e) {
var code = e.keyCode || e.which;
if (code == '9') return;
if (code == '27') $(this).val(null);
var $rows = $(this).closest('.dual-list').find('.list-group li');
var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();
$rows.show().filter(function() {
var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
return !~text.indexOf(val);
}).hide();
});
});
$(function() {
var ctList = [];
var ctRight = [];
var $tBody = $("#La");
var $rbody = $("#accordian");
$.getJSON('https://api.myjson.com/bins/d6n2a', function(data) {
data.topic_info.qt_ct_connection.map(value => {
value.ct_list.forEach(CTLIST => {
$tBody.append(`<li class="list-group-item" id="rl">${CTLIST.ct}<p style="display: none" class="show">
Simple collapsible
<div id="demo_${CTLIST.ct}" class="collapse">
${CTLIST.tts}, ${CTLIST.topic_level}, ${CTLIST.to_be_shown_individually}, ${CTLIST.check_for_geometry}
</div>
</p>
</li>`);
});
})
})
})
.ctList {
padding-top: 20px;
}
.ctList .dual-list .list-group {
margin-top: 8px;
}
.ctList .list-left li,
.list-right li {
cursor: pointer;
}
.ctList .list-arrows {
padding-top: 100px;
}
.ctList .list-arrows button {
margin-bottom: 20px;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.0/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class="ctList">
<div class="container">
<div class="row">
<div class="dual-list list-left col-md-5">
<div class="well text-right">
<div class="row">
<div class="col-md-10">
<div class="input-group">
<span class="input-group-addon glyphicon glyphicon-search">
<i class="fa fa-search" aria-hidden="true" style="padding-right: 20px;"></i>
</span>
<input type="text" name="SearchDualList" class="form-control" placeholder="search" />
</div>
</div>
<div class="col-md-2">
<div class="btn-group">
<a class="btn btn-default selector" title="select all">
<i class="glyphicon glyphicon-unchecked"></i>
</a>
</div>
</div>
</div>
<ul class="list-group" id="La"></ul>
</div>
</div>
<div class="list-arrows col-md-1 text-center">
<button class="btn btn-default btn-sm move-left">
<span class="glyphicon glyphicon-chevron-left">
<i class="fa fa-arrow-left" aria-hidden="true"></i>
</span>
</button>
<button class="btn btn-default btn-sm move-right">
<span class="glyphicon glyphicon-chevron-right">
<i class="fa fa-arrow-right" aria-hidden="true"></i>
</span>
</button>
</div>
<div class="dual-list list-right col-md-5">
<div class="well">
<div class="row">
<div class="col-md-2">
<div class="btn-group">
<a class="btn btn-default selector" title="select all">
<i class="glyphicon glyphicon-unchecked"></i>
</a>
</div>
</div>
<div class="col-md-10">
<div class="input-group">
<input type="text" name="SearchDualList" class="form-control" placeholder="search" />
<span class="input-group-addon glyphicon glyphicon-search"></span>
</div>
</div>
</div>
<form>
<ul class="list-group" id="accordian">
<!-- right list -->
</ul>
<input type="submit" value="submit" name="submit">
</form>
</div>
</div>
</div>
</div>
</section>
Add CSS and remove inline style display none from p tag in JS.
$('.content').hide();
$('.listelement').on('click', function() {
if (!($(this).children('.content').is(':visible'))) {
$('.content').slideUp();
$(this).children('.content').slideDown();
} else {
$('.content').slideUp();
}
});
$(function() {
$('body').on('click', '.show', function() {
css("display", "block");
});
$('body').on('click', '.list-group .list-group-item', function() {
$(this).toggleClass('active');
});
$('.listarrows button').click(function() {
var $button = $(this),
actives = '';
if ($button.hasClass('move-left')) {
actives = $('.list-right ul li.active');
actives.clone().appendTo('.list-left ul');
actives.remove();
} else if ($button.hasClass('move-right')) {
actives = $('.list-left ul li.active');
actives.clone().appendTo('.list-right ul');
actives.remove();
}
});
$('[name="SearchDualList"]').keyup(function(e) {
var code = e.keyCode || e.which;
if (code == '9') return;
if (code == '27') $(this).val(null);
var $rows = $(this).closest('.dual-list').find('.list-group li');
var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();
$rows.show().filter(function() {
var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
return !~text.indexOf(val);
}).hide();
});
});
$(function() {
var ctList = [];
var ctRight = [];
var $tBody = $("#La");
var $rbody = $("#accordian");
$.getJSON('https://api.myjson.com/bins/d6n2a', function(data) {
data.topic_info.qt_ct_connection.map(value => {
value.ct_list.forEach(CTLIST => {
$tBody.append(`<li class="list-group-item" id="rl">${CTLIST.ct}<p>
Simple collapsible
<div id="demo_${CTLIST.ct}" class="collapse">
${CTLIST.tts}, ${CTLIST.topic_level}, ${CTLIST.to_be_shown_individually}, ${CTLIST.check_for_geometry}
</div>
</p>
</li>`);
});
})
})
})
.ctList {
padding-top: 20px;
}
.ctList .dual-list .list-group {
margin-top: 8px;
}
.ctList .list-left li,
.list-right li {
cursor: pointer;
}
.ctList .list-arrows {
padding-top: 100px;
}
.ctList .list-arrows button {
margin-bottom: 20px;
}
/********************************/
/********************************/
/********************************/
/* ADD THIS */
.dual-list.list-left .well li.list-group-item p {
display: none;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class="ctList">
<div class="container">
<div class="row">
<div class="dual-list list-left col-6">
<div class="well text-right">
<div class="row">
<div class="col-md-10">
<div class="input-group">
<span class="input-group-addon glyphicon glyphicon-search">
<i class="fa fa-search" aria-hidden="true" style="padding-right: 20px;"></i>
</span>
<input type="text" name="SearchDualList" class="form-control" placeholder="search" />
</div>
</div>
<div class="col-md-2">
<div class="btn-group">
<a class="btn btn-default selector" title="select all">
<i class="glyphicon glyphicon-unchecked"></i>
</a>
</div>
</div>
</div>
<ul class="list-group" id="La"></ul>
</div>
</div>
<div class="dual-list list-right col-6">
<div class="well">
<div class="row">
<div class="col-md-2">
<div class="btn-group">
<a class="btn btn-default selector" title="select all">
<i class="glyphicon glyphicon-unchecked"></i>
</a>
</div>
</div>
<div class="col-md-10">
<div class="input-group">
<input type="text" name="SearchDualList" class="form-control" placeholder="search" />
<span class="input-group-addon glyphicon glyphicon-search"></span>
</div>
</div>
</div>
<ul class="list-group" id="La">
<li class="list-group-item" id="rl">point_in_first_quad
<p>
Simple collapsible
</p>
<div id="demo_point_in_first_quad" class="collapse">
10, capable, true, true
</div>
<p></p>
</li>
<li class="list-group-item" id="rl">point_in_second_quad
<p>
Simple collapsible
</p>
<div id="demo_point_in_second_quad" class="collapse">
10, capable, true, true
</div>
<p></p>
</li>
<li class="list-group-item" id="rl">trapezium_draw_slope_area_equ
<p>
Simple collapsible
</p>
<div id="demo_trapezium_draw_slope_area_equ" class="collapse">
20, strong, true, true
</div>
<p></p>
</li>
</ul>
<form>
<ul class="list-group" id="accordian">
<!-- right list -->
</ul>
<input type="submit" value="submit" name="submit">
</form>
</div>
</div>
</div>
</div>
</section>

Vue2 Transition Mode not working

The following is the code of my .vue. swapping between div worked just fine and the transition fade works well too. but mode out-in not working at all. both elements were shown at the same time while transitioning.
EDIT##
Sorry that I am not familiar with fiddle. Please find the full code of my .vue below for your best reference.
<template>
<div>
<div class="col-md-3">
<namecard :shop="shop" :owner="user"></namecard>
</div>
<div class="col-md-9">
<div>
<ul class="nav nav-tabs shop-manage-tabs">
<li class="nav-item">
<a class="nav-link" :class="isActive == 'items' ? 'active' :''" #click.prevent="activateTab('items')">Items</a>
</li>
<li class="nav-item">
<a class="nav-link" :class="isActive == 'operaters' ? 'active' : ''" #click.prevent="activateTab('operaters')">Operaters</a>
</li>
<li class="nav-item">
<a class="nav-link" :class="isActive == 'info' ? 'active' : ''" #click.prevent="activateTab('info')">Info</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false" :class="isActive == 'statistics' ? 'active' : ''">Statistics</a>
<div class="dropdown-menu">
<a class="dropdown-item" #click.prevent="activateTab('statistics')">Action</a>
<a class="dropdown-item" #click.prevent="activateTab('statistics')">Another action</a>
<a class="dropdown-item" #click.prevent="activateTab('statistics')">Something else here</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" #click.prevent="activateTab('statistics')">Separated link</a>
</div>
</li>
</ul>
</div>
<transition-group name="fade" mode="out-in">
<div v-if="isActive == 'items'" key="items">
<div class="card" style="padding: 1rem">
<h1>Control Panel</h1>
<button type="button" class="btn btn-success" #click="addNewProduct = true">Add New Product</button>
<button type="button" class="btn btn-danger" #click="addNewProduct = true">Delete Product</button>
</div>
<add-new-product v-show="addNewProduct"></add-new-product>
<div class="card" style="padding: 1rem">
<item-card :productId="product.id" v-for="product in shop.products" :key="product"></item-card>
</div>
</div>
<div v-else-if="isActive == 'operaters'" key="operaters">
<div class="card" style="padding: 1rem">
<h1>Control Panel</h1>
<button type="button" class="btn btn-success" #click="addNewProductModal = true">Add Operator</button>
<button type="button" class="btn btn-danger" #click="addNewProductModal = true">Delete Operator</button>
</div>
<div class="card">operaters</div>
</div>
<div v-else-if="isActive == 'info'" class="card" key="info">
<div class="card">info</div>
</div>
<div v-else-if="isActive == 'statistics'" class="card" key="statistics">
<div class="card">statistics</div>
</div>
</transition-group>
</div>
</div>
</template>
<script>
import itemCard from './Item-card.vue'
import nameCard from '../Namecard.vue'
import addNewProduct from './Add-new-product.vue'
export default {
components:{
'item-card':itemCard,
'namecard':nameCard,
'add-new-product':addNewProduct,
},
data(){
return{
user:{},
shop:{},
isActive:'items',
addNewProduct:false,
}
},
props:[
],
created(){
this.getUserInfo()
},
mounted(){
},
methods:{
getUserInfo(){
var vm = this
vm.$http.get('/getAuthUser').then((response)=>{
vm.user = response.data
vm.$http.get('/getShop/'+vm.user.id).then((response)=>{
vm.shop = response.data.data.shop
})
})
},
activateTab(tab){
var vm = this
vm.isActive = tab
}
}
}
</script>
You need to give key attribute to each of the div to make the transition work smoothly. In your case I see an extra ', which might be an issue, try removing that.
Change
<div v-if="isActive == 'items'" key="'items'">
to
<div v-if="isActive == 'items'" key="items">
and similarly at other places as well.

getting around stopPropagation()

Once upon a time, a frond end dev had some menus he wanted to close when somebody clicked outside them anywhere on the page, so he used some ifs and the method mentioned to handle he job. Of course later this came back to bite him in the ass, because the clicks made inside the mentioned menus would not take effect. How do i get around that? Or how could i differently handle this? I am using bootstrap 3 if that is of some help
the HTML
<div class="shopbar pull-right">
<a data-toggle="collapse" href="#nav-shop" class="collapsed"> <i class="fa fa-lg fa-shopping-cart"></i> </a>
<a data-toggle="collapse" href="#search" class="collapsed"> <i class="fa fa-lg fa-search"></i> </a>
</div>
....
<div id="search" class="panel-collapse collapse">
<div class="container">
<div class="row">
<div class="col-xs-12">
<div class="input-group">
<div class="input-group-btn">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">Search In <span class="caret down"></span><span class="caret up"></span></button>
<ul class="dropdown-menu">
<li>Blog</li>
<li>Portfolio</li>
<li>Events</li>
<li>Shop</li>
<li>Pages</li>
</ul>
</div><!-- /btn-group -->
<input type="text" class="form-control">
<span class="input-group-btn">
<button class="btn btn-default fa fa-search" type="button"></button>
</span>
</div><!-- /input-group -->
</div>
</div>
</div>
</div>
the Jquery
$('html').click(function () {
$(".shopbar a").addClass("collapsed");
if ($("#nav-shop").hasClass("in")) {
$("#nav-shop").collapse('hide');
}
if ($("#search").hasClass("in")) {
$("#search").collapse('hide');
}
});
$("#nav-shop").click(function (event) {
event.stopPropagation();
return true;
});
$("#search").click(function (event) {
event.stopPropagation();
return true;
});
$('html').click(function (event) {
var target = $(event.target);
if(!target.is("#nav-shop") && !target.is("#search") ) {
$(".shopbar a").addClass("collapsed");
if ($("#nav-shop").hasClass("in")) {
$("#nav-shop").collapse('hide');
}
if ($("#search").hasClass("in")) {
$("#search").collapse('hide');
}
}
});
And no event.stopPropagation needed.

Categories

Resources