Click and toggle between two classes on an array (no JQuery) - javascript

I need to make a site where I can add something to a shoppingcart. I do not need to store any data, so just changing a class to 'addedInCart' is enough. This is what I have so far, but it's not working yet. I know all the classnames I got are coming back in an array. I just dont know how to change them if the button is clicked. I tried a lot with the addEventListener and the toggle, but I just started coding, not everything is clear for me yet. I am not alloud to use Jquery, only HTML and Javascript.
This is what I have in Javascript:
var buyMe = document.getElementsByClassName("materials-icon");
function shoppingcart() {
for(let i = 0; i < buyMe.length; i++){
buyMe[i].classList.toggle("addedInCart");
buyMe[i].addEventListener("click", toggleClass, false)
}
}
This is what my button looks like:
<button class="material-icons" onclick="shoppingcart()"></button>
Thank you for your time!

Use event delegation to be able to use one handler. Use a data-attribute to verify the button as being a button for adding to cart. Something like:
document.addEventListener("click", handle);
function handle(evt) {
const origin = evt.target;
if (origin.dataset.cartToggle) {
// ^ if element has attribute data-cart-toggle...
origin.classList.toggle("addedInCart");
// ^ ... toggle the class
}
};
.addedInCart {
color: red;
}
.addedInCart:after {
content: " (in cart, click to remove)";
}
<button class="material-icons" data-cart-toggle="1">buy</button>
<button class="material-icons" data-cart-toggle="1">buy</button>
<button class="material-icons" data-cart-toggle="1">buy</button>

Related

How to read specific value from button in js function

I have several buttons contain some values:
<button class="Hotspot" onclick="ChangeView()" slot="hotspot-1" camera.Orbit='2.895deg 85deg 27.92m' ;>
and I need to create function that read camera.Orbit value from button's container after click on it:
function ChangeView() {
const modelViewer = document.querySelector('#orbit-demo');
modelViewer.cameraOrbit = camera.Orbit ???
}
I have no idea how to solve this. I do not use getElementbyId because it has to work for all buttons (not specific one).
I barely can JS.
Thank you for help.
You can use Element.getAttribute:
function ChangeView() {
const modelViewer = document.querySelector('#orbit-demo');
let orbit = modelViewer.getAttribute('camera.Orbit')
console.log(orbit)
}
<button class="Hotspot" onclick="ChangeView()" slot="hotspot-1" camera.Orbit='2.895deg 85deg 27.92m' id="orbit-demo">Click</button>
The onclick function passes the click event to the method. You can take the target of this event (the button element) and acquire tha attribute like that.
onclick(e => changeView(e))
ChangeView(e) {
// do things with e.target.???
}

Change class name of font-awesome when clicked

