onclick keeps calling javascript function - javascript

HTML:
<div class="container-fluid">
<div class = "row text-center" align = "middle">
<h2>Pseudo Random Quote Machine</h2>
</div>
<div class = "row text-center" align = "middle">
<div class = "col-xs-12 well message" id = "quoting">
</div>
</div>
<div class = "row text-center" align = "middle">
<div class = "col-xs-12">
<button id = "getMessage" class = "btn btn-primary">
Get Random Quote
</button>
<button id = "tweet" class = btn btn-primary>Tweet this!
</button>
</div>
</div>
</div>
Javascript:
function randomQuotes()
{
//array of quotes
var quotes = [ "\"Operator! Give me the number for 911!\" - Homer J. Simpson", "\"I\'m normally not a praying man, but if you\'re up there, please save me Superman\" - Homer J. Simpson", "\"I\'m in no condition to drive...wait! I shouldn\'t listen to myself, I\'m drunk!\" - Homer J. Simpson", "\"A Degenerate, Am I? Well You Are A Festizo. See, I Can Make Up Words Too, Sister\" - Peter Griffen", "\"Victory Shall Be Mine!\" - Stewie Griffen", "\"He's a spy, blow him up. I'm gonna go take a shit.\" - Rick Sanchez", "\"Ohh yea, you gotta get schwifty. \" - Rick Sanchez", "\"Yo! What up my glip glops!\" - Rick Sanchez", "\"WUBBA LUBBA DUB DUBS!!! \" - Rick Sanchez", "\"Existence is pain to a meeseeks Jerry, and we will do anything to alleviate that pain.\" - Mr. Meeseeks", " \"It\'s morphine time\" - TheRussianBadger"];
var randNum = Math.floor((Math.random() * quotes.length));
document.getElementById("quoting").innerHTML = quotes[randNum];
}
function tweetThis()
{
var tweetToShare = document.getElementById("quoting").innerHTML;
var tweetUrl = 'https://twitter.com/share?text=' + encodeURIComponent(tweetToShare) + ".";
window.open(tweetUrl);
}
document.getElementById("getMessage").onclick = function(){randomQuotes();}
document.getElementById("tweet").onclick = function(){tweetThis();}
Basically, any time I click either of the two buttons the function keeps being called over and over again. Here is the code running in Code Pen
I guess my questions would be:
why would the functions be called more than one time ?
What should I do to either stop the functions from being called multiple times or prevent it from happening in the first place?

functions seem to be called only one time on chrome. Maybe your browser cached an old script: maiusc+f5 to clean

Related

JavaScript shopping cart not functioning correctly

