clicking next page causes my page to slow down exponentially - javascript

this is my first time asking a question on Stack Overflow, any help would be greatly appreciated.
I have a website that displays images from the pixabay api. When i click the button, next, the next page of images is shown. The problem is that with each click, the page slows down at an exponential rate. I know this because i added a success console.log after every completion.
This is the image before:
Image Link Here.
and after
Image Link Here
I think the problem has something to do with the .getJSON call and the for loop inside that call, but I havn't been able to figure it out.
This is the Javascript and HTML
/*
Pixabay api key:
*/
$(document).ready(function () {
var searchValue = "rice"
var defaultPage = 1;
returnPhotos(searchValue, defaultPage);
$("#searchForm").on("submit", function (event) {
//obtain value from user input
searchValue = $("#searchText").val();
returnPhotos(searchValue, defaultPage);
//stops form from submitting to a file
event.preventDefault();
});
});
/*
1. Return Photos from pixabey API
*/
function returnPhotos(searchValue, pageNum) {
let key = "8712269-5b0ee0617ceeb0fd2f84487c3";
let startURL = "https://pixabay.com/api/?key=" + key;
let page = "&page=" + pageNum;
let imagesPerPage = "&per_page=" + 22
let addWH = "&min_width&min_height";
let safeSearch = "&safesearch=true";
let endingURL = "&q=" + searchValue + page + addWH + safeSearch + imagesPerPage;
// activate api and get data
$.getJSON(startURL + endingURL, function (data) {
let image = data.hits;
var imageLength = image.length;
arrayLength = image.length;
if (data) {
let output = ""
for (let x = 0; x < arrayLength; x++) {
//imageObject contains information on each image passed through the array
let imageObject = {
// id: image[x].id,
// pageURL: image[x].pageURL,
// tags: image[x].tags,
// previewURL: image[x].previewURL,
// previewWidth: image[x].previewWidth,
// previewHeight: image[x].previewHeight,
// webformatURL: image[x].webformatURL,
// webformatWidth: image[x].webformatWidth,
// webformatHeight: image[x].webformatHeight,
largeImageURL: image[x].largeImageURL,
// fullHDURL: image[x].fullHDURL,
// views: image[x].views,
// user_id: image[x].user_id,
// user: image[x].user,
// userImageURL: image[x].userImageURL
}
// output this template to the website
output += `
<div class="brick">
<img src="${imageObject.largeImageURL}">
</div>
`
}
$(".masonry").imagesLoaded(function () {
localStorage.clear();
$(".masonry").html(output);
});
console.log("success");
} else {
console.log("Didn't work");
}
getPage(searchValue, pageNum, arrayLength);
// console.log(arrayLength);
});
}
/*
2. INCREASE/Decrease PAGE
*/
function getPage(searchValue, defaultPage, max) {
if (defaultPage <= max + 1) {
$("#pagination2").click(function () {
if (defaultPage <= max) {
defaultPage++;
returnPhotos(searchValue, defaultPage);
console.log(1);
}
$(".pageNumber").html("Page " + defaultPage);
console.log("This is the default page:", defaultPage);
});
}
$("#pagination1").click(function () {
if (defaultPage != 1) {
defaultPage--;
returnPhotos(searchValue, defaultPage);
console.log(1);
}
$(".pageNumber").html("Page " + defaultPage);
console.log("This is the default page:", defaultPage);
});
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv='cache-control' content='no-cache'>
<title>Photo Gallery</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link href="https://fonts.googleapis.com/css?family=Lato:300,400" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="vendors/css/ionicons.min.css">
<link rel="stylesheet" type="text/css" href="vendors/css/animate.min.css">
<link rel="stylesheet" href="resources/css/style.css">
<link href="data:image/x-icon;base64,AAABAAEAICAAAAEAIACoEAAAFgAAACgAAAAgAAAAQAAAAAEAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////+4z/L/pMLv//j6/f///////v7//6vG8P+lwu//5u76/3ek5/+70fP///////7+/v+wyvH/daLn/9Hg9////////////////////////////////////////////////////////////////////////////////////////////1SM4f8kbNn/8PX8///////H2vX/CFnU/4yy6v/W4/j/ClvU/4St6f//////y9z2/xVi1v9QiuD/9Pf9////////////////////////////////////////////////////////////////////////////////////////////VIzh/yRs2f/w9fz/9Pf9/z9+3f9Egd7/8/f9/9bj+P8KW9T/hK3p/+7z+/8ob9n/LXLa//D0/P////////////////////////////////////////////////////////////////////////////////////////////////9UjOH/JGzZ/87e9v+Bqun/CVrU/8zc9v//////1uP4/wpb1P9+qej/ZZfk/xdj1v/J2/X//////////////////////////////////////////////////////////////////////////////////////////////////////1SM4f8kbNn/jrPr/zB02/8RX9X/e6bo//X4/f/W4/j/ClvU/2+e5v8faNj/oL/u////////////////////////////////////////////////////////////////////////////////////////////////////////////VIzh/yRs2f/w9fz/+vz+/6zH8P8EVtP/p8Tv/9bj+P8KW9T/cqDm/yRs2f9ek+P/+fv+//////////////////////////////////////////////////////////////////////////////////////////////////////9UjOH/JGzZ//D1/P///////v7//xJf1f9vnuX/1uP4/wpb1P+ErOn/nb3t/wdY1P+cvO3//v7//////////////////////////////////////////////////////////////////////////////////////////////////1SM4f8kbNn/8PX8//7+///J2/X/BFbT/5G17P/W4/j/ClvU/4St6f/5+/7/RoLe/xZi1v/e6fn/////////////////////////////////////////////////////////////////////////////////////////////////VIzh/yRs2f+au+3/RYLe/xdj1v9bkeL/7/T8/9bk+P8MXNX/ha3q///////W4/f/GmXX/0iE3//1+P3///////////////////////////////////////////////////////////////////////////////////////////+70fP/p8Tv/8fZ9f+jwe//xtn1/8nMz/+Ojo7/vcDG/77S8v/f6fn///////7+/v/P3/b/wNT0//T4/f/////////////////////////////////////////////////////////////////////////////////////////////////////////////////39/f/aWlp/9jY2P9ycnL/29vb/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////v7+/9LS0v/CwsL/9/f3//r6+v9oaGj/vr6+/2xsbP/f39//7Ozs/729vf/j4+P//v7+//////////////////////////////////////////////////////////////////////////////////////////////////////+7u7v/f39//6CgoP+JiYn//v7+/+Hh4f+pqan/29vb//n5+f9mZmb/qqqq/2xsbP/h4eH//////////////////////////////////////////////////////////////////////////////////////////////////////6urq/+ampr/0NDQ/3d3d//9/f3/rMfw/9nl+P+zzPH/9vb2/2RkZP/c3Nz/eXl5/9jY2P//////////////////////////////////////////////////////////////////////////////////////////////////////9/f3/5mZmf+Li4v/5OTk/+Hr+f+Msuv/ydv1/42y6//u9Pz/ysrK/4aGhv+0tLT//Pz8/////////////////////////////////////////////////////////////////////////////////////////////////////////////Pz8//j4+P/4+v3/XJHi/+Xt+v//////irHq/7nQ8//+/v7/9fX1//7+/v///////////////////////////////////////////////////////////////////////////////////////////////////////////9nZ2f9ra2v/b29v/7e3t//k7fr/bp3l/6C/7v+xyvH//Pz8/42Njf91dXX/eHh4//Dw8P//////////////////////////////////////////////////////////////////////////////////////////////////////o6Oj/7a2tv/t7e3/bW1t//b4/P/U4vf/4Or5/+nw+//z8/P/ZmZm//b29v+FhYX/09PT///////////////////////////////////////////////////////////////////////////////////////////////////////g4OD/eXl5/3l5ef+/v7///Pz8/6Kiov+FhYX/vr6+//39/f+Xl5f/gYGB/4WFhf/z8/P////////////////////////////////////////////////////////////////////////////////////////////////////////////4+Pj/9PT0///////Ozs7/hoaG/97e3v9tbW3/6+vr//39/f/w8PD//f39/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////+fn5/9vb2//mpqa/3d3d//09PT//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////+Dg4P/IyMj/7e3t////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
rel="icon" type="image/x-icon" />
</head>
<body>
<div class="container">
<nav class="nav">
<h1>
<a class="brand-logo" href="index.html">Photo Gallery</a>
</h1>
</nav>
<!-- IMAGE search box-->
<div class="header">
<div>
<h3 class="text-center">Search For Any Image</h3>
<form id="searchForm" autocomplete="off">
<input type="text" class="form-control" id="searchText" placeholder="Search Image Here">
</form>
<h4 class="from-pixabay">Images from Pixabay</h4>
</div>
<div class="paginations">
Previous
<p class="pageNumber">Page 1</p>
Next
</div>
</div>
<!-- IMAGES GO HERE -->
<div class="masonry">
</div>
</div>
<!-- Pre-footer -->
<!--SECTION Contact-Footer -->
<footer class="footer-section" id="contact">
<div class="rows-container">
<div class="footer-con">
<div class="homepage-link">
<a href="http://rkdevelopment.org" target="_blank">
<h3>Rkdevelopment.org</h3>
</a>
</div>
<ul class="social-list center">
<li>
<a href="https://github.com/RexfordK" target="_blank">
<i class="ion-social-github"></i>
</a>
</li>
<li>
<a href="https://www.linkedin.com/in/rexford-koduah" target="_blank">
<i class="ion-social-linkedin"></i>
</a>
</li>
<li>
<a href="https://www.freecodecamp.org/rexfordk" target="_blank">
<i class="ion-fireball"></i>
</a>
</li>
</ul>
<p>Copyright © 2018 by Rexford Koduah. All rights reserved.</p>
</div>
</div>
</div>
</footer>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script src="https://unpkg.com/imagesloaded#4/imagesloaded.pkgd.min.js"></script>
<script src="resources/js/main.js"></script>
</body>
</html>

Every time you call getPage, you are adding another $("#pagination2").click handler. Which means the first time you click it, you do one ajax request. The second time you do two, the third time you do three, etc. You need to either only setup the click handler once, and make sure your logic reflects that, or clear the old one each time with $("#pagination2").off('click').click(

Related

Webpage eventlistener and script section not running

Trying to make a basic webpage where you can type a message for it to be displayed on the website. However, the script section of my website does not seem to work.
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<script>
document.addEventListener('DOMContentLoaded', function()
{
let submit = document.querySelector('#submit');
submit.addEventListener('click',function()
{
let questions = document.querySelectorAll('.question');
let input = document.querySelector('input');
for (let i =0; i< questions.length; i++)
{
if questions[i].innerHTML == ""
{
questions[i].innerHTML = 'a';
}
else
{
continue;
}
}
});
function myfunction()
{
alert('test');
}
});
</script>
<title>Write A Message!</title>
</head>
<body class="p-3 mb-2 bg-secondary text-white">
<h1>How to write a message</h1>
<hr>
<p>Type a Message into the textbox below to display a public letter!</p>
<div>
<input type = 'text'>
<button id = 'submit'>Type a message!</button>
</div>
<div>
<h1>Message 1!</h1>
<hr>
<p class = 'question'></p>
<h2>Message 2!</h2>
<hr>
<p class = 'question'></p>
<h3>Message 3!</h3>
<hr>
<p class = 'question'></p>
<button onclick = 'myfunction()'>test</button>
</div>
</body>
</html>
I tried adding a button that would display an alert as well but it does not run as well when clicked.
First, javscript that contains listener/reference to DOM elements is better to include in the end on body, avoid putting in head.
Second, myfunction() is not accessible bebcause you included it under DOMContentLoaded. It should be outside of the listener (global scope).
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<title>Write A Message!</title>
</head>
<body class="p-3 mb-2 bg-secondary text-white">
<h1>How to write a message</h1>
<hr>
<p>Type a Message into the textbox below to display a public letter!</p>
<div>
<input type='text'>
<button id='submit'>Type a message!</button>
</div>
<div>
<h1>Message 1!</h1>
<hr>
<p class='question'></p>
<h2>Message 2!</h2>
<hr>
<p class='question'></p>
<h3>Message 3!</h3>
<hr>
<p class='question'></p>
<button onclick='myfunction()'>test</button>
</div>
<script>
document.addEventListener('DOMContentLoaded', function(){
let submit = document.querySelector('#submit');
submit.addEventListener('click',function(){
let questions = document.querySelectorAll('.question');
let input = document.querySelector('input');
for (let i =0; i< questions.length; i++){
if (questions[i].innerHTML == ""){
questions[i].innerHTML = 'a';
} else {
continue;
}
}
});
});
function myfunction() {
alert('test');
}
</script>
</body>
</html>

Making JS items links to other pages

So I'm using some code from CodePen to make my nagivation buttons as well as my cursor. All of the button creation seems to happen within the JavaScript file, however. I want to add links to each of the buttons to redirect to separate HTML pages. I'm hoping to find a way to do it within the JS file, but all solutions are welcome!
Also, I'm aware this may be a very silly question but I'm still new to web development so bear with me! I'm going to post snippets of the HTML and JS files. I can't include the CSS snippet because the file is much too large.
The website is ryanhursh.xyz for reference of how it's built.
const app = Vue.createApp({
data() {
return {
items: [{ page: "about" }, { page: "works" }, { page: "contact" }],
cursorPosX: 960,
cursorPosY: 540,
cursorFollowActiveBuffer: 16,
buttonHoverFlag: false
};
},
mounted() {
this.cursorPointer = this.$refs.cursorPointer;
this.cursorFollow = this.$refs.cursorFollow;
this.button = document.querySelectorAll(".js-button");
window.addEventListener("mousemove", (e) => {
if (this.buttonHoverFlag === true) {
return;
}
this.mouseMoveCursor(this.cursorPointer, e, 1.0);
this.mouseMoveCursor(this.cursorFollow, e, 1.0);
});
this.onMouseMove();
this.onMouseLeave();
},
methods: {
mouseMoveCursor(element, event, friction) {
this.cursorPosX += (event.clientX - this.cursorPosX) * friction;
this.cursorPosY += (event.clientY - this.cursorPosY) * friction;
element.style.transform = `translate(${
this.cursorPosX - element.clientWidth / 2
}px,${this.cursorPosY - element.clientHeight / 2}px)`;
},
onMouseMove() {
for (let i = 0; i < this.button.length; i++) {
this.button[i].addEventListener("mousemove", (e) => {
this.buttonHoverFlag = true;
this.cursorPointer.style.backgroundColor = "transparent";
this.cursorFollow.style.transform = `translate(${
e.target.getBoundingClientRect().left -
this.cursorFollowActiveBuffer
}px,${
e.target.getBoundingClientRect().top - this.cursorFollowActiveBuffer
}px)`;
this.cursorFollow.style.width =
e.target.getBoundingClientRect().width + "px";
this.cursorFollow.style.height =
e.target.getBoundingClientRect().height + "px";
this.cursorFollow.style.padding =
this.cursorFollowActiveBuffer + "px";
this.cursorFollow.style.borderRadius = 0;
});
}
},
onMouseLeave() {
for (let i = 0; i < this.button.length; i++) {
this.button[i].addEventListener("mouseleave", () => {
this.buttonHoverFlag = false;
this.cursorPointer.style.backgroundColor = "#fff";
this.cursorFollow.style.width = 10 + "px";
this.cursorFollow.style.height = 10 + "px";
this.cursorFollow.style.padding = 32 + "px";
this.cursorFollow.style.borderRadius = "100%";
});
}
}
}
});
app.mount("#app");
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>Ryan R. Hursh</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js" type="text/javascript"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<link rel="stylesheet" href="./style.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>
<div id="app">
<header class="header">
<nav class="header__nav">
<ul class="header__list">
<li v-for="item in items" class="header__item"><a class="button js-button">{{ item.page }}</a></li>
</ul>
</nav>
</header>
<div class="cursor">
<div class="cursor__pointer" ref="cursorPointer"></div>
<div class="cursor__follow" ref="cursorFollow"></div>
</div>
</div>
</head>
<!-- content-->
<body>
<div class="firefly"></div>
<div class="firefly"></div>
<div class="firefly"></div>
<div class="firefly"></div>
<div class="firefly"></div>
<div class="firefly"></div>
<div class="firefly"></div>
<div class="firefly"></div>
<div class="firefly"></div>
<div class="firefly"></div>
<div class="firefly"></div>
<div class="firefly"></div>
<div class="firefly"></div>
<div class="firefly"></div>
<div class="firefly"></div>
<link href='https://fonts.googleapis.com/css?family=Lato:300,400,700' rel='stylesheet' type='text/css'>
<!--
<div id='stars'></div>
<div id='stars2'></div>
<div id='stars3'></div>
-->
<div id='title'>
<span>
Ryan R. Hursh
</span>
<br>
<span>
HTML, CSS, JavaScript
</span>
</div>
<!-- end content-->
<!-- embedded scripts -->
<script src='//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src='https://unpkg.com/vue#next'></script>
<script src="./script.js"></script>
</script>
<!-- end scripts -->
</body>
</html>
For buttons that take you to other HTML pages, you can just do:
Html:
<button id="whateveruwant" onclick="whateverfunctionuwant()">text here</button>
The JS is also simple:
function whateverfunctionuwant() {
location.href = "whateverhtmlpageuwant.html"
}
So then the button will direct you to a different HTML page. If Location doesn't work, try Window.href. The Id is for CSS purposes if you wanted to change its appearance and location of it. If you still don't understand, then just go to W3 Schools and search for how to make a button change to another HTML page. (BTW JUST CHANGE THE STUFF THAT I LEFT AS WHATEVER FUNCTION U WANT TO WHAT YOU WANT)

How to correctly search an JavaScript object and push it from one js file into an array of another js file?

I am learning to implement JS dynamic pages.
I have created 2 JavaScript files to display data dynamically in HTML. One JavaScript file data.js has two arrays of objects (catalogArray and myCartArry) and another JavaScript file (function.js) has a functionchargerArticles() which loads those objects. then creates HTML elements and display items (catalog) on HTML page.
The functionality I want to implement is:
When user will press 'Add to Cart' button, the oneClick(), it gets position of ith object (requested), this event should invoke addToCart(pos) function. (requesting to push certain object(item) into myCartArry from catalogArray)
addToCart(pos) will check (by obj name) if certain requested object is already exists in myCartArryor not, using searchInCart(name) function. (searc/hInCart(catalogArray[pos].name))
and on this basis if searchInCart() returns false(the object's name is not found into myCartArray[]), then object will be pushed into myCartArry[]of data.js.
I have written below code to do this but its not functioning, onclick event is not doing anything. Alsoother functionis not working. Please help me resolving this as data(object) is not being searched and inserted correctly. Where am I doing mistakes? Thank you.
// data.js
var catalogArray = [
{
code: 100,
name: "T Shirt c100",
desc: "Lorem ipsum, or lipsum as it is sometimes known as",
price: 150,
image: "./images/img100.jpg"
},
{
code:101 ,
name: "T Shirt c101",
desc: "Lorem ipsum, or lipsum as it is sometimes known as",
price: 250,
image: "./images/img101.jpg"
},
];
var myCartArray = [
{
name: "T Shirt c100",
price: 150,
qte:2,
TotalPrice:150,
}
];
//function.js
// var catalog=catalogArray;
function chargerArticles() {
var myShoppingCart = [];
// var articleCmd = {}; //array of objects
// articleCmd.name="aaaa";
// articleCmd.price="aaaa";
// articleCmd.qte="5";
// // articleCmd.priceTotal="567";
// myCartArray.push(articleCmd);
var articles = document.getElementById("content");
for (var i =0; i < catalogArray.length; i++) {
//Product div
var article = document.createElement("div");
article.setAttribute("class", "as");
//Unique id
article.id=i+"-article";
//Command Input Area
var zoneCmd=document.createElement("div");
zoneCmd.setAttribute("class", "border");
var inputCmd=document.createElement("input");
inputCmd.setAttribute("class", "qty");
//inputcmd unique id
inputCmd.id=i+"-qte";
//inputcmd all properties
inputCmd.type="number";
inputCmd.value=0;
inputCmd.min=0;
inputCmd.max=5;
inputCmd.addEventListener('keydown', e => {
console.log('blocked keydown e.key:', e.key);
// prevent default input response
e.preventDefault();
});
zoneCmd.appendChild(inputCmd); //child 1
//Button of add to cart
var button=document.createElement("BUTTON");
button.setAttribute("class", "cartBtn hvr-underline-btn");
// button.innerHtml = '<i class="fa fa-shopping-cart fa-3x" aria-hidden="true" style="font-size:36px"></i> Lägg till i kundkorgen';
// button.setAttribute("class","sourceText fa fa-trash-o");
// $(button.sourceText).append('<i class="fa fa-trash-o"></i>');
button.innerHTML = " ADD TO CART";
//Button unique id
button.id=i+"-cmd";
button.onclick=function()
{
var item=this.getAttribute("id");
var pos=item.substring(0,1);
// document.getElementById("1234").innerHTML = "Hello World";
addToCart(pos);
}
zoneCmd.appendChild(button); //child 2
//zoneCmd child of article element
article.appendChild(zoneCmd);
//finally article as a child of articles
articles.appendChild(article);
}
}
function searchInCart(name) //T-Shirt
{
myShoppingCart=myCartArray;
var name1=name;
var stop=0;
for (var i =0; i < myShoppingCart.length && stop==0; i++) {
if(myShoppingCart[i].name==name1)
{
stop=1;
console.log("Hello wooooorld!");
return true;
}
else{
return false;
}
}
}
function addToCart(pos)
{
if(searchInCart(catalogArray[pos].name))
{
alert("Already Exists!"); // display string message
}
else
{
var ident=pos+"-qte";
var quatity= document.getElementById("ident").value;
if(quatity>0)
{
var articleCmd = {}; //array of objects
articleCmd.name=catalogArray[pos].name;
articleCmd.price=catalogArray[pos].price;
articleCmd.qte=quatity;
articleCmd.priceTotal=articleCmd.price*articleCmd.qte;
myCartArray.push(articleCmd);
}
else
{
// alert
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Daily Shop | Product</title>
<link rel="stylesheet" type="text/css" href="css/mystyle.css">
<link href="css/font-awesome.css" rel="stylesheet">
<link href="css/style1.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="css/slick.css">
<link id="switcher" href="css/color/theme.css" rel="stylesheet">
<link href="css/sequence-theme.modern-slide-in.css" rel="stylesheet" media="all">
<!-- Google Font -->
<link href='https://fonts.googleapis.com/css?family=Lato' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Raleway' rel='stylesheet' type='text/css'>
</head>
<!-- !Important notice -->
<!-- Only for product page body tag have to added .productPage class -->
<body class="productPage" onload="chargerArticles()">
<!-- SCROLL TOP BUTTON -->
<a class="scrollToTop" href="#"><i class="fa fa-chevron-up"></i></a>
<!-- END SCROLL TOP BUTTON -->
<p id="1234">aaaa</p>
<div class="mainDivClass">
<section id="aa-product-category">
<div class="container">
<div class="row">
<div class="">
<div class="aa-product-catg-content">
<div class="aa-product-catg-head">
<div class="aa-product-catg-head-left">
<form action="" class="aa-sort-form">
<label for="">Sort by</label>
<select name="">
<option value="1" selected="Default">Default</option>
<option value="2">Name</option>
<option value="3">Price</option>
<option value="4">Date</option>
</select>
</form>
<form action="" class="aa-show-form">
<label for="">Show</label>
<select name="">
<option value="1" selected="12">12</option>
<option value="2">24</option>
<option value="3">36</option>
</select>
</form>
</div>
<div class="aa-product-catg-head-right">
<a id="grid-catg" href="#"><span class="fa fa-th"></span></a>
<a id="list-catg" href="#"><span class="fa fa-list"></span></a>
</div>
</div>
</section>
<section id="content">
</section>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="js/function.js"></script>
<script src="js/data.js"></script>
</body>
</html>

how to fix this? use a function based on the target of the button clicked

How can i code my calc function so that it subtracts 1 to the main counter if clicked on the "lower count" button or add 1 if clicked on the "add counter".
I could use separate functions for each one, but im trying to learn how to create a single functions that will work for both scenarios based on the value of the button clicked.
The issue is 100% in the if else statement line 17.
Code below.
(function () {
//create a main counter to store the calculations
let value = 0;
//variables to use as selectors
const counter = document.getElementById("counter");
const lower = document.querySelector(".prevBtn");
const upper = document.querySelector(".nextBtn");
//set the html text to the counter value
counter.textContent = value;
// function to add or subtract value
let calc = function (event) {
//here is my problem the target value please help
let target = event.target;
if (target.classList.contains("Prevbtn")) {
value -= 1;
counter.textContent = value;
} else {
value += 1;
counter.textContent = value;
}
};
//add functionality to the buttons
lower.addEventListener("click", calc);
upper.addEventListener("click", calc);
})();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<!-- bootstrap css -->
<link rel="stylesheet" href="css/bootstrap.min.css" />
<!-- main css -->
<link rel="stylesheet" href="css/main.css" />
<!-- google fonts -->
<link
href="https://fonts.googleapis.com/css?family=Courgette"
rel="stylesheet"
/>
<!-- font awesome -->
<script src="js/all.js"></script>
<title>Counter Project</title>
<style></style>
</head>
<body>
<div class="container">
<div class="row max-height align-items-center">
<div class="col-10 mx-auto col-md-6 text-center main-container p-5">
<h1 class="text-uppercase">counter</h1>
<h1 id="counter"></h1>
<div class="btn-container d-flex justify-content-around flex-wrap">
<button class="btn counterBtn prevBtn text-uppercase m-2">
lower count
</button>
<button class="btn counterBtn nextBtn text-uppercase m-2">
add count
</button>
</div>
</div>
</div>
</div>
<!-- jquery -->
<script src="js/jquery-3.3.1.min.js"></script>
<!-- bootstrap js -->
<script src="js/bootstrap.bundle.min.js"></script>
<!-- script js -->
<script src="js/app.js"></script>
</body>
</html>
typo, prevBtn is not the same as Prevbtn, fix that and it works
answer given by user CertainPerformance

Trouble adding 'active' class to entire list of <p>, only adds it to first 7 items

Problem
I have a small navigation containing seven pets names, a scroll listener is checking to see how far a person scrolls down the page. It then and adds a class of active to <p class="nameNav> when the person scrolls to that pet and points to expanded adoption information.
However, this active class is only being added to the first seven items in the navigation, not all forty and I'm wondering if it's because of problems with the scroll listener or how var index= has been declared.
JSFiddle: http://jsfiddle.net/jja9vecc/
scripts.js
$(function(){
// Deals with loading the pets
var public_spreadsheet_url = "https://docs.google.com/spreadsheets/d/1TOIGfwdi1GhV7BMhc5fH481icHi7zEEyXZZx3Y5J61I/pubhtml";
$(document).ready( function() {
Tabletop.init( { key: public_spreadsheet_url,
callback: showInfo,
parseNumbers: true } );
});
function showInfo(data, tabletop) {
var source = $("#pets").html();
var template = Handlebars.compile(source);
// The actual name of the sheet, not entire .csv
$.each(tabletop.sheets("Pets").all(), function(i, fact) {
var html = template(fact);
// You need an element with this id or class in your HTML
$("#pets-list").append(html);
$('.container').eq(i).addClass(data.Pets.elements[i]);
// console.log(data.Pets.elements[i].name);
// Deals with the left menu
$(".nameNav").click(function(){
$(".nameNav").removeClass("active");
$(this).toggleClass("active");
});
$(window).scroll(function(){
var $pets = $('.pet').map(function(_, i){
return $(i).offset().top;
});
var scroll = $(window).scrollTop();
var index = $pets.filter(function(i, v){ if(v < scroll) return i; }).length;
$(".nameNav").removeClass("active");
$(".nameNav").eq(index).addClass("active");
// console.log(index);
if (index >= 7 && index <= 13) {
$(".first").html(data.Pets.elements[7].name);
$(".second").html(data.Pets.elements[8].name);
$(".third").html(data.Pets.elements[9].name);
$(".fourth").html(data.Pets.elements[10].name);
$(".fifth").html(data.Pets.elements[11].name);
$(".sixth").html(data.Pets.elements[12].name);
$(".seventh").html(data.Pets.elements[13].name);
} else if (index >= 14 && index <= 20) {
$(".first").html(data.Pets.elements[14].name);
$(".second").html(data.Pets.elements[15].name);
$(".third").html(data.Pets.elements[16].name);
$(".fourth").html(data.Pets.elements[17].name);
$(".fifth").html(data.Pets.elements[18].name);
$(".sixth").html(data.Pets.elements[19].name);
$(".seventh").html(data.Pets.elements[20].name);
} else if (index >= 21 && index <= 27) {
$(".first").html(data.Pets.elements[21].name);
$(".second").html(data.Pets.elements[22].name);
$(".third").html(data.Pets.elements[23].name);
$(".fourth").html(data.Pets.elements[24].name);
$(".fifth").html(data.Pets.elements[25].name);
$(".sixth").html(data.Pets.elements[26].name);
$(".seventh").html(data.Pets.elements[27].name);
} else if (index >= 28 && index <= 34) {
$(".first").html(data.Pets.elements[28].name);
$(".second").html(data.Pets.elements[29].name);
$(".third").html(data.Pets.elements[30].name);
$(".fourth").html(data.Pets.elements[31].name);
$(".fifth").html(data.Pets.elements[32].name);
$(".sixth").html(data.Pets.elements[33].name);
$(".seventh").html(data.Pets.elements[34].name);
} else if (index >= 35 && index <= 38) {
$(".first").html(data.Pets.elements[35].name);
$(".second").html(data.Pets.elements[36].name);
$(".third").html(data.Pets.elements[37].name);
$(".fourth").html(data.Pets.elements[38].name);
} else {
$(".first").html(data.Pets.elements[0].name);
$(".second").html(data.Pets.elements[1].name);
$(".third").html(data.Pets.elements[2].name);
$(".fourth").html(data.Pets.elements[3].name);
$(".fifth").html(data.Pets.elements[4].name);
$(".sixth").html(data.Pets.elements[5].name);
$(".seventh").html(data.Pets.elements[6].name);
}
if (index >= 35 && index <= 38) {
$(".fifth").addClass("hide");
$(".sixth").addClass("hide");
$(".seventh").addClass("hide");
} else {
$(".fifth").removeClass("hide");
$(".sixth").removeClass("hide");
$(".seventh").removeClass("hide");
}
});
});
};
});
index.html
<!DOCTYPE html>
<html lang="en" class="no-js">
<head>
<meta charset="UTF-8">
<title>Name of Website</title>
<meta name="description" content="">
<meta name="author" content="">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="assets/css/style.css">
<link href='http://fonts.googleapis.com/css?family=Lato:300,400,700' rel='stylesheet' type='text/css'>
<!-- <link rel="icon" type="image/png" href="assets/img/favicon.ico"> -->
</head>
<body>
<nav class="vertical">
<div class="rectangle">
<p class="nameNav first active">Adonis</p>
<p class="nameNav second">Billy</p>
<p class="nameNav third">Comet</p>
<p class="nameNav fourth">Dexter</p>
<p class="nameNav fifth">Evan</p>
<p class="nameNav sixth">Fritz</p>
<p class="nameNav seventh">Grommit</p>
</div><!-- /.rectangle -->
</nav>
<main>
<div id="pets-list"></div>
</main>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="assets/js/scripts.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tabletop.js/1.3.5/tabletop.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.0/handlebars.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.js"></script>
<!-- This is where the template for facts goes -->
<script id="pets" type="text/x-handlebars-template">
<div class="container">
<div class="pet">
<p class="nameTitle" id="{{name}}">{{name}}</p>
<img src="{{image}}" alt="">
<p class="breed">{{breed}}</p>
<p class="description">{{description}}</p>
<p class="cost">{{cost}}</p>
<hr>
</div><!-- /.pet -->
</div><!-- /.container -->
</script>
</body>
</html>

Categories