Here is the problem
This is my html code
<div id="bookmark">
<i class="far fa-bookmark"></i>
</div>
I want to change .far to .fas and vice versa in loop when clicked.
This is my updated javascript
function changeClass(elem) {
var i = elem.childNodes[1];
var c = i.classList;
console.log(i)
console.log(c)
// Change class
if (c.contains("far")) {
i.classList.remove("far");
i.classList.add("fas");
} else {
i.classList.remove("fas");
i.classList.add("far");
}
}
This is the screenshot of the console output in the browser when I click on the bookmark icon
Screenshot
When I pass the index value in the var c respectively, on i.classList[0] I get svg-inline--fa but I get undefined value in i.classList[3] instead of far. SO WHAT SHOULD I DO?
I hope this is what you are looking for (Demo: https://jsfiddle.net/hwv0oacL/8/)
HTML
<div id="bookmark" onclick="changeClass(this)">
<i class="far fa-bookmark"></i>
</div>
Javascript
changeClass(elem) {
var i = elem.childNodes[0].classList;
// Change class far to fas
if (i.includes("far")) {
i.classList.remove("far");
i.classList.add("fas");
}
// Get back to original state
if (i.includes("fas")) {
i.classList.remove("fas");
i.classList.add("far");
}
}
-------------------Updated--------------------------
Replace the above javascript with the one below. It will also work in loop like you want because we are getting element by this keyword.
JavaScript
function changeClass(elem) {
var i = elem.childNodes[1];
var c = i.classList;
// Change class
if (c.contains("far")) {
i.classList.remove("far");
i.classList.add("fas");
} else {
i.classList.remove("fas");
i.classList.add("far");
}
}
You can do it like below with jQuery:
$("#bookmark").find("i").removeClass("far");
$("#bookmark").find("i").addClass("fas");
assuming you want this to be done for single element and not for all the elements that are using .far class
add an id to the tag like id="i1" then you can add an event listener on that element. listening to the click event and once captured - toggle the class.
add the following just before the end of the body tag i.e. before </body>
<script>
document.getElementById('i1').addEventListener('click', (e) => {
e.target.classList.toggle('far');
e.target.classList.toggle('fas');
})
</script>

How to copy an event listener in plain Javascript

So I am making some overrides on a Wordpress plugin. I need to copy the event listener on an element and then replace the element and add it back. The event listener is generated by the plugin.
I thought getEventListeners() would work but I have read that it only works in console. If that is this case I'm really astounded. We're in freaking 2020 and I am not finding an obvious solution to this.
What is the solution here people?
Below is the code I was trying to implement having assumed getEventListeners wasn't just a console function.
// Edit Affirm
(function replaceAffirm() {
if (document.querySelector(".affirm-modal-trigger")) {
const learnMore = document.querySelector("#learn-more");
const modalTrigger = document.querySelector(".affirm-modal-trigger");
const clickHandler = getEventListeners(modalTrigger).click[0].listener;
const substr = learnMore.innerHTML
.toString()
.substring(
learnMore.innerHTML.indexOf("h") + 2,
learnMore.innerHTML.length
);
learnMore.innerHTML = "Easy Financing with " + substr;
modalTrigger.addEventListener("click", clickHandler);
} else {
setTimeout(function () {
replaceAffirm();
}, 250);
}
})();
HTML
<p id="learn-more" class="affirm-as-low-as" data-amount="20000" data-affirm-color="white" data-learnmore-show="true" data-page-type="product">
Starting at
<span class="affirm-ala-price">$68</span>
/mo with
<span class="__affirm-logo __affirm-logo-white __ligature__affirm_full_logo__ __processed">Affirm</span>.
<a class="affirm-modal-trigger" aria-label="Prequalify Now (opens in modal)" href="javascript:void(0)">Prequalify now</a>
</p>
You can't copy event listeners, but it seems because of the structure of your HTML it's more likely that you shouldn't need to re-add it. Instead of editing the HTML and removing the event listener by doing so, the best bet would be to edit around it.
If you want to remove the text nodes you can iterate through childNodes and separate out what should be removed.
Then to rebuild the appropriate text where you want it you can use insertAdjacentText
if (document.querySelector(".affirm-modal-trigger")) {
const learnMore = document.querySelector("#learn-more");
const modalTrigger = document.querySelector(".affirm-modal-trigger");
const children = Array.from(learnMore.childNodes);
children.forEach(child => {
if (child.nodeType === Node.TEXT_NODE || child.matches(".affirm-ala-price")) {
if (learnMore.contains(child)) {
learnMore.removeChild(child);
}
}
});
learnMore.insertAdjacentText("afterBegin", "Easy Financing With ");
modalTrigger.insertAdjacentText("beforeBegin", " ");
} else {
setTimeout(function() {
replaceAffirm();
}, 250);
}
<p id="learn-more" class="affirm-as-low-as" data-amount="20000" data-affirm-color="white" data-learnmore-show="true" data-page-type="product">
Starting at
<span class="affirm-ala-price">$68</span> /mo with
<span class="__affirm-logo __affirm-logo-white __ligature__affirm_full_logo__ __processed">Affirm</span>.
<a class="affirm-modal-trigger" aria-label="Prequalify Now (opens in modal)" href="javascript:void(0)">Prequalify now</a>
</p>
Yes waiting for the Html element to be loaded and checking until it gets loaded is okay and this is one of the correct ways to wait for it.
As per my understanding of your issue, you just have to change the text of the learn-more element.
for that, it is not necessary to copy event listener and then again binding it.
Instead of replacing the whole element just change the text keeping the same element.
So it gets binded with the event listener by default.

jquery if $this has not ClassName do action

I see many answers but none of them seem to be working.
All my buttons have the "Trev" class. I want to check if the clicked class, also contains the "Namdons" class, and if so, do some code. However if not, do some code.
Some code that half works is:
$(".Trev").click
(
function(e)
{
if($(this).hasClass("Namdons"))
{
console.log("Namdons");
}
else
{
console.log("Asdf");
}
e.preventDefault();
}
);
However the "else" condition is not executing.
I've tried:
$(".Trev").click
(
function(e)
{
if($(this).hasClass("Namdons"))
{
console.log("Namdons");
}
if(!$(this).hasClass("Namdons")) //added apostrophe
{
console.log("Asdf");
}
e.preventDefault();
}
);
as per these pages:
How to check if an element does NOT have a specific class?
How do I use hasClass to detect if a class is NOT the class I want?
The "not" command does not apply as I'm only wanting to procure a single element and not select a bunch of them. Explained more on those pages.
HTML:
<div class="Trev Width50" onclick="Button('buttonname')"></div>
and
<button onclick="Namdons()" class="Namdons Trev TextAlignCenter">ButtonTitle</button>
also tried changing the Width50 div to a button:
<button class="Trev Width50" onclick="Button('buttonname')"></button>
There also doesn't seem to be an "elseif" in javascript is that correct?
Thanks.
Since you tag javascript i put example in vanilla js. I leave it for you to translate it to jQuery. I also put notes inside:
const trev = document.querySelectorAll('button.trev'); // get button with .trev style
for (var i=0; i < trev.length; i++) { // itterate them
trev[i].addEventListener('click', function() { // add click event
if (this.classList.contains('Namdons')) {alert('This is .Namdons');} // if it has .Namdons alert it
else {alert('This is NOT .Namdons');} // it not alert that
});
}
<button class="Trev TextAlignCenter">ButtonTitle</button>
<button class="Namdons Trev TextAlignCenter">ButtonTitle</button>
<button class="Trev TextAlignCenter">ButtonTitle</button>
<button class="Namdons Trev TextAlignCenter">ButtonTitle</button>
<button class="Trev TextAlignCenter">ButtonTitle</button>
Read more about classList on MDN

How to change class name of two IDs at same time using js?

I have two IDs in same name ! if any one clicked among them , i need to change the class name of the both IDs. i know we should use ID for single use. Because of my situation(I have two classes for button ) so i have moved to ID.
Her is my code if i click one id that name only changes another one is remains same
<button class="success" id="1" onClick="reply(this.id)"> Added </button>
<button class="success" id="1" onClick="reply(this.id)"> Added </button>
js function
function reply(clicked_id)
{
document.getElementById(clicked_id).setAttribute('class', 'failed');
var el = document.getElementById(clicked_id);
if (el.firstChild.data == "Added")
{
el.firstChild.data = "Add";
}
}
if i use instead of 'class' to id while renaming class which one will be renamed success class or 'class name 1' ?
You can't. Getelementbyid will only return one element. Probably the first one.
Pure JS Is Second Example
My JS Fiddle Example: http://jsfiddle.net/eunzs7rz/
This example will use the class attribute only to perform the switching that you need, its a extremely basic example as do not want to go beyond what is needed... Also i forgot to remove the id's in the JS Fiddle Example.. so just ignore them
THE CSS:
.success {
background-color:#00f;
}
.failed {
background-color:#f00;
}
THE HTML:
<button class="success"> Added </button>
<button class="success"> Added </button>
THE JAVSCRIPT:
$(function() {
$(".success").click(function(){
Reply(this);
});
});
function Reply(oElm) {
$(oElm).attr('class', 'failed');
}
EDIT - PURE JAVASCRIPT VERSION
Sorry, did not think to check the post tags if this was pure JS. But here you go anyway ;)
<style>
.success {
background-color:#00f;
}
.failed {
background-color:#f00;
}
</style>
<button class="success" onclick="Reply(this)"> Added </button>
<button class="success" onclick="Reply(this)"> Added </button>
<script>
function Reply(oElm) {
oElm.className = 'failed';
}
</script>
THE MAIN THING HERE
Once you have the element either by using 'this' or by using 'getElementBy', you can then simply use ".className" to adjust the class attribute of the selected element.
As already explained by others, id is for single use and is quicker than using class or type. So even if you have a group, if only one is ever used.. use an id.
Then you use the object/reference of 'this' from an event on an element, in this case the onclick... that will send that variable to the function / code called.
So using 'this' is a preferred option as it will always reference the element that it is used/called from.
pass elemenet, not it's Id
<button class="success" id="1" onClick="reply(this)"> Added </button>
<button class="success" id="1" onClick="reply(this)"> Added </button>
function reply(elem)
{
$(elem).setAttribute('class', 'failed');
if (elem.firstChild.data == "Added")
{
elem.firstChild.data = "Add";
}
}
the ID attribute must be unique or else it will get the last defined element with that ID.
See this for reference.
Use a class instead of an id. ids are supposed to be unique in a dom tree.
html:
<button class="success" onClick="reply()"> Added </button>
<button class="success" onClick="reply()"> Added </button>
js:
var ary_success = document.querySelectorAll(".success"); // once and forever. If the set of elements changes, move into function `reply`
function reply () {
var elem;
var s_myclasses;
for (var i=0; i < ary_success.length; i++) {
elem = ary_success[i];
s_myclasses = elem.getAttribute('class');
s_myclasses = s_myclasses.replace ( /(success|failed)/g, '' );
s_myclasses = s_myclasses + ' failed';
elem.setAttribute('class', s_myclasses );
if ( elem.firstChild.data.indexOf("Added") !== -1) {
elem.firstChild.data = "Add";
}
}
}
Live Demo here.
Notes
Make sure that you set ary_successin the onload handler or in an appropriately placed script section - at the timeof execution the buttons must be present in the dom ! If in doubt, move it to the start of reply' body.
If you employ jquery, the code simplifies (well...) to:
$(document).ready( function () {
$(".success").on ( 'click', function ( eve ) {
$(".success").removeClass("success").addClass("failed");
$(".success *:first-child:contains('Added')").text(" Add ");
});
});
Updates
Notes, Live Demo
Iterator method changed, every not supported on test platform

Categories

Resources