JS button only firing on first element - javascript

I created a button that changes text upon clicking. However, the action only works for the first button on the page. Any button further down in the code, that has the same action, doesn't work. How do I change the JS so that it allows for multiple firings of the event?
Thanks!
HTML:
<div class="addtocart">
<a href="#" class="add-to-cart">
<div class="pretext">
ADD TO CART
</div>
</a>
<div class="pretext done">
<div class="posttext"><i class="fas fa-check"></i> ADDED</div>
</div>
</div>
JS:
<script>
const button = document.querySelector(".addtocart");
const done = document.querySelector(".done");
console.log(button);
let added = false;
button.addEventListener("click", () => {
if (added) {
done.style.transform = "translate(-110%) skew(-40deg)";
added = false;
} else {
done.style.transform = "translate(0px)";
added = true;
}
});
</script>

I think what you want is to select all button elements. Using querySelectorAll.
This will return an array of DOM elements matching the query. Then you loop through and add the event listener to each.
What the above code does is, select the first instance of a DOM element with .addtocart, not every instance, then adds the event listener.

Here is example of working code. You need to use this keyword to get what you want.
<div class="addtocart">
<a href="#" class="add-to-cart" id="addToCardItem1" onclick="addToCart(this)">
<div class="pretext">
ADD TO CART
</div>
</a>
</div>
<div class="addtocart" id="addToCardItem1" onclick="addToCart(this)">
<a href="#" class="add-to-cart">
<div class="pretext">
ADD TO CART
</div>
</a>
</div>
<script>
function addToCart(elem) {
alert(elem.id);
}
</script>

Related

finding closest sibling in jQuery

