JS remove div with button after cloning - javascript

I have problem with removing div containing button. First I clone and add button, then change its class from 'add' to 'remove'. Then I try to remove div containing button with 'remove' but I can't access remove functions.
<div class="margin"></div>
<div class='new'>
<button type="button" class="btn btn-success add"><i class="fas fa-plus"></i></button>
</div>
<script>
$(document).ready(function() {
var div = document.getElementById('new');
$(".add").click(function(){
clone = div.cloneNode(true);
$(clone).insertAfter(".margin");
$("button.add:not(:last)).removeClass('add').addClass('remove');
$(".remove").click(function(){
console.log('inside')
//$(this).parent('div').remove();
});
});
</script>

document.getElementById('new') ... ur element does not have an ID. Its class-name is 'new' but not its ID. Some corrections should make it work:
$(document).ready(function() {
var div = document.getElementById('new');
$(".add").click(function(){
clone = div.cloneNode(true);
$(clone).insertAfter(".margin");
$("button.add:not(:last)").removeClass('add').addClass('remove');
$(".remove").click(function(){
console.log('inside')
//$(this).parent('div').remove();
});
})
});
.add {
background: green;
}
.remove {
background: red;
}
button {
color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="new">
<button type="button" class="btn btn-success add">
<i class="fas fa-plus"></i> new
</button>
</div>
<div class="margin"></div>
Edit:
Is there a more elegant way to do this?
Maybe like so:
$('.add').on('click', function() {
$(this).clone()
.toggleClass('add remove')
.on('click', function() {
$(this).remove()
})
.prependTo('#new');
})
.add {
background: green;
}
.remove {
background: red;
}
button {
color: white;
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="new">
<button type="button" class="btn btn-success add">
<i class="fas fa-plus"></i> new
</button>
</div>

Related

How to use queryselectorall in addevent listener

when i click the left button that other right button must be active,then i do the same for the right button it should work,i acheived this using queryselector but when i duplicate the same element,this same code wont work,is there any way i can use queryselectorall to acheive this,thanks.
(function() {
const slick_prev_button = document.querySelector('.prev-button');
const slick_next_button = document.querySelector('.next-button');
const slick_left_button_background = document.querySelector('.left-arrow-color');
const slick_right_button_background = document.querySelector('.right-arrow-color');
slick_prev_button.addEventListener('click', function() {
slick_left_button_background.classList.remove('left-arrow-color');
slick_left_button_background.classList.add('left-arrow-color-active');
slick_right_button_background.classList.remove('right-arrow-color-active');
slick_right_button_background.classList.add('right-arrow-color');
});
slick_next_button.addEventListener('click', function() {
slick_left_button_background.classList.remove('left-arrow-color-active');
slick_left_button_background.classList.add('left-arrow-color');
slick_right_button_background.classList.remove('right-arrow-color');
slick_right_button_background.classList.add('right-arrow-color-active');
});
})();
.dual-button {
display: flex;
justify-content: center;
gap: 10px;
}
.left-arrow-colour i {
color: #f67b54;
background: #efefef;
}
.left-arrow-colour-active i {
color: #efefef;
background: #f67b54;
}
.right-arrow-colour i {
color: #f67b54;
background: #efefef;
}
.right-arrow-colour-active i {
color: #efefef;
background: #f67b54;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" rel="stylesheet"/>
<div class="dual-button">
<button class="prev-button left-arrow-colour"><i class=" fas fa-angle-left "></i></button>
<button class="next-button right-arrow-colour"><i class=" fas fa-angle-right "></i></button>
</div>
<div class="dual-button">
<button class="prev-button left-arrow-colour"><i class=" fas fa-angle-left "></i></button>
<button class="next-button right-arrow-colour"><i class=" fas fa-angle-right "></i></button>
</div>
<div class="dual-button">
<button class="prev-button left-arrow-colour"><i class=" fas fa-angle-left "></i></button>
<button class="next-button right-arrow-colour"><i class=" fas fa-angle-right "></i></button>
</div>
You could call your code on the parent element like so:
document.querySelectorAll('.dual-button').forEach(function(parentEl) {
const prev = parentEl.querySelector('.prev-button');
const next = parentEl.querySelector('.next-button');
prev.addEventListener('click', function() {
this.classList.remove('left-arrow-color');
this.classList.add('left-arrow-color-active');
next.classList.remove('right-arrow-color-active');
next.classList.add('right-arrow-color');
});
next.addEventListener('click', function() {
prev.classList.add('left-arrow-color');
prev.classList.remove('left-arrow-color-active');
this.classList.add('right-arrow-color-active');
this.classList.remove('right-arrow-color');
});
});
Also, judging by your css classes you can probably simplify that a lot since you are using the same style rules for the same css classes multiple times (e.g. you could just make a .button-inactive and .button-active class. Or even better, just a .active class. The inactive state would then just be the default style on the button element).

how to get clicked element from multiple class in javascript

I am polluting a div with the help of following codes every time the 'Add' button is clicked on the website.
const addClick = document.getElementById("addBtn");
addClick.addEventListener("click", () => {
addNote();
});
function addNote(){
const notes = document.getElementById("notes");
notes.innerHTML += `
<div class="note">
<div class="delete"><i class="fas fa-times"></i></div>
<button class="save"><i class="fas fa-check"></i></button>
<textarea type="text" class="text"></textarea>
</div>
`;
}
With this code, I am generating note(s) that has delete or save options. I want to know which class element was clicked. I want to do this with vanilla Javascript.
You can use event delegation:
add an event listener to the parent element or document and then check if the clicked element contains the class that you want to target.
You may need to also check if the element clicked is a child of the button (the icon)
document.addEventListener("click", function(event) {
var target = event.target;
if (isElement(target, 'delete')) {
console.log("delete button clicked", target.closest(".note"));
} else if (isElement(target, "save")) {
console.log("save button clicked", target.closest(".note"));
}
});
function isElement(element, className) {
return element.classList.contains(className) || element.closest(`.${className}`);
}
<div class="note">
<button class="delete"><i class="fas fa-times"></i>Delete</button>
<button class="save"><i class="fas fa-check"></i>Save</button>
<textarea type="text" class="text"></textarea>
</div>
<div class="note">
<button class="delete"><i class="fas fa-times"></i>Delete</button>
<button class="save"><i class="fas fa-check"></i>Save</button>
<textarea type="text" class="text"></textarea>
</div>
<div class="note">
<button class="delete"><i class="fas fa-times"></i>Delete</button>
<button class="save"><i class="fas fa-check"></i>Save</button>
<textarea type="text" class="text"></textarea>
</div>
Here is a snippet for your case.
HTML
<div id="app"></div>
JS
const appDiv = document.getElementById("app");
appDiv.innerHTML = `<h1>JS Starter</h1>`;
[1, 2, 3, 4].forEach((el, index) => {
const note = document.createElement("div");
appDiv.insertAdjacentElement("afterend", note);
note.classList.add("note");
note.addEventListener("click", () => {
appDiv.innerHTML = `<h1>Box number: ${index + 1}<h1>`;
});
});
CSS
.note {
border: 1px solid black;
height: 100px;
width: 100px;
margin: 10px;
}
.note:hover {
cursor: pointer;
}

How to add class to buttons on click

Sorry for silly question , but I can't add class to button on click. I have list of buttons and on click I need to change background of active button . I dont know how to get index of element on click inside list and add class. I need to make it on pure javascript. Only need to leave $(document).ready(function() . Here is my fiddle https://jsfiddle.net/armakarma/ns5tfcL0/15/
HTML
<div class="content-itinerary__buttons-wrapper">
<button class="content-itinerary__buttons description-text ">Day 2</button>
<button class="content-itinerary__buttons description-text">Day 3</button>
<button class="content-itinerary__buttons description-text">Day 4</button>
</div>
JS
$(document).ready(function() {
let myBtns=document.querySelector('.content-itinerary__buttons-wrapper')
myBtns.addEventListener('click', ()=>{
console.log('test')
})
});
Only need to leave $(document).ready(function()
I am not sure why do you need to leave that when you have the equivalent JavaScript (DOMContentLoaded).
Loop through all the buttons, inside the event handler function first remove the class from all the buttons then add the class only to the clicked button:
document.addEventListener('DOMContentLoaded', () => {
let myBtns=document.querySelectorAll('.content-itinerary__buttons');
myBtns.forEach(function(btn) {
btn.addEventListener('click', () => {
myBtns.forEach(b => b.classList.remove('active'));
btn.classList.add('active');
});
});
});
.active {
color: #fff;
background-color: #4CAF50;
}
<div class="content-itinerary__buttons-wrapper">
<button class="content-itinerary__buttons description-text ">Day 2</button>
<button class="content-itinerary__buttons description-text">Day 3</button>
<button class="content-itinerary__buttons description-text">Day 4</button>
</div>
You just need to use event object in click event
$(document).ready(function() {
let myBtns=document.querySelectorAll('.content-itinerary__buttons-wrapper')[0];
myBtns.addEventListener('click', (e)=> {
if (e.target.className.indexOf('clicked') === -1) {
e.target.className += ' clicked';
} else {
e.target.className = e.target.className.replace(' clicked', '');
}
})
});
This is your solution
var header = document.getElementById("myDIV");
var btns = header.getElementsByClassName("content-itinerary__buttons");
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener("click", function() {
var current = document.getElementsByClassName("active");
current[0].className = current[0].className.replace(" active", "");
this.className += " active";
});
}
.content-itinerary__buttons-wrapper {
display: flex;
margin-top: 20px;
}
.content-itinerary__buttons {
flex-grow: 1;
padding: 21px 15px 15px 15px;
box-sizing: border-box;
border: 1px solid #D7D7D7;
outline: none;
&:not(:last-child) {
border-right: 0;
}
}
.active, .btn:hover {
background-color: red;
color: white;
}
<div class="content-itinerary__buttons-wrapper" id="myDIV">
<button class="content-itinerary__buttons description-text active ">Day 2</button>
<button class="content-itinerary__buttons description-text">Day 3</button>
<button class="content-itinerary__buttons description-text ">Day 4</button>
<button class="content-itinerary__buttons description-text">Day 5</button>
<button class="content-itinerary__buttons description-text">Day 6</button>
<button class="content-itinerary__buttons description-text">Day 7</button>
<button class="content-itinerary__buttons description-text">Day 8</button>
<button class="content-itinerary__buttons description-text">Day 9</button>
<button class="content-itinerary__buttons description-text">Day 10</button>
</div>
See Code link
I would definitely use Element.classList API for adding/removing classes to/from elements.
Why?
Adding/removing classes won't affect other classes already set to the element
Updating the className of the element will replace all existing classes
It comes with handy functions like "toggle" and "replace
Your code will look something like this:
$(document).ready(function() {
let myBtns=document.querySelectorAll('.content-itinerary__buttons-wrapper')
myBtns
.forEach(btn => btn
.addEventListener('click', (e)=>{
// Check if the classList already exists on the element clicked
// If so, remove it
// Else, add it
e.classList.contains('clicked')
? e.classList.add('clicked')
: e.classList.remove('clicked');
})
);
});
Onclick of the button you can set class name to the button
function a(e)
{
e.setAttribute("class","active");
}
.active
{
color:red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="content-itinerary__buttons-wrapper">
<button class="content-itinerary__buttons description-text" onclick="a(this)">Day </button>
<button class="content-itinerary__buttons description-text" onclick="a(this)">Day </button>
<button class="content-itinerary__buttons description-text" onclick="a(this)">Day </button>
</div>
If you going to get rid of jQuery replace wrapper function to use listen for DOMContentLoaded event. It's the same as jQuery documentReady.
In your click handler use event object, ev.target in my example is a button which fired the event. Then use classList property to add your class.
document.addEventListener('DOMContentLoaded', function(){
let myBtns=document.querySelector('.content-itinerary__buttons-wrapper')
myBtns.addEventListener('click', (ev)=>{
let btn = ev.target;
btn.classList.add('red');
});
});
Just use forEach loop :)
$(document).ready(function() {
let myBtns=document.querySelectorAll('.content-itinerary__buttons-wrapper')
let myAllButtons = myBtns.querySelectorAll('.content-itinerary__buttons')
myAllButtons.forEach(function(element) {
element.onclick = () => element.classList.add('some-class')
})
});

Toggle changed button class

I want to create a toggle button where will change button class from class="fa fa-toggle-off" to class="fa fa-toggle-on" when clicked.
<button class="btn btn-default" id="btn" name="btn"><i id="change" class="fa fa-toggle-off"></i></button>
I create the javascript below, however it changed the button style="display:none" instead change its class.
$(function() {
$('#btn').click(function(e) {
e.preventDefault();
var display = true,
image = 'details_close.png';
if ($('.td1:visible').length == $('.td1').length) {
display = false;
image = 'details_open.png';
}
$('.td1').toggle(display);
$("#change").toggle(function()
{
$('#change').removeClass("fa-toggle-off").addClass("fa-toggle-on");
}, function() {
$('#change').removeClass("fa-toggle-on").addClass("fa-toggle-off");
});
});
});
There you go, I used toggleClass (http://api.jquery.com/toggleclass/) function to toggle the class when you click your button, it'll disabled this class fa-toggle-off and activate this class fa-toggle-on on click
(https://api.jquery.com/click/) and vice versa.
$(document).ready(function(){
$("#btn").click(function() {
$("#change").toggleClass("fa-toggle-off fa-toggle-on");
});
});
.fa-toggle-off {
background-color: #F00;
}
.fa-toggle-on {
background-color: #0F0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="btn btn-default" id="btn" name="btn">
Button <i id="change" class="fa fa-toggle-off">AAA</i>
</button>
Beware, in your code you're checking if #change is clicked, the button got #btn ID attribute.
Wish I helped you.
You can use .toggleClass to add or remove class alternatively
$(document).ready(function() {
$("#btn").click(function() {
$("#change").toggleClass("fa-toggle-on");
});
});
.fa-toggle-off {
color: red;
}
.fa-toggle-on {
color: blue;
}
.btn-default {
display: block;
width: 200px;
height: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="btn btn-default" id="btn" name="btn"><i id="change" class="fa fa-toggle-off">Hello my button</i></button>
You can check if on/off class exist and then can remove existing class & add new class as below code:
$(function() {
$('#btn').click(function(e) {
e.preventDefault();
var display = true,
image = 'details_close.png';
if ($('.td1:visible').length == $('.td1').length) {
display = false;
image = 'details_open.png';
}
$('.td1').toggle(display);
if ($("#change").hasClass("fa-toggle-off"))
{
$('#change').removeClass("fa-toggle-off").addClass("fa-toggle-on");
} else {
$('#change').removeClass("fa-toggle-on").addClass("fa-toggle-off");
});
});
});
Hope it helps you.

Check if navbar got clicked

I have a navbar and want to close it when clicking outside. The only thing I need to check is the click event of the body.
var navBtnActive = true;
function toggleMenu(){
navBtnActive = !navBtnActive;
$("#navContent").slideToggle();
}
$('body').click(function() {
// if( clicked target is NOT the menu ){
// if(navBtnActive){ // just if the menu is open
// toggleMenu();
// }
// }
});
#navContainer {
position: relative;
display: inline-block;
}
#navContent button {
display: block;
width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="navContainer">
<button onclick="toggleMenu()">Menu</button>
<div id="navContent">
<button onclick="toggleMenu()">Slider</button>
<button onclick="toggleMenu()">Calculator</button>
<button onclick="toggleMenu()">Imageupload</button>
<button onclick="toggleMenu()">Settings</button>
<button onclick="toggleMenu()">Search</button>
<button onclick="toggleMenu()">Servercall</button>
</div>
</div>
As you can see below, my $('body').click(function() got the code for closing it. I just want to get a way checking if the clicked object is the menu itself or not. If not, close the menu.
Hi you can try this code
var navBtnActive = true;
function toggleMenu(e) {
navBtnActive = !navBtnActive;
$("#navContent").slideToggle();
}
jQuery(document).on('click', function() {
$("#navContent").slideUp();
});
jQuery('#navContainer').on('click', function(e) {
e.stopPropagation();
});
#navContainer {
position: relative;
display: inline-block;
}
#navContent button {
display: block;
width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="navContainer">
<button onclick="toggleMenu()">Menu</button>
<div id="navContent">
<button onclick="toggleMenu()">Slider</button>
<button onclick="toggleMenu()">Calculator</button>
<button onclick="toggleMenu()">Imageupload</button>
<button onclick="toggleMenu()">Settings</button>
<button onclick="toggleMenu()">Search</button>
<button onclick="toggleMenu()">Servercall</button>
</div>
</div>
just check the click targer jQuery event targer
$('body').click(function(e){
var $elem = $(e.target);
if ($elem.attr('id') === 'my_nav_bar_id') {
doSomething();
}
});
Here you go with a solution https://jsfiddle.net/ap7m4xnu/
var navBtnActive = true;
$('#menuToggle').click(function(e){
e.stopPropagation();
navBtnActive = !navBtnActive;
$("#navContent").slideToggle();
})
$('body').not('#menuToggle').click(function(e) {
e.preventDefault();
$("#navContent").slideUp();
});
#navContainer {
position: relative;
display: inline-block;
}
#navContent button {
display: block;
width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="navContainer">
<button id="menuToggle">Menu</button>
<div id="navContent">
<button onclick="toggleMenu()">Slider</button>
<button onclick="toggleMenu()">Calculator</button>
<button onclick="toggleMenu()">Imageupload</button>
<button onclick="toggleMenu()">Settings</button>
<button onclick="toggleMenu()">Search</button>
<button onclick="toggleMenu()">Servercall</button>
</div>
</div>
You can use the compareDocumentPosition method. You can read its documentation here: https://developer.mozilla.org/en-US/docs/Web/API/Node/compareDocumentPosition
You can test if the clicked element is contained by the menu by doing the following:
var DOCUMENT_POSITION_CONTAINED_BY = 16;
if ((navContainer.compareDocumentPosition(clickedElement) & DOCUMENT_POSITION_CONTAINED_BY) !== 0) {
// clicked element is inside the menu
} else {
// clicked element is outside of the menu
}
In your example it would work like this:
var navBtnActive = true;
function toggleMenu(){
navBtnActive = !navBtnActive;
$("#navContent").slideToggle();
}
$('body').click(function(event) {
var DOCUMENT_POSITION_CONTAINED_BY = 16,
navContainer = document.getElementById('navContainer'),
compareResult = navContainer.compareDocumentPosition(event.target) & DOCUMENT_POSITION_CONTAINED_BY;
if (compareResult === 0) {
// clicked element is outside of the menu
toggleMenu();
}
});
#navContainer {
position: relative;
display: inline-block;
}
#navContent button {
display: block;
width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="navContainer">
<button onclick="toggleMenu()">Menu</button>
<div id="navContent">
<button onclick="toggleMenu()">Slider</button>
<button onclick="toggleMenu()">Calculator</button>
<button onclick="toggleMenu()">Imageupload</button>
<button onclick="toggleMenu()">Settings</button>
<button onclick="toggleMenu()">Search</button>
<button onclick="toggleMenu()">Servercall</button>
</div>
</div>
function toggleMenu(){
$("#navContent").slideToggle();
}
$('body').click(function(e) {
if(document.querySelector('body')== e.toElement && $("#navContent").is(':visible')){
$("#navContent").slideToggle();
}
});
#navContainer {
position: relative;
display: inline-block;
}
#navContent button {
display: block;
width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="navContainer">
<button onclick="toggleMenu()">Menu</button>
<div id="navContent">
<button onclick="toggleMenu()">Slider</button>
<button onclick="toggleMenu()">Calculator</button>
<button onclick="toggleMenu()">Imageupload</button>
<button onclick="toggleMenu()">Settings</button>
<button onclick="toggleMenu()">Search</button>
<button onclick="toggleMenu()">Servercall</button>
</div>
</div>

Categories

Resources