how to fix onClick button for append functions? - javascript

Here I work on a project where I want to implement open and close buttons but I am not able to do
currently, it's a close button for both, I need to add separate open and close buttons so that when the user clicks on open then it's open and when someones click on close then it should close properly also when I click continuously close then buttons freezes for sometime
Here is the demo of my JSFiddle Demo
please check the js Fiddle demo where buttons doesn't work properly
Here is the code
function createItem(item) {
var elemId = item.data("id");
var clonedItem = item.clone();
var newItem = $(`<div data-id="${elemId}"></div>`);
newItem.append(clonedItem);
newItem.appendTo('.item-append');
}
function countSaveItems() {
$('.count').html($(".item-append div.item-save[data-id]").length);
}
$('.item-all .item-save').click(function() {
$(this).toggleClass('productad')
window.localStorage.setItem('test_' + this.dataset.id, $(this).hasClass('productad'));
});
$('.item-all .item-save').each(function() {
var id = 'test_' + $(this).data("id");
$(this).append(`<button class='close'>Close</button>`);
if (localStorage.getItem(id) && localStorage.getItem(id) == "true") {
$(this).addClass('productad');
createItem($(this));
countSaveItems();
}
});
$(".item-all .item-save").click(function() {
var elemId = $(this).data("id");
var existing = $(`.item-append div[data-id="${elemId}"]`);
if (existing.length > 0) {
existing.remove();
} else {
createItem($(this));
}
countSaveItems();
});
$(".item-append").on("click", ".close", function() {
var id = $(this).parent().data("id");
localStorage.removeItem(`test_${id}`);
$(`.item-save[data-id='${id}']`).removeClass('productad');
$(this).parent().remove();
countSaveItems();
});
.item-save {
position: relative;
display: block;
font-size: 14px;
margin: 5px;
padding: 5px;
background: #a5a5a5;
float: left;
text-align: center;
cursor: pointer;
}
.productad {
background: red;
color: #eee
}
.count {
display: block;
background: #cbcbcb;
float: left;
font-size: 15px;
padding: 5px 18px;
margin: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='item-all'>
<div class='item-save' data-id='123'>
Save1
</div>
<div class='item-save' data-id='124'>
Save2
</div>
<div class='item-save' data-id='125'>
Save3
</div>
<div class='item-save' data-id='126'>
save4
</div>
</div>
<div class='item-append'>
</div>
<div class='count'>0</div>
Any Kind of help or suggestion is highly appreciated

To do the effect you need to add the open button into the HTML because that will be static, then switch between "Open" and "Close" when the user clicks into the "Open" or close the item, also needs to fix the local storage instead of removing in the close button just switch the value to false and validate based on that value. check the following code to see if that is what you are looking for:
function createItem(item){
var elemId = item.data("id");
var clonedItem = item.clone();
var newItem = $(`<div data-id="${elemId}"></div>`);
newItem.append(clonedItem);
clonedItem.children('.open').remove();
clonedItem.append(`<button class='close'>Close</button>`);
newItem.appendTo('.item-append');
}
function countSaveItems(){
$('.count').html($(".item-append div.item-save[data-id]").length);
}
$('.item-all .item-save').click(function() {
var id = $(this).data("id");
var lsId = `test_${id}`;
$(this).toggleClass('productad');
if (!$(this).hasClass('productad')){
window.localStorage.setItem(lsId, false);
$(this).children(".open").html("Open");
createItem($(this));
}else{
window.localStorage.setItem(lsId, true);
$(this).children(".open").html("Close");
$(`.item-append div[data-id='${id}']`).remove();
}
countSaveItems();
});
$('.item-all .item-save').each(function() {
var id = 'test_' + $(this).data("id");
if (localStorage.getItem(id) && localStorage.getItem(id) == "true") {
$(this).addClass('productad');
createItem($(this));
}
countSaveItems();
});
$(".item-all .item-save").click(function() {
var elemId = $(this).data("id");
var existing = $(`.item-append div[data-id="${elemId}"]`);
if (existing.length > 0){
existing.remove();
}else{
createItem($(this));
}
countSaveItems();
});
$(".item-append").on("click", ".close", function() {
var id = $(this).parent().data("id");
window.localStorage.setItem(`test_${id}`, false);
$(`.item-save[data-id='${id}']`).removeClass('productad');
$(`.item-save[data-id='${id}']`).children(".open").html("Open");
$(this).parent().parent().remove();
countSaveItems();
});
.item-save {
position: relative;
display: block;
font-size: 14px;
margin: 5px;
padding: 5px;
background: #a5a5a5;
float: left;
text-align: center;
cursor: pointer;
}
.productad {
background: red;
color: #eee
}
.count {
display: block;
background: #cbcbcb;
float: left;
font-size: 15px;
padding: 5px 18px;
margin: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='item-all'>
<div class='item-save' data-id='123'>
Save1 <button class='open'>Open</button>
</div>
<div class='item-save' data-id='124'>
Save2 <button class='open'>Open</button>
</div>
<div class='item-save' data-id='125'>
Save3 <button class='open'>Open</button>
</div>
<div class='item-save' data-id='126'>
Save4 <button class='open'>Open</button>
</div>
</div>
<div class='item-append'></div>
<div class='count'>0</div>

Related

Disable button 1 Section when click on button 2

Have multiple buttons and sections associated with those buttons in the Elementor page builder.
What I am trying to achieve is when page loads, we can only see buttons and section will toggle when someone clicks on the button.
I have managed to achieve that, but when clicking on second button, button 1 section should hide and button 2 section should display.
Here is the w3 schools link for my project
jQuery(document).ready(function( $ ){
var hbtn = $(".coursesBtn");
var hcon = $(".coursesSection");
hcon.hide();
hbtn.click(function(e) {
var index = hbtn.index(this)
$(hcon).eq(index).slideToggle("slow");
e.preventDefault();
});
});
jQuery(document).ready(function( $ ){
var hbtn = $(".videosBtn");
var hcon = $(".videosSection");
hcon.hide();
hbtn.click(function(e) {
var index = hbtn.index(this)
$(hcon).eq(index).slideToggle("slow");
e.preventDefault();
});
});
You can use onclick for buttons for example
<button class="btn1" onclick="f1()">BUTTON1</button>
and add the function to toggle in f1()
Here is a quick example, the idea is to hide the other sections first, and show the section that you want to be displayed;
$(document).ready(function($) {
$('.btn1').click(function() {
$('.section').hide();
$('.section1').show();
})
$('.btn2').click(function() {
$('.section').hide();
$('.section2').show();
})
$('.btn3').click(function() {
$('.section').hide();
$('.section3').show();
})
})
.section {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
}
.section2 {
background-color: lightgreen;
}
.section3 {
background-color: orange;
}
<button class="btn1">BUTTON1</button>
<button class="btn2">BUTTON2</button>
<button class="btn3">BUTTON3</button>
<div class="section section1">
This is Section1.
</div>
<div class="section section2">
This is Section2.
</div>
<div class="section section3">
This is Section3.
</div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
Add a new class for each button (.btn) and section (.section) and use these as in the code below. You can have as many buttons and sections as you want and the code below will work without any modification:
var hbtn = $(".btn");
var hcon = $(".section");
hcon.hide();
hbtn.click(function(e) {
var index = hbtn.index(this);
hcon.hide() //OR hcon.filter(':visible').slideToggle("slow")
.eq(index).slideToggle("slow");
});
DEMO
$(document).ready(function( $ ){
var hbtn = $(".btn");
var hcon = $(".section");
hcon.hide();
hbtn.click(function(e) {
var index = hbtn.index(this);
hcon.hide() //OR hcon.filter(':visible').slideToggle("slow")
.eq(index).slideToggle("slow");
});
});
.section1 {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
}
.section2 {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="btn1 btn">BUTTON1</button>
<button class="btn2 btn">BUTTON2</button>
<div class="section1 section">
This is Section1.
</div>
<div class="section2 section">
This is Section2.
</div>

Hide a DIV and show another when I press the enter key

I'm trying to do a function that when I press the enter key it disappears a div (containerMessage) and another (containerResult) one appears, what am I doing wrong? When I press the enter key the function is not even called
A Live Example
HTML
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="bloco">
<h1>NSGM</h1>
<h2>Namorada Super Gostosa e Modelo</h2>
<img src="girlfriend.png">
<div id="containerMessage">
<p id="message">Qual seu nome meu amor</p>
<form>
<input type="text" name="name" id="digitarNome">
</form>
<div id="containerResult">
<p id="result">EU TE AMO RODRIGO</p>
</div>
</div>
</div>
<script src="NSGM.js"></script>
</body>
</html>
Javascript
var digitarNome = document.getElementById("digitarNome");
digitarNome.addEventListener("keydown", function (e) {
if (e.keyCode === 13) {
validate(e);
}
});
function validate(e) {
if (document.getElementById('containerMessage').style.display == 'block') {
document.getElementById('containerMessage').style.display = 'none'
document.getElementById('containerResult').style.display = 'block'
}
}
When you press enter, the form gets submitted, so you'll have to prevent that default behaviour:
var digitarNome = document.getElementById("digitarNome");
digitarNome.addEventListener("keydown", function (e) {
if (e.keyCode === 13) {
e.preventDefault(); // Prevent submitting the form
validate(e);
}
});
The other issue is that you're hiding the containerMessage div which contains your containerResult, so it will never be shown. Check the snippet below, but basically you'll just have to move the containerResult div out of the containerMessage div.
var digitarNome = document.getElementById("digitarNome");
digitarNome.addEventListener("keydown", function(e) {
if (e.keyCode === 13) {
e.preventDefault();
validate(e);
}
});
function validate(e) {
let container = document.getElementById("containerMessage");
if (!container.style.display || container.style.display == "block") {
container.style.display = "none";
document.getElementById("containerResult").style.display = "block";
}
}
body {
background-color: red;
margin: 0;
}
img {
height: 50vh;
}
#bloco {
text-align: center;
margin: 0;
position: absolute;
top: 45%;
left: 50%;
transform: translate(-50%, -50%);
white-space: nowrap;
}
h1 {
margin: 100px 0px 0px 0px;
font-size: 10em;
}
h2 {
margin: 0;
font-size: 3em;
}
p {
font-size: 3em;
margin: 0;
}
h1,
h2,
p {
color: white;
}
input[type="text"] {
margin: 50px 0px 0px 0px;
padding: 16px 20px;
border: none;
border-radius: 8px;
background-color: #f1f1f1;
font-size: 2em;
text-align: center;
}
input[type="text"]:focus {
background-color: #ea8079;
color: white;
outline: 0;
}
#result {
font-size: 6em;
}
#containerResult {
display: none;
}
#containerMessage {
display: block;
}
<div id="bloco">
<h1>NSGM</h1>
<h2>Namorada Super Gostosa e Modelo</h2>
<div id="containerMessage">
<p id="message">Qual seu nome meu amor</p>
<form>
<input type="text" name="name" id="digitarNome" />
</form>
</div>
<div id="containerResult">
<p id="result">EU TE AMO RODRIGO</p>
</div>
</div>
The problem is that .style.display will only return the current style if it has been previously set inline or via javascript.
Otherwise, you must use:
getComputedStyle(element, null).display
where element is previously selected in the DOM.
I removed the form from the example to remove that distraction.
var digitarNome = document.getElementById("digitarNome");
digitarNome.addEventListener("keydown", function(e) {
if (e.keyCode === 13) {
validate(e);
}
});
function validate(e) {
let msgDiv = document.getElementById('containerMessage');
let resDiv = document.getElementById('containerResult');
let divStyle = getComputedStyle(msgDiv, null).display;
if (divStyle == 'block') {
msgDiv.style.display = 'none';
resDiv.style.display = 'block';
}
}
#containerResult{display:none;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div id="bloco">
<div id="containerMessage">
Nome meu amor: <input type="text" name="name" id="digitarNome">
</div>
<div id="containerResult">
<p id="result">EU TE AMO RODRIGO</p>
</div>
</div>
References:
https://stackoverflow.com/a/4866269/1447509
Element.style will only retrieve the styles from the attribute on the element so
document.getElementById('containerMessage').style.display == 'block'
Will always return false
From W3 schools https://www.w3schools.com/jsref/prop_html_style.asp
Note: The style property only returns the CSS declarations set in the element's inline style attribute, e.g.
. It is not possible to use this property to get information about style rules from the section in the document or external style sheets.
You can instead apply the display style as in line attribute like so
<div id="containerMassage" style="display:block"></div>