I have the following code in HTML:
$(".remove-post").click((event) => {
$(event.target).fadeOut();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="side-bar">
<button class="remove-post"> delete </button>
<a class="list">
<p>post title</p>
</a>
<button class="remove-post"> delete <button>
<a class="list"><p>another post title</p></a>
</div>
every time that I click on a delete button I want to delete the closest "a" tag with the paragraph inside it as well as the delete button by itself. I was able to delete the button but can't target the closest a tag to that clicked button
I wrote it in jQuery
If the button will always stay before paragraph you can do:
$(".remove-post").on("click", function () {
$(this).next(".list").fadeOut()
$(this).fadeOut()
})
I would recommend you to wrap the paragraph and the button together like:
<div class="side-bar">
<div class="wrapper">
<button class="remove-post">Delete<button>
<a class="list">Another post title</a>
</div>
<div class="wrapper">
<button class="remove-post">Delete <button>
<a class="list">Another post title</a>
</div>
</div>
If you do so, then you can use this:
$(".remove-post").on("click", function () {
$(this).parent().fadeOut()
})
Assuming you want to remove the next a.list sibling, use .next()
$(".remove-post").on("click", function() {
const btn = $(this)
btn.add(btn.next("a.list")).fadeOut()
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="side-bar">
<button class="remove-post">delete</button>
<a class="list"><p>post title</p></a>
<button class="remove-post">delete</button>
<a class="list"><p>another post title</p></a>
</div>
jQuery's .add() is used here to collect both the <button> and <a> so you can fade them out together.

jQuery click link when another is clicked

I have an element like this
I want mylink2 to also be clicked whenever somebody clicks on mylink
To start I am trying to get the parent container on click like this
$("#mylink").click(function(){
parentcontainer = this.closest('.myelement');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="myelement">
<div class="container">
<div class="testitem">
<a id="mylink" href="#">
Test Link 1
</a>
</div>
</div>
<div class="container">
<a id="mylink2" href="#">
Test Link 2
</a>
</div>
</div>
But now I am stuck trying to click mylink2 am I on the right track?
You can use closest to get the parent and then find second element and trigger click command but since you have ids maybe you can use them for selecting elements. Keep in mind that id's must be unique.
$("#mylink").click(function() {
const parent = $(this).closest('.myelement');
parent.find('#mylink2').trigger('click')
});
$("#mylink2").on('click', function() {
console.log('click link 2')
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="myelement">
<div class="container">
<div class="testitem">
<a id="mylink" href="#">
Test Link 1
</a>
</div>
</div>
<div class="container">
<a id="mylink2" href="#">
Test Link 2
</a>
</div>
</div>
you can trigger the jQuery first click to trigger the second one this way:
$("#mylink").click(function(){
$("#mylink2").click();
});
taking in cosider that #mylink2 has some kind of a click handler function
If your links have ids the easiest way would be to use these ids:
$('#mylink').on('click', function(event) {
console.log('my link click');
$('#mylink2').click();
});
$('#mylink2').on('click', function(event) {
console.log('my link2 click');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="myelement">
<div class="container">
<div class="testitem">
<a id="mylink" href="#">
Test Link 1
</a>
</div>
</div>
<div class="container">
<a id="mylink2" href="#">
Test Link 2
</a>
</div>
</div>
Try this:
$('#mylink, #mylink2').on('click', function(event){
console.log($("#mylink1").text());
console.log($("#mylink2").text());
});
It should be straightforward since you are using unique IDs for the two elements.
Triggering the second elements click event in the first elements handler.
$("#mylink").on("click", function(){
$("#mylink2").trigger("click");
});`

On click event backfiring after adding nested anchor tag to section element

I wanted to create a modal of sorts to open when a <li> offering additional information about a topic is clicked. I created a popUpTrigger that responds to a user "click" and then gathers the provided section (and all tags nested inside) and moves it to the popUp div that then appears on the page. I've taken necessary precaution in case the section is empty in which an alert will sound. However, the alert still fires when a section is not empty (it has text and contains an additional anchor tag). I'm not sure why this is happening.
When I console log, I see the nested anchor tag is being viewed by the browser as a separate entity to the section. I've tried nesting the anchor tag further within a div element and rewriting the javascript so the html of the nested anchor tag will be evaluated accordingly as part of the section but all to no avail. This backfiring only occurs when an additional anchor tag is included in the section element of the HTML.
HTML
<li id="card">
<a class="popUpTrigger" href="#">
Get a Library Card
<section class="hide">
<h6> How to Obtain a Library Card:</h6>
<p> Additional Info </p>
<p> Additional Info </p>
<p> Additional Info </p>
<p> Additional Info </p>
<a href="https://docs.wixstatic.com/ugd/858998_1fae2b5d06fa41a3ba3fcb493b349d19.pdf">
<img src="imgs/LibraryCardVector.png" alt="library card">
</a>
</section>
</a>
</li>
<div class="popUp">
<div>
<div id="popUpClose"> <button type="button" class="btn">X</button></div>
</div>
<div id="moreInfo">
<!--WILL BE FILLED IN WITH <section class="hide"> DATA ABOVE-->
</div>
</div>
JavaScript
$('a.popUpTrigger').on('click', function() {
$(this).addClass('selected');
if ($('.selected')) {
let messageArea = $('.selected > section.hide');
let strippedMessage = messageArea.text().replace(/(\r\n|\n|\r)/gm, "").replace(/\s/g, "");
let fullMessage = messageArea.html();
if (strippedMessage === "") {
alert("Sorry that page isn't available right now.");
$(this).removeClass('selected');
} else {
$('.popUp').css('display', 'block');
$('.popUp #moreInfo').html(fullMessage);
}
}
$('.popUp #popUpClose').on('click', function() {
$('.popUpTrigger').removeClass('selected');
$('.popUp').css('display', 'none');
});
});
I removed the children from your anchor, and instead used NEXT. Also your if statement was not needed. I left .selected in the code just in case you wanted to style the anchor when clicked.
$('a.popUpTrigger').on('click', function() {
$('a.popUpTrigger').removeClass("selected");
$(this).addClass('selected');
let messageArea = $(this).next("section");
let strippedMessage = messageArea.text().replace(/(\r\n|\n|\r)/gm, "").replace(/\s/g, "");
let fullMessage = messageArea.html();
if (strippedMessage === "") {
alert("Sorry that page isn't available right now.");
$(this).removeClass('selected');
} else {
$('.popUp').css('display', 'block');
$('.popUp #moreInfo').html(fullMessage);
}
$('.popUp #popUpClose').on('click', function() {
$('.popUpTrigger').removeClass('selected');
$('.popUp').css('display', 'none');
});
});
.selected{color:red;}
.hide{display:none;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li id="card">
<a class="popUpTrigger" href="#">
Get a Library Card </a>
<section class="hide">
<h6> How to Obtain a Library Card:</h6>
<p> Additional Info </p>
<p> Additional Info </p>
<p> Additional Info </p>
<p> Additional Info </p>
<a href="https://docs.wixstatic.com/ugd/858998_1fae2b5d06fa41a3ba3fcb493b349d19.pdf">
<img src="imgs/LibraryCardVector.png" alt="library card">
</a>
</section>
</li>
<div class="popUp">
<div>
<div id="popUpClose"> <button type="button" class="btn">X</button></div>
</div>
<div id="moreInfo">
<!--WILL BE FILLED IN WITH <section class="hide"> DATA ABOVE-->
</div>
</div>
You have the following code
<a href="#">
</a>
It is not valid to have nested anchors in HTML. So the browser breaks it up when it renders. That is why you are seeing it act weird.
You will need to stick the pop up code outside of the element.
<a class="popUpTrigger" href="#">
Get a Library Card
</a>
<section class="hide">
<p>Foo</p>
Bar
</section>
and reference it with next()
$(".popUpTrigger").on("click", function (e) {
e.preventDefault();
var anchor = $(this);
anchor.next('section').toggleClass("hide");
});

jQuery - find the index of itself inside a div

HTML
<form class="data-table">
<div class="row">...</div>
<div class="row">...</div>
<div class="row>
<div class="col-lg-3">...</div>
<div class="col-lg-3">...</div>
<div class="col-lg-3">
<div class="has-box">
<input ...>
<button> ...</button>
<div class="modal">...</div>
<ul class="panel_toolbox">
<li>
<a class="close-link">
<i class="fa fa-close"></i>
</a>
</li>
</ul>
</div>
</div>
</div>
</form>
Inside <form>, there are multiple <div class="row">. Except for the first row, all the other rows have <i class="fa fa-close"> inside themselves. The purpose of my code is to allow users to remove a row by clicking 'x' icon. But in order to do that, I first need to know which row the user clicked.
JavaScript
$('.close-link').click(function () {
// if statement makes sure that the user doesn't remove the first row
if ($('form.data-table').children().length > 2) {
var $ROW = $(this).closest('.row');
$ROW.remove();
}
});
The above Javascript code works only for the second row, and from the third row, the remove icon won't work (first row is never to be removed, because it's a title row).
Here's how it looks like.
How can I edit my jQuery code so that I can detect which row the user clicked, and remove only that row?
++ Additional information
There is an "Add" button at the bottom, and new rows are added when I click the button. So, initially there are only two rows, title row and the input row. If I click add button, a new input row is added, and click is not recognized on the newly-added rows
Try this: You can use closest() function to find the parent div and then remove it. Use index to find the position of row so that first row will not be removed. Please check below code.
$(document).ready(function() {
$(document).on("click", ".close-link", function() {
var parent = $(this).closest(".row");
var index = parent.index();
if (index > 0) {
parent.remove();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form class="data-table">
<div class="row">...</div>
<div class="row">...</div>
<div class="row">
<div class="col-lg-3">...</div>
<div class="col-lg-3">...</div>
<div class="col-lg-3">
<div class="has-box">
<input value="This is value">
<button>Button</button>
<div class="modal"></div>
<ul class="panel_toolbox">
<li>
<a class="close-link">Close
<i class="fa fa-close"></i>
</a>
</li>
</ul>
</div>
</div>
</div>
</form>
Use closest('div.row').
Also change the length to 1
Example:
$('.close-link').click(function() {
// if statement makes sure that the user doesn't remove the first row
if ($('form.data-table').children().length > 1) {
var $ROW = $(this).closest('div.row');
$ROW.remove();
}
});
Update:(As per question update)
Use the following type click event for dynamically added rows also to work.
$("form.data-table").on("click", ".close-link", function() {
// if statement makes sure that the user doesn't remove the first row
if ($('form.data-table').children().length > 1) {
var $ROW = $(this).closest('div.row');
$ROW.remove();
}
});

Javascript incrementing itself

I have a form index.asp
<div class="wrapper pop-up" id="pop_up" style="display:none;"></div>
<div class="log_in">
Login
</div>
Login.asp
<div class="authorize" id="authorizeID" >
<a href="#" id="authorize-closeBut" class="authorize-close">
<img src="img/icons/cross.png" />
</a>
<div id="response"> </div>
<div class="authorize-footer">
ForgotPassword
Registration
</div>
</div>
ForgotPassword.asp
<div class="authorize" id="passremainderID" >
<a href="#" id="passremainder-closeBut" class="authorize-close">
<img src="img/icons/cross.png" />
</a>
</div>
I have a javascript
$(".LogInBut").on('click', function(e) {
e.preventDefault();
$.get($(this).attr('href'), function(data) {
alert($('#pop_up').length);
if ($('#pop_up').length) {
$('#pop_up').html(data).show(function() {
$('.authorize-close').click(function(e){
e.preventDefault();
if ($('#pop_up').length) {
$('#pop_up').html("");
$('#pop_up').hide();
}
});
});
}
});
});
So if i insert this javascript into Index.asp page and click #LogIn, I got pop-up window with Login.asp and once alert($('#pop_up').length);, if i click on .authorize-close windows will close. If i click #LogIn again i got the same but alert($('#pop_up').length); appears twice and so incrementing each time i click #LogIn.
So how to prevent incrementing and show only once this alert?
Everytime you click the button.. you are creating a new event click for #pop_up
$('.authorize-close').click(function(e){
Its showing twice, because you created the event twice. you need to delete the old event, than create again.. change the line to:
$('.authorize-close').unbind('click').bind('click',function(e){

Categories

Resources