I tried coding a webpage with a functional shopping cart, where you can add items, and see the total money. There's obviously something wrong with my JS, I just don't know what it is since I'm new to JS.
You’re supposed to be able to add items to the cart and see the total amount... I’m unable to add items to cart and see the total. The first function seemed to work but after that none of my JavaScript affected my webpage. I’m assuming I typed something in wrong or I’m missing a few brackets.. etc...
Here's a link to the tutorial I followed
https://www.youtube.com/watch?v=0I1TorcXFP0&list=PLnHJACx3NwAey1IiiYmxFbXxieMYqnBKF&index=5
There is a fair amount of code, I'm just going to put my JS here but the complete code can be found on codepen linked below
https://codepen.io/jlcdevdesign/pen/GRqxBzz
Here's the JS
(function() {
const cartInfo = document.getElementById("cart-info");
const cart = document.getElementById("cart");
cartInfo.addEventListener("click", function() {
cart.classList.toggle("show-cart");
})
})();
(function(){
const cartBtn = document.querySelectorAll(".store-item-icon");
cartBtn.forEach(function(btn){
btn.addEventListener("click", function(event)){
//console.log(event.target);
if(event.target.parentElement.classList("store-item-icon"))
{
let fullPath =
event.target.parentElement.previousElementSibling.src;
let pos = fullPath.indexOf("img") + 3;
let partPath = fullPath.slice(pos);
const item = {};
item.img = 'img-cart${}partPath';
let name = event.target.parentElement.parentElement.nextElementSibling.children[0].children[0].textContent;
item.name = name;
let price = event.target.parentElement.parentElement.nextElementSibling.children[0].children[1].textContent;
let finalPrice = price.slice(1).trim();
item.price = finalPrice;
const cartItem = document.getElementById('div')
cartItem.classList.add('cart-item', 'd-flex', 'justify-content-between', 'text-capitalize', 'my-3');
cartItem.innerHTML = '
<img src="${item.img}" class="img-fluid rounded-circle" id="item-img" alt="">
<div class="item-text">
<p id="cart-item-title" class="font-weight-bold mb-0">${item.name}</p>
<span>$</span>
<span id="cart-item-price" class="cart-item-price" class="mb-0">${item.price}</span>
</div>
<a href="#" id='cart-item-remove' class="cart-item-remove">
<i class="fas fa-trash"></i>
</a>
</div>
';
const cart = deocument.getElementById('cart');
const total = deocument.querySelector('.cart-total-container');
cart.insertBefore(cartItem, total);
alert("item added to the cart");
showTotals();
}
});
})
function showTotals() {
const total = [] {
const items = document.querySelectorAll(".cart-item-price");
items.forEach(function(item){
total.push(parseFloat(item.textContent));
});
}
const totalMoney = total.reduce(function(total,items){
total += item;
return total;
}, 0)
const finalMoney = totalMoney.toFixed(2);
document.getElementById('cart-total').textContent = finalMoney;
document.querySelector('.item-total').textContent = finalMoney;
document.getElementById('item-count').textContent = total.length;
}
})();
In line 53 and 54 you misspelled 'document' with 'deocument' and you also forgot to some braces. And your code is also bit messy, make it harder to read, since you are a beginner this mistakes are common.
Just go through your code carefully correct your spelling and properly put the braces in correct places. And it will solve most of your problems!
I went to your website and found a lot of errors. And your code is also very weird and looks like you just copy pasted and if you really are a begginer or haven't done much projects than you should definetely not do this instead you should try building some simple things like a Rock Paper Scissor game like the one I built when I was a beginner
(simple-rps.vercel.app).
(All the links I have given there are of my old projects you don't have to check them.) And you can press ctrl + u to see the codes then copy the code and paste it into your code editor so that it can get some colours. Then try to read the code and understand how things are working and then try to build your own. And you should not follow that 2 year old tutorial.
Instead you should follow some YouTube channels like Programming with Mosh and Online Tutorials.

How to search for <p> by id for condition in Javascript, and then output text in another <p>?

Sorry, I tried to search for an answer, but I couldn't find exactly what I was looking for.
I am trying to make and webpage using Javascript, and I need some sort of decoder. For example, I have one abbreviation which is "NN", which stands for "Noun Nominative". Another abbreviation is "NA" which stands for "Noun Accusative". Another is "AN" which is "Adjective Nominative". There are many (too many) mixed-and-matched instances of these abbreviations, so I am trying to make a easy way for my Javascript/HTML code to search the whole page for every instance of "N" when it is the part of speech, and then output "Noun" in a different <p> when the abbreviation containing "N" is clicked. I hope this makes sense. So I came up with this:
document.querySelector("div.abbreviation").onclick = parseWord;
function parseWord(event) {
if (event.target.id === 'noun') {
document.getElementById("part-of-speech-decoded").innerHTML = "Noun";
}
}
<div class="abbreviation">
<p id="noun">N</p>
<p id="nominative">N</p>
</div>
<div id="decoder">
<p id="part-of-speech-decoded"></p>
<p id="case-decoded"></p>
</div>
Obviously, it is not correct by a long shot and the formatting is terrible (I am very new to coding), but I hope you can see what I am trying to do. So I want my function to search if p id = "noun", then when the div containing p id="noun" is clicked, I want the word "Noun" to show up in where p id="part-of-speech-decoded" is.
Any help would be appreciated!
You can use event.target.id and capitalise the first letter:
document.querySelector("div.abbreviation").onclick = parseWord;
function parseWord(event) {
var word = event.target.id.charAt(0).toUpperCase() + event.target.id.slice(1);
document.getElementById("part-of-speech-decoded").innerHTML = word;
}
<div class="abbreviation">
<p id="noun">N</p>
<p id="nominative">N</p>
</div>
<p id="part-of-speech-decoded"></p>
To achieve expected result, use below option of creation options Object with 'id' and its value to be displayed
document.querySelector("div.abbreviation").onclick = parseWord;
let abbrArr = {
'noun' : 'Noun',
'nominative' : 'Nominative',
'nn':'Noun Nominative',
'na':'Noun Accusative',
}
function parseWord(event) {
document.getElementById("part-of-speech-decoded").innerHTML = abbrArr[event.target.id];
}
<html>
<body>
<div class="abbreviation" onclick="parseWord(this)">
<p id="noun">N</p>
<p id="nominative">N</p>
<p id="nn">NN</p>
<p id="na">NA</p>
</div>
<div id="decoder">
<p id="part-of-speech-decoded"></p>
<p id="case-decoded"></p>
</div>
</body>
</html>
codepen - https://codepen.io/nagasai/pen/jJvxpY?editors=1010

jQuery single class selector not firing when target has multiple classes

I cannot figure out why my jQuery event handler does not fire in this cirucmstance. I have exhausted my research on Stack Overflow.
HTML:
<div class='pst-header-ad parenting pst-subscribe-motherhood-kit'>
<div class='pst-header-ad-wrap'>
<h3></h3>
<p></p>
</div>
</div>
JS, which does not fire as it should when user clicks element with class pst-subscribe-motherhood-kit:
var subscribeForms = [
{
formclass : "pst-subscribe-motherhood-kit",
formnumber : "151496",
formtitle : "Get Your FREE Mom Kit Now!",
formdescription : "Leave your email below and we'll send you our Mom Kit packed full of printables that will make your mom journey more fun. You'll also receive email updates from me from time to time. Enjoy your Mom Kit!!",
formredirect : "https://pintsizedtreasures.com/landing-pages/mom-bundle-offer/"
}, {
formclass : "pst-subscribe-marriage-kit",
formnumber : "151501",
formtitle : "Get Your FREE Marriage Kit Now!",
formdescription : "Where should we send your Marriage Kit? Leave your email below and you'll receive three printables: a praying for your husband printable, simple, romantic ideas printable and love notes printable. You'll also receive email updates from time to time from me. Enjoy your Marriage Kit!",
formredirect : "https://pintsizedtreasures.com/landing-pages/marriage-bundle-offer/"
}
];
for (var i = 0; i < subscribeForms.length; i++) {
jQuery("." + subscribeForms[i].formclass).click(function(e) {
e.preventDefault();
for (var j = 0; j < subscribeForms.length; j++) {
if (this.className == subscribeForms[j].formclass) {
var formnumber = subscribeForms[j].formnumber;
var formtitle = subscribeForms[j].formtitle;
var formdescription = subscribeForms[j].formdescription;
loadForm(formnumber, formtitle, formdescription);
}
}
});
}
FYI, this loop dynamically loads event handlers from an object of various subscription form data. The selector looks like this in practice:
jQuery(".pst-subscribe-motherhood-kit").click(function(e) { ... }
Research as shown me that when pst-subscribe-motherhood-kit is the element's class value alone, without any other class, jQuery fires as expected.
WORKS: <div class="pst-subscribe-motherhood-kit">Some text</div>
DOES NOT WORK: <div class="my-class pst-subscribe-motherhood-kit">Some text</div>
As always, any help is appreciated.
EDIT: added the object that is iterated through. And, YES, the DOM is loaded before this function is called. It is called in the footer.
You can use let instead of var for creating individual scope in each iteration of the for loop:
var subscribeForms = [{formclass: 'pst-header-ad-wrap'},{formclass: 'pst-header-ad-wrap-2'}];
for (let i = 0; i < subscribeForms.length; i++) {
jQuery("." + subscribeForms[i].formclass).click(function(e) {
e.preventDefault();
console.log(subscribeForms[i].formclass);
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='pst-header-ad parenting pst-subscribe-motherhood-kit'>
<div class='pst-header-ad-wrap'>
pst-header-ad-wrap
<h3></h3>
<p></p>
</div>
<div class='pst-header-ad-wrap-2'>
pst-header-ad-wrap-2
<h3></h3>
<p></p>
</div>
</div>

Trying to split an Alt tag in an Object and then place it all into an Array

I have some products on a page that I need to grab the Alt tag from. I need to turn them into an Object. After that they need to go into an Array.
I was thinking of creating a for loop to loop through the Alt tags, but I am stuck as to how to Split the Alt tag at the pipe '|'.I keep getting an Invalid or unexpected Token. This is code and below that is what I have.
Right at the end I have the jQuery version that works fine, but I want to know the Vanilla Javascript way. As I want to step away from jQuery and learn how to code better in Javascript.
<div class="product col-xl-3 col-lg-3 col-md-4 col-sm-6 col-12" alt="0016|AUX Cable|2.39|5m|Black|2|Tech-Aux">
<a href="/0016/product">
<img class="productImage" src="/static/store/images/products/download-10.jpg">
</a>
<a href="/0016/product">
<h3>AUX Cable</h3>
</a>
<h4 class="price">£2.39</h4>
<input type="button" class="button style_one addToCartOne" value="Add To Cart">
</div>
<div class="product col-xl-3 col-lg-3 col-md-4 col-sm-6 col-12" alt="0015|USB 2 Type A|3.49|10m|Black|300|Tech-Usb">
<a href="/0015/product">
<img class="productImage" src="/static/store/images/products/download_Jb4ucER.jpg">
</a>
<a href="/0015/product">
<h3>USB 2 Type A</h3>
</a>
<h4 class="price">£3.49</h4>
<input type="button" class="button style_one addToCartOne" value="Add To Cart">
</div>
Here is my code:
var products = document.querySelectorAll('.product');
for(var i=0; i<products.length; i++){
products[i].alt.split(“|”);}
Thank you for any advise. Also any help as to where I can look this up in the future would be great as well.
This is the jQuery code that works. And this is what I want to achieve in Javascript:
var products = [];
$.each($(".product"), function(){
var prodOb = {};
var prodDetails = $(this).attr("alt").split("|");
prodOb.id = prodDetails[0];
prodOb.name = prodDetails[1];
prodOb.price = prodDetails[2];
prodOb.brand = "Some Company";
products.push(prodOb)
})
console.log(products)
You're really close, you've done the big that people find tricky (using the DOM instead of jQuery to find the elements).
Two things:
You seem to have stopped in the middle. You have the code using jQuery to do this, and most of that code has nothing to do with jQuery, but you haven't used that code in your attempt.
You're using fancy quotes (“”), but JavaScript requires boring straight up-and-down quotes (").
If we just copy the code from the sample using jQuery into the code you've already written, and fix the quotes, use elements instead of products to conflict with the array you're creating, use a reasonable placement for }, and add a missing semicolon or two, we get:
var products = [];
var elements = document.querySelectorAll('.product');
for (var i = 0; i < elements.length; i++){
var prodDetails = elements[i].getAttribute("alt").split("|");
var prodOb = {};
prodOb.id = prodDetails[0];
prodOb.name = prodDetails[1];
prodOb.price = prodDetails[2];
prodOb.brand = "Some Company";
products.push(prodOb);
}
console.log(products);
Or we can use Array.prototype.map, but for one it isn't a lot more concise:
var products = Array.prototype.map.call(
document.querySelectorAll('.product'),
function(element) {
var prodDetails = elements.getAttribute("alt").split("|");
return {
id: prodDetails[0],
name: prodDetails[1],
price: prodDetails[2],
brand: "Some Company"
};
}
);
console.log(products);
Note: We have to use .getAttribute("alt") instead of .alt because the HTML is invalid. div elements have no alt attribute. I have to admit in the first version of this question I didn't look at the HTML and assumed that it was valid, where the alt attribute is used on an img element (which has the .alt property).

WEBSITE Button that displays a random value from an array Javascript

http://jsfiddle.net/7118zcfc
$scope.ctx.skills = data.result.skills;
$scope.ThingsYouWouldntLearn = [
"Hooray",
"Amount of mushrooms in Mario.",
"How to complete life.",
"How to create an aryan race",
"How paper papers",
"Do do do dododooooooo",
"A Level Physics / things you dont know = this site",
"How to eat 200000 bananas in .23 seconds",
"Why Jeremy Clarkson has curly hair.",
"Starting to run out of things here",
"Why Oli Stratford looks like James May",
];
$scope.ThingsYouWouldntLearn = $scope.ThingsYouWouldntLearn[Math.floor(Math.random()*$scope.ThingsYouWouldntLearn.length)];
}
How do I make it so when the button that is shown on the jsfiddle is clicked one of these statements is put onto the web page in the same font.
There are a lot of things going on here that you'll need to fix. First, it looks like you're using Angular but its not included on the file. If you were going the Angular route you would have something that looks like:
<!-- HTML -->
<button ng-click="getThingToLearn()" type="button">Learn Something</button>
<p>{{thingToLearn}}</p>
// JS
$scope.thingToLearn = '';
$scope.getThingToLearn = function () {
$scope.thingToLearn = $scope.ThingsYouWouldntLearn[Math.floor(Math.random()*$scope.ThingsYouWouldntLearn.length)];
}
If you're doing more of a JavaScript style then you could do something like:
<!-- HTML -->
<button onclick="getThingToLearn()" type="button">Learn Something</button>
<p id="thingToLearn"></p>
// JS
var getThingToLearn = function () {
var thingToLearn = document.getElementById('thingToLearn');
thingToLearn.textContent = ThingsYouWouldntLearn[Math.floor(Math.random()...
};
Hopefully this will help get you in the right direction to start fixing up your code.

Categories

Resources