How to chain javascript hide/show function for each div ID?

I have many <p>s with the same function.
document.getElementById("minus").onclick = function() {
functionHide()
};
function functionHide() {
document.getElementById("plus").style.display = "block";
document.getElementById("minus").style.display = "none";
}
document.getElementById("plus").onclick = function() {
functionShow()
};
function functionShow() {
document.getElementById("plus").style.display = "none";
document.getElementById("minus").style.display = "block";
}
#plus {
display: none;
cursor: pointer;
}
#minus {
cursor: pointer;
}
.floatright {
float: right
}
.w50 {
width: 50%;
text-align: center;
}
<div class="w50">
<p>What paperwork do I need to complete to file for divorce ?
<span class="floatright inlineb" id="minus">- </span>
<span class="floatright inlineb" id="plus">+</span>
</p>
<p>How do I change my custody and suport orders ?
<span class="floatright inlineb" id="minus">- </span>
<span class="floatright inlineb" id="plus">+</span>
</p>
</div>
When I click on the first minus ( "-" ) it works correctly.
but for the second, it doesn't work.
I want to know how can I automatically chain for all others divs. they have the same typing code.
Also, I would know how can I change the last element (" - ") when an another + is clicked?
Here is a preview of what I want to do
And a fiddle: https://jsfiddle.net/khrismuc/prsebqg3/15/
You are using duplicate IDs, which is a no-no. Here is an example using classes and .querySelectorAll.
var minuses = document.querySelectorAll(".minus");
var pluses = document.querySelectorAll(".plus");
minuses.forEach(function(minus) {
minus.addEventListener('click', functionHide);
});
pluses.forEach(function(plus) {
plus.addEventListener('click', functionShow);
});
function functionHide() {
pluses.forEach(function(plus) {
plus.style.display = "block";
});
minuses.forEach(function(minus) {
minus.style.display = "none";
});
}
function functionShow() {
pluses.forEach(function(plus) {
plus.style.display = "none";
});
minuses.forEach(function(minus) {
minus.style.display = "block";
});
}
You can modify for your particular uses.
Your logic needs to be slightly more complex:
var current = -1;
function handleClick(clicked) {
$(".w50 p").removeClass("active").find("span").text("+");
$("#box p").hide();
if (current === clicked) {
current = -1;
return;
}
current = clicked;
$(".w50 p").eq(current).addClass("active").find("span").text("-");
$("#box p").eq(current).show();
}
$(document).ready(function() {
$(".w50 p").each(function(i, el) {
$(this).append($("<span>").text("+"));
$(this).click(function() {
handleClick(i);
});
});
$(".w50 p").eq(0).click();
});
.w50 {
width: 80%;
text-align: center;
}
.w50 p {
cursor: pointer
}
.w50 p.active {
color: orange
}
.w50 p span {
float: right;
width: 1em;
display: inline-block;
}
#box {
background-color: orange;
margin: 20px;
min-height: 6em;
}
#box p {
display: none;
padding: 1em
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="w50">
<p>What paperwork do I need to complete to file for divorce?</p>
<p>How do I change my custody and support orders?</p>
</div>
<div id="box">
<p>Paperwork description</p>
<p>Custody description</p>
</div>

Can't delete div from to-do list

I'm creating a to-do list app, and in the app there is a div that wraps an input box (for the to-do item and so the user can edit the to-do) and a icon from font-awesome. When the user clicks on the icon, I want the entire div (which contains the to-do and the delete icon) to be deleted. But when tried to do that, it didn't work. Can someone help me?
Here's the JS Code
$(document).ready(() => {
$(".input input").on("keypress", check_todo);
$(".fa-trash").on("click", ".todo_container", delete_todo);
})
// delete todo
let delete_todo = (e) => {
e.target.remove();
}
// add todo
let add_todo = () => {
let todo = $(".input input").val();
$(".output").append(`
<input type="text" placeholder="Edit To-do" value="${todo}"><i class="fa fa-trash fa-lg" aria-hidden="true"></i>
`);
$(".input input").val("");
}
// check todo
let check_todo = (e) => {
if (e.keyCode == 13) {
if ($(".input input").val() == "") {
no_todo();
} else {
add_todo();
}
}
}
// no todo
let no_todo = () => {
alert("Please add a new todo");
}
See the html and a demo
You should binding to .out-put container.
$(".output").on("click",".fa-trash" , delete_todo);
http://codepen.io/Vrety/pen/WoWmaE
http://codepen.io/anon/pen/eBoXZe
In your event listener, you need to swap ".todo_container" and ".fa-trash".
$(".todo_container").on("click",".fa-trash" , delete_todo);
This statement means, when a click event occurs and bubbles up to .todo_container, check if the clicked element is .fa-trash, if so call the function.
Then change your delete function
let delete_todo = (e) => {
$(e.currentTarget).closest('.todo_container').remove()
}
This code means from the clicked icon, travel up the dom to find .todo_container, then remove it.
Good job with using the delegation in JQuery but while using it
$(".todo_container").on("click",".fa-trash" , delete_todo);
The base element $(".todo_container") needs to be static, You are deleting this also in the delete_todo() function.
Try using $(".output") instead and see if it works.
here is a working code
$(document).ready(function() {
$(".input input").on("keypress", check_todo);
//$(".fa-trash").on("click", ".todo_container", delete_todo);
$(".todo_container .fa-trash").on("click", delete_todo);
})
// delete todo
let delete_todo = function(e) {
//e.target.remove();
$(e.target).parent().remove();
}
// add todo
let add_todo = function() {
let todo = $(".input input").val();
//to do container element, the delete icon will added later
var toDoContainer = $(`
<div class="todo_container">
<input type="text" placeholder="Edit To-do" value="${todo}"></div>
`);
//create delete icon and set event listener
var elem = $('<i class="fa fa-trash fa-lg" aria-hidden="true"></i>').on("click", delete_todo).appendTo(toDoContainer);
$(".output").append(toDoContainer);
$(".input input").val("");
}
// check todo
let check_todo = (e) => {
if (e.keyCode == 13) {
if ($(".input input").val() == "") {
no_todo();
} else {
add_todo();
}
}
}
// no todo
let no_todo = () => {
alert("Please add a new todo");
}
#font-face {
font-family: Open Sans;
src: url("assets/fonts/OpenSans-Regular");
font-weight: 400
}
#font-face {
font-family: Open Sans;
src: url("assets/fonts/OpenSans-Semibold");
font-weight: 600
}
* {
margin: 0;
padding: 0;
transition: all 200ms ease-in-out;
}
*::selection {
background-color: #ffffaa;
}
.container {
width: 60%;
margin: 20px auto;
}
.header {
padding: 10px;
}
.header input {
padding: 10px;
width: 60%;
border: none;
outline: none;
font: 400 1.8em Open Sans;
}
.to-do {
padding: 10px;
text-align: center;
}
.input input {
padding: 10px;
width: 40%;
border: none;
outline: none;
font: 600 1em Open Sans;
border-bottom: 3px solid #333;
}
.output {
margin: 10px;
}
.output input {
padding: 20px;
border: none;
outline: none;
font: 600 1em Open Sans;
width: 50%;
cursor: pointer;
}
.output input:hover {
background-color: #eee;
}
.fa-trash {
padding: 20px;
cursor: pointer;
}
.fa-trash:hover {
background-color: #333;
color: #fff;
}
<head>
<title>To-do List</title>
<!-- FONTS -->
<link href="https://fonts.googleapis.com/css?family=Open+Sans:400,500" rel="stylesheet">
</head>
<body>
<div class="container">
<header class="header">
<input type="text" name="edit_name" placeholder="Edit Name">
</header>
<section class="to-do">
<div class="input">
<input type="text" name="add_todo" placeholder="Click To Add A New To-do">
</div>
<div class="output">
<div class="todo_container">
<input type="text" placeholder="Edit To-do" value="Todo #1"><i class="fa fa-trash fa-lg" aria-hidden="true"></i>
</div>
<div class="todo_container">
<input type="text" placeholder="Edit To-do" value="Todo #2"><i class="fa fa-trash fa-lg" aria-hidden="true"></i>
</div>
</div>
</section>
</div>
<!-- JQUERY -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://use.fontawesome.com/5840114410.js"></script>
</body>

Jquery Drag to Delete

I am currently playing with some jquery and as i tried to create a simple todo-list I came across a problem.
So far the goal is to be able to add paragraphs by clicking the green square and remove them by clicking it once and then dragging it to the red square.
Everything works out fine except the deleting of the dragged paragraph.
Right now it only works by removing the whole class but I want to only delete the dragged one.
Here the code: https://codepen.io/anon/pen/OXXXpY
jQuery:
$(document).ready(function() {
var send = $("#send");
var dlt = $("#delete");
send.click(function() {
var input = $("input").val();
$("#container").prepend("<p class='entry'>" + input + "</p>");
});
$(document).on("click", ".entry", function() {
$(this).draggable();
$("#delete").droppable({
drop: function() {$(".entry").remove();}
});
});
});
Please don't mind my English and the real use of this project. This is just an jQuery experiment.
Use $(this) to target the dragged element
$(document).on("click", ".entry", function() {
var $this = $(this);
$(this).draggable();
$("#delete").droppable({
drop: function() {
$($this).remove();
}
});
});
$(document).ready(function() {
var send = $("#send");
var dlt = $("#delete");
send.click(function() {
var input = $("input").val();
$("#container").prepend("<p class='entry'>" + input + "</p>");
});
$(document).on("click", ".entry", function() {
var $this = $(this);
$(this).draggable();
$("#delete").droppable({
drop: function() { $($this).remove(); }
});
});
});
body {
text-align: center;
}
h1 {
font-family: Helvetica;
}
form input {
width: 500px;
font-size: 30px;
}
form input:focus {
outline: none;
}
.inline {
display: inline-block;
}
#send {
width: 40px;
height: 40px;
background-color: green;
}
#delete {
width: 40px;
height: 40px;
background-color: red;
}
.entry {
font-family: helvetica;
border: solid 1px grey;
-webkit-user-select: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<h1>ToDo</h1>
<form class="">
<div class="inline" id="delete"></div>
<input type="text" name="input" value="">
<div class="inline" id="send"></div>
</form>
<div id="container"></div>

